Tôi có một khối bản mã được tạo bằng thuật toán JCE "PBEWithSHA256And256BitAES-CBC-BC". Nhà cung cấp là BouncyCastle. Điều tôi muốn làm là giải mã bản mã này bằng cách sử dụng API nhẹ BouncyCastle. Tôi không muốn sử dụng JCE vì điều đó đòi hỏi phải cài đặt các tập tin chính sách quyền hạn không giới hạn quyền lực.Cách sử dụng API nhẹ Bouncy Castle với AES và PBE
Tài liệu có vẻ mỏng trên mặt đất khi nói đến việc sử dụng BC với PBE và AES.
Đây là những gì tôi có cho đến nay. Mã giải mã chạy không có ngoại lệ nhưng trả về rác.
Mã mã hóa,
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());
}
Mã giải mã,
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;
}
Cảm ơn Greg. Hoạt động tuyệt vời. – Adrian
dòng pGen.generateDerivedParameters (256, 128); là thiết lập độ dài khóa? –
@george_h: 256 là độ dài khóa; 128 là chiều dài IV. –