2011-11-15 6 views
1

文字列を暗号化および復号化するための次のテストコードがあります。私のキーのラップとアンラップコードをtest()で取り除いても、うまくいきますが、私のキーをラップしてからもう一度ラップして解読に使うと、失敗して "結果の復号化された文字列として "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 

} 

そして、上記のコードで呼ばれている2つのヘルパーメソッド:

あなたがcipher.initするために、異なるIVを与えているように見えます
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.ENCRYPT_MODEを、...) Generator()を2回呼び出してcipher.init(Cipher.DECRYPT_MODE、...)を呼び出します。

+0

ありがとうございました。私は単にそれを見ていない。 –

関連する問題