使用JCE / JCA从主密钥中获取秘密

时间:2010-12-22 20:30:28

标签: java cryptography encryption-symmetric pkcs#5

有人能指出我正确的方向吗?

我想使用JCE / JCA从主密钥中获取新密钥,我该如何实现?

问候。

1 个答案:

答案 0 :(得分:5)

JCA提供标准的基于密码的密钥派生函数,如PKCS#5 v2.0RFC 2898中定义的PBKDF2。该算法从主密钥(密码)创建一些随机材料,以便生成适合于给定密码的密钥。

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);
}