【问题标题】:AES 256 Encryption IssueAES 256 加密问题
【发布时间】:2014-05-11 21:12:54
【问题描述】:

以下代码完美实现了AES-128加密/解密。

public static void main(String[] args) throws Exception
{
    String input = JOptionPane.showInputDialog(null, "Enter your String");
    System.out.println("Plaintext: " + input + "\n");

    // Generate a key
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128); 
    byte[] key = keygen.generateKey().getEncoded();
    SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

    // Generate IV randomly
    SecureRandom random = new SecureRandom();
    byte[] iv = new byte[16];
    random.nextBytes(iv);
    IvParameterSpec ivspec = new IvParameterSpec(iv);

    // Initialize Encryption Mode
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);

    // Encrypt the message
    byte[] encryption = cipher.doFinal(input.getBytes());
    System.out.println("Ciphertext: " + encryption + "\n"); //

    // Initialize the cipher for decryption
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivspec);

    // Decrypt the message
    byte[] decryption = cipher.doFinal(encryption);
    System.out.println("Plaintext: " + new String(decryption) + "\n");
}

当我想使用 AES-256 时,我认为可以通过修改 keygen.init(256);byte[] iv = new byte[32]; 来完成,但这会变成错误(线程“main”中的异常 java.security.InvalidKeyException:非法密钥大小) !有人可以解释为什么在我进行这两个修改时会发生错误以及我应该怎么做。谢谢各位:)

【问题讨论】:

  • 你得到什么错误?
  • 线程“主”java.security.InvalidKeyException 中的异常:非法密钥大小
  • InvalidKeyException: Illegal key size 表示您没有安装无限的策略文件或将它们放入错误的目录。您可以使用Cipher.getMaxAllowedKeyLength( "AES/CBC/PKCS5Padding" ) 来检查您是否正确安装它们:如果输出为128,那么加密仍然是有限的。
  • AES 192 和 AES 256 的 IV 大小是相同的 16 字节 - 无论密钥大小如何,AES 块大小始终为 128 位。

标签: java encryption cryptography aes


【解决方案1】:

如果您想使用 AES 256 加密,您必须安装 Unlimited Strength Jurisdiction Policy Files:

http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

这可以启用更高的加密级别,例如 AES 256 和 RSA 2048。

将 zip 中的文件替换为 <java-home>\lib\security 中的当前文件。

【讨论】:

  • 谢谢。我做的和你说的完全一样,但是bug还是:(
  • 线程“主”java.security.InvalidKeyException 中的异常:javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1024) 处的非法密钥大小在 javax.crypto.Cipher.implInit(Cipher.java :790) 在 javax.crypto.Cipher.chooseProvider(Cipher.java:849) 在 javax.crypto.Cipher.init(Cipher.java:1348) 在 javax.crypto.Cipher.init(Cipher.java:1282) 在 cipher .me.AesWithCbcExample.main(AesWithCbcExample.java:79)
  • 您必须确保策略文件位于运行时 jre 目录中。如果您安装了多个 jre,则它们必须在正确的一个中。 (简单的技巧是将它们放在所有 jre 目录中。)
  • 感谢 Amurka,它帮了很多忙,我完全为 AES 256 做的,并增加了我的“无限强度管辖权政策”,它对我有用
猜你喜欢
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-12
相关资源
最近更新 更多