1

我有以下测试代码来加密和解密字符串。如果我在 test() 中省略了我的密钥的包装和解包代码,它工作正常,但是当我尝试包装我的密钥,然后再次解包并将其用于解密时,它会失败并且我没有得到“测试”作为结果解密字符串返回,但改为“�J��”。

有人看到我在包装和展开时出现的错误吗?谢谢。

private static void test() throws Exception {

    // create wrap key
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AESWrap");
    keyGenerator.init(256);
    Key wrapKey = keyGenerator.generateKey();

    SecretKey key = generateKey(PASSPHRASE);
    Cipher cipher;

    // wrap key
    cipher = Cipher.getInstance("AESWrap");
    cipher.init(Cipher.WRAP_MODE, wrapKey);
    byte[] wrappedKeyBytes = cipher.wrap(key);

    // unwrap key again
    cipher.init(Cipher.UNWRAP_MODE, wrapKey);
    key = (SecretKey)cipher.unwrap( wrappedKeyBytes, "AES/CTR/NOPADDING", Cipher.SECRET_KEY);

    // encrypt
    cipher = Cipher.getInstance("AES/CTR/NOPADDING");
    cipher.init(Cipher.ENCRYPT_MODE, key, generateIV(cipher), random);
    byte[] b = cipher.doFinal("Test".toString().getBytes());

    // decrypt
    cipher = Cipher.getInstance("AES/CTR/NOPADDING");
    cipher.init(Cipher.DECRYPT_MODE, key, generateIV(cipher), random);
    b = cipher.doFinal(b);

    System.out.println(new String(b));  
    // should output "Test", but outputs �J�� if wrapping/unwrapping

}

以及上面代码中调用的两个辅助方法:

private static IvParameterSpec generateIV(Cipher cipher) throws Exception {
    byte [] ivBytes = new byte[cipher.getBlockSize()];
    random.nextBytes(ivBytes);    // random = new SecureRandom();
    return new IvParameterSpec(ivBytes);
}

private static SecretKey generateKey(String passphrase) throws Exception {
    PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray(), salt.getBytes(), iterations, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBE_ALGORITHM); //"PBEWITHSHA256AND256BITAES-CBC-BC"
    return keyFactory.generateSecret(keySpec);
}
4

1 回答 1

4

看起来您通过调用 generateIV() 两次为 cipher.init(Cipher.ENCRYPT_MODE, ...) 和 cipher.init(Cipher.DECRYPT_MODE, ...) 提供了不同的 IV。

于 2011-11-15T20:28:49.723 回答