Question

I have a function to generate the key using PBE, and I have searched on internet and find out the following code.

class PBE{
    public PBE(String pw) {
        this.password = pw;
    }
    public SecretKey generateKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
        // make password
        PBEKeySpec keySpec = new PBEKeySpec(this.password.toCharArray(),this.salt,20);
        // create key instance
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        // generate key
        SecretKey key = keyFactory.generateSecret(keySpec);
        return key;
    }
}

And I use this function as

PBE myPBE = new PBE("102a102s");
SecretKey myKey = myPBE.generateKey();
System.out.println(myKey.getEncoded());

However, the output is as the same as my input password. I don't know why

Was it helpful?

Solution

According to documentation, getEncoded() returns

an external encoded form for the key used when a standard representation of the key is needed outside the Java Virtual Machine, as when transmitting the key to some other party

Since you use password-based encryption, external form of the password is the password itself, therefore this behavour is correct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top