android - AES 加密 : InvalidKeyException: Key length not 128/192/256 bits

标签 android encryption aes diffie-hellman

我正在尝试使用 AES 加密 Android 上的字符串。对称 key 是之前用 Diffie-Hellman 算法确定的,似乎没问题( key 长度是 128 位,见下文)。
然而,我得到一个 InvalidKeyException: "Key length not 128/192/256 bits."

代码:

KeyAgreement keyAgree = KeyAgreement.getInstance("DH", "BC");
keyAgree.init(this.smartphonePrivKey);
keyAgree.doPhase(serverPubKey, true);
SecretKey key = keyAgree.generateSecret("AES");
System.out.println("Key Length: " + key.getEncoded().length);
System.out.println("Key Algorithm: "+ key.getAlgorithm());
System.out.println("Key Format: "+ key.getFormat());

byte[] encrypted = null;
  Cipher cipher;
  try {
   cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
   System.out.println("Allowed Key Length: "
     + cipher.getMaxAllowedKeyLength("AES"));
   cipher.init(Cipher.ENCRYPT_MODE, key);
   encrypted = cipher.doFinal("YEAH".getBytes("UTF8"));
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (NoSuchPaddingException e) {
   e.printStackTrace();
  } catch (InvalidKeyException e) {
   e.printStackTrace();
  } catch (IllegalBlockSizeException e) {
   e.printStackTrace();
  } catch (BadPaddingException e) {
   e.printStackTrace();
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }

上面的代码导致以下输出:

_12-10 20:24:53.119: INFO/System.out(757): Key Length: 128_  
_12-10 20:24:53.119: INFO/System.out(757): Key Algorithm: AES_   
_12-10 20:24:53.119: INFO/System.out(757): Key Format: RAW_  
_12-10 20:24:53.470: INFO/System.out(757): Allowed Key Length: 2147483647_ 

在那之后,我得到了 InvalidKeyException: Key length not 128/192/256 bits. 但如您所见,SecretKey 的长度为 128 位!

有什么想法吗?

最佳答案

您生成的 key 是 128 字节,而不是 128 。 “ key 长度”应为 16。

关于android - AES 加密 : InvalidKeyException: Key length not 128/192/256 bits,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4413023/

相关文章:

javax.crypto.BadPaddingException AES

android - 以编程方式使用android版本

c# - C# 中的对象加密和解密

javascript - 如何在javascript中将整数列表转换为数组缓冲区?

c - 使用凯撒密码的 C 加密

php - 我应该如何存储 AES 加密 key ?

java - Firebase 实时数据库隐私最佳实践

android - 如何修复 "End of stream on null"网络问题?

android - 如何从 Android 上的 XML 文件加载 SQL 查询?

iphone - 使用 openssl 加密并使用 AES 128、ecb 模式在 iPhone 上解密