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

在尝试使用AES加密Android应用中的字符串时,遇到了InvalidKeyException,尽管秘钥长度显示为128位。问题出在使用Diffie-Hellman算法生成的密钥与AES加密不兼容。代码中展示了如何初始化KeyAgreement,生成SecretKey以及进行加密操作,但在加密过程中抛出了异常。允许的最大密钥长度为2147483647,但仍然收到错误提示,表明密钥可能不被接受。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我试图使用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位!

任何想法?

2010-12-10

Peter

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值