我试图加密Android上的一个字符串AES。对称密钥被确定previously用的Diffie-Hellman算法似乎是确定(密钥长度为128位,见下文)。结果不过,我得到一个 InvalidKeyException将:密钥长度不128/192/256位
I'm trying to encrypt a string on Android with AES. The symmetric key is determined previously with the Diffie-Hellman algorithm and seems to be ok (Key Length is 128 Bit, see below).
Nevertheless, I get a InvalidKeyException: "Key length not 128/192/256 bits.
"
code:
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();
}
以上code导致以下的输出:结果的 12-10 20:24:53.119:信息/的System.out(757):密钥长度:128 的结果的 12-10 20:24:53.119:信息/的System.out(757):密钥算法:AES 的结果的 12-10 20:24:53.119:信息/的System.out(757):密钥格式:RAW 的结果的 12-10 20:24:53.470:信息/的System.out(757):允许密钥长度:2147483647 的
在那之后,我得到了InvalidKeyException将:密钥长度不128/192/256位。但正如你所看到的,SecretKey的有128位长度!
After that, I get the "InvalidKeyException: Key length not 128/192/256 bits." But as you can see, the SecretKey has a length of 128 Bits!
任何想法?
感谢
在生成的关键是128的字节的,而不是128的位的。 密钥长度应该是16。
The key you generated is 128 bytes, not 128 bits. "Key Length" should be 16.