Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

java - Deriving a secret from a master key using JCE/JCA

Can some point me in the right direction?

I'd like to use JCE/JCA to derive a new key from a master secret key, How can I achieve this?

Regards.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The JCA provides standard password-based key derivation functions like PBKDF2 defined in PKCS#5 v2.0 and RFC 2898. This algorithm creates some random material from a master secret (a password) in order to generate a key suitable for a given cipher.

public byte[] deriveKey(String password, byte[] salt, int keyLen) {
    SecretKeyFactory kf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec specs = new PBEKeySpec(password.toCharArray(), salt, 1024, keyLen);
    SecretKey key = kf.generateSecret(specs);
    return key.getEncoded();
}

public byte[] encrypt(String password, byte[] plaintext) {
    byte[] salt = new byte[64];
    Random rnd = new Random();
    rnd.nextByte(salt);
    byte[] data = deriveKey(password, salt, 192);
    SecretKey desKey = SecretKeyFactory.getInstance("DESede").generateSecret(new DESedeKeySpec(data));
    Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, desKey);
    return cipher.doFinal(plaintext);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...