【问题标题】:AES encrypt/decrypt with Bouncy Castle provider [duplicate]使用 Bouncy Castle 提供程序进行 AES 加密/解密 [重复]
【发布时间】:2013-04-02 05:54:16
【问题描述】:

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

谢谢

【问题讨论】:

  • 您确实意识到您将使用相同的 API,但只是使用不同的提供者,对吗?无论如何,请阅读here
  • 请注意,AES256 在 Oracle 的所有 Java 版本中默认禁用。您必须为 Java 5 安装 Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files。顺便说一句:Java 5 已过时且不安全。不要再使用它了。
  • 我知道罗伯特,谢谢。感知,我想使用 Boucny Castle,因为它比 Java 的本机库更便携(仅来自 JDK 6+)
  • 是的,这是重复的,但 the original 的答案非常稀少。
  • 没错,它是重复的,但场景不同。

标签: java cryptography aes bouncycastle


【解决方案1】:

你可以使用

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 不需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 2011-01-26
    • 1970-01-01
    • 2012-04-25
    • 2020-09-01
    • 2011-12-16
    • 2011-08-20
    • 2017-02-19
    相关资源
    最近更新 更多