以下是我使用JDK 5本机库开发的AES 256加密和解密的实现:
public static String encrypt(String key, String toEncrypt) throws Exception {
Key skeySpec = generateKeySpec(key);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
byte[] encryptedValue = Base64.encodeBase64(encrypted);
return new String(encryptedValue);
}
public static String decrypt(String key, String encrypted) throws Exception {
Key skeySpec = generateKeySpec(key);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decodedBytes = Base64.decodeBase64(encrypted.getBytes());
byte[] original = cipher.doFinal(decodedBytes);
return new String(original);
}
我想用Boucy Castle API(Java)实现相同的方法:我搜索了很多,测试了很多,没有结果......有人可以帮助我吗?
由于
答案 0 :(得分:22)
您可以使用
Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES", "BC");
或者
Cipher cipher = Cipher.getInstance("AES", new BouncyCastleProvider());
尽管如此,Cipher.getInstance("AES")
使用Electronic Codebook,这是不安全的。您要么需要密码块链接(Cipher.getInstance("AES/CBC/PKCS5Padding")
)或计数器(Cipher.getInstance("AES/CTR/NoPadding")
)模式;它们都是安全的,主要区别在于CBC需要填充而CTR不需要填充。