2011-11-15 74 views
1

我有以下測試代碼來加密和解密字符串。如果我在test()中省去了我的密鑰的包裝和解包代碼,但是當我試圖包裝我的密鑰,然後再次解包並將其用於解密時,它工作正常,但它失敗,我不會得到「測試「返回爲解密後的字符串,而是」 J 「。包裝和解包加密密鑰失敗(javax.crypto)

有沒有人看到我正在做的包裝和解包的錯誤?謝謝。

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

回答

3

它看起來像你給不同的四cipher.init(Cipher.ENCRYPT_MODE,...)和cipher.init(Cipher.DECRYPT_MODE,...)通過調用generateIV()兩次。

+0

謝謝,就是這樣。我只是沒有看到它。 –