2010-12-10 370 views
9

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

代码:

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位!

任何想法?

回答

19

您生成的密钥是128 字节而不是128 。 “密钥长度”应为16.

+0

+1打我给它。 @Peter:唯一可以找到表示位数的Length属性的地方是一个专门的位集合。 99.9%的时间将会是字符或字节的计数。 – 2010-12-10 21:07:02

+0

嗯,你显然是对的。因此,使用KeyAgreement.generateSecret(“AES”)将返回一个长度为128字节的密钥。显然,这太多了...我怎么能得到一个关键,让我们说256位?谢谢 – Peter 2010-12-11 09:39:40

+0

顺便说一句:Android使用BouncyCastle作为安全提供程序... – Peter 2010-12-11 09:55:14

1

此例外情况基本上是由于您为加密传递的密钥长度所致。如果您使用AES加密,则字符数必须为128/192/256位。 例如,您可以使用16个字符,24个字符或32个字符的键。

String encrypted_data=AES.encrypt("HELLO","ASDFGHJKLASDFGHJ"); 

希望这有助于...

+0

已经有一个可接受的答案。 – 2017-01-31 05:54:50