java - 使用 Bouncy CaSTLe 提供程序进行 AES 加密/解密

标签 java cryptography aes bouncycastle

<分区>

这是我使用 JDK 5 的 native 库开发的 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) 实现相同的方法:我搜索了很多,测试了很多,但没有结果......有人可以帮助我吗?

谢谢

最佳答案

你要么使用

Security.addProvider(new BouncyCastleProvider());
Cipher cipher = Cipher.getInstance("AES", "BC");

否则

Cipher cipher = Cipher.getInstance("AES", new BouncyCastleProvider());

也就是说,Cipher.getInstance("AES") 使用 Electronic Codebook ,这是不安全的。您需要密码 block 链接 (Cipher.getInstance("AES/CBC/PKCS5Padding")) 或计数器 (Cipher.getInstance("AES/CTR/NoPadding"))模式;它们都是安全的,主要区别在于 CBC 需要填充而 CTR 不需要。

关于java - 使用 Bouncy CaSTLe 提供程序进行 AES 加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15925029/

相关文章:

java - 当值不为空时更新列 JOOQ

java - ROUND_HALF_EVEN 为什么以及如何在重复应用于一系列计算时最小化累积误差?

java - getGlobalVisibleRect() 究竟是什么?

asp.net-core - ASP.NET Core - 数据保护

java - EST 与充气城堡

java - 让 Ant 的 Java 任务打印空行

php - 使用 Objective-C 加密并使用 MCRYPT_RIJNDAEL_256 MCRYPT_MODE_ECB 在 PHP 中解密

cryptography - OpenSSL GCM 解密中的后期身份验证

Android JNI字符串加密/解密

c# - AES GCM 手动 byte[] IV 和标记与加密信息的串联