AES加密:InvalidKeyException:密钥长度不是128/192/256位

Pet*_*ter 13 encryption android aes diffie-hellman

我正在尝试使用AES加密Android上的字符串.先前使用Diffie-Hellman算法确定对称密钥,并且似乎没问题(密钥长度为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();
  }
Run Code Online (Sandbox Code Playgroud)

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

_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_ 
Run Code Online (Sandbox Code Playgroud)

在那之后,我得到了InvalidKeyException: Key length not 128/192/256 bits.但是你可以看到,SecretKey的长度为128位!

有任何想法吗?

eri*_*son 24

您生成的密钥是128 字节,而不是128 ."密钥长度"应为16.


小智 7

发生此异常的原因主要是您为加密传递了密钥的长度。如果使用的是AES加密,则字符数的长度必须为128/192/256位。例如,您可以使用16个字符,24个字符或32个字符的键。

String encrypted_data=AES.encrypt("HELLO","ASDFGHJKLASDFGHJ");
Run Code Online (Sandbox Code Playgroud)

希望能有所帮助...