2012-11-16 54 views
2

我试图将BouncyCastle特定的实现转换为通用的实现,但由于我仍在努力处理基础知识,所以我很难做到。使用密钥和iv的Java AES块解密

这是以前的BC代码的工作原理:

public int decrypt(SecurityToken token, byte[] dataToDecrypt, int inputOffset, 
     int inputLength, byte[] output, int outputOffset) { 
    // Make new RijndaelEngine 
    RijndaelEngine engine = new RijndaelEngine(128); 

    // Make CBC blockcipher 
    BufferedBlockCipher bbc = new BufferedBlockCipher(
     new CBCBlockCipher(engine)); 

    // find right decryption key and right initialization vector 
    KeyParameter secret = new KeyParameter(
     token.getRemoteEncryptingKey()); 
    byte[] iv = token.getRemoteInitializationVector(); 

    // initialize cipher for decryption purposes 
    bbc.init(false, new ParametersWithIV(secret, iv)); 
    decryptedBytes = bbc.processBytes(dataToDecrypt, inputOffset, 
     inputLength, output, outputOffset); 

    decryptedBytes += bbc.doFinal(output, outputOffset+decryptedBytes); 
    return decryptedBytes; 
} 

,这是我谦虚的尝试至今:

SecretKeySpec spec = new SecretKeySpec(
    token.getRemoteEncryptingKey(), 
    "AES"); 

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
cipher.init(Cipher.DECRYPT_MODE, spec, new IvParameterSpec(token.getRemoteInitializationVector())); 
decryptedBytes = cipher.update(dataToDecrypt, inputOffset, 
    inputLength, output, outputOffset); 
decryptedBytes += cipher.doFinal(output, outputOffset+decryptedBytes); 
return decryptedBytes; 

这给

javax.crypto.BadPaddingException: Given final block not properly padded 

,在这里输入功能:

decrypt: dataToDecrypt.length=1088 inputOffset=0 inputLength=1088 output.length=16384 outputOffset=1180 
decrypt: token.getRemoteEncryptingKey()=lBjgFjfR3IilCyT5AqRnXQ== 
decrypt: token.getRemoteInitializationVector()=0JFEdkuW6pMo0cwfKdZa3w== 

我错过了什么?

E:输入数据

回答

1

通常BadPaddingException意味着要么:

  • 原始明文不使用你所建议的填充算法填充。所以当数据被加密时,PKCS#5可能不会被使用。

  • 您使用了错误的密钥进行解密。这导致解密完成时填充看起来不正确。

希望你可以看看你的环境,并找出这些是否可能吗?看着你的BouncyCastle代码,我会假设你根本没有填充。尝试改变:

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 

到:

cipher = Cipher.getInstance("AES/CBC/NoPadding");