我有一塊使用JCE算法「PBEWithSHA256And256BitAES-CBC-BC」創建的密文。提供商是BouncyCastle。我想要做的是使用BouncyCastle輕量級API來解密這個密文。我不想使用JCE,因爲這需要安裝無限強度管轄權策略文件。如何在AES和PBE中使用Bouncy Castle輕量級API
當涉及到使用BC與PBE和AES時,文檔似乎很薄弱。
這是我到目前爲止。解密代碼無一例外地運行,但返回垃圾。
加密代碼,
String password = "qwerty";
String plainText = "hello world";
byte[] salt = generateSalt();
byte[] cipherText = encrypt(plainText, password.toCharArray(), salt);
private static byte[] generateSalt() throws NoSuchAlgorithmException {
byte salt[] = new byte[8];
SecureRandom saltGen = SecureRandom.getInstance("SHA1PRNG");
saltGen.nextBytes(salt);
return salt;
}
private static byte[] encrypt(String plainText, char[] password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
Security.addProvider(new BouncyCastleProvider());
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
Cipher encryptionCipher = Cipher.getInstance("PBEWithSHA256And256BitAES-CBC-BC");
encryptionCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
return encryptionCipher.doFinal(plainText.getBytes());
}
解密代碼,
byte[] decryptedText = decrypt(cipherText, password.getBytes(), salt);
private static byte[] decrypt(byte[] cipherText, byte[] password, byte[] salt) throws DataLengthException, IllegalStateException, InvalidCipherTextException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
BlockCipher engine = new AESEngine();
CBCBlockCipher cipher = new CBCBlockCipher(engine);
PKCS5S1ParametersGenerator keyGenerator = new PKCS5S1ParametersGenerator(new SHA256Digest());
keyGenerator.init(password, salt, 20);
CipherParameters keyParams = keyGenerator.generateDerivedParameters(256);
cipher.init(false, keyParams);
byte[] decryptedBytes = new byte[cipherText.length];
int numBytesCopied = cipher.processBlock(cipherText, 0, decryptedBytes, 0);
return decryptedBytes;
}
謝謝格雷格。很棒。 – Adrian 2010-06-03 07:11:27
行pGen.generateDerivedParameters(256,128);是設置密鑰長度嗎? – 2014-01-15 09:21:58
@george_h:256是關鍵字長度; 128是IV長度。 – 2014-01-15 23:51:22