java – GCMParameterSpec抛出InvalidAlgorithmParameterException:未知参数类型

我正在做 android数据加密以保存在SharedPreferences中. GCMParameterSpec是在API 19中的 Android中引入的,我用它来进行AES / GCM / NoPadding加密.这就是我实现它的方式:

Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, getSecretKey(context),new GCMParameterSpec(128,Base64.decode(myGeneratedIV, Base64.DEFAULT)));

我的问题是,在Android 4.4.2(API 19)中,我得到了引发的错误,但是从API 21开始,它可以工作.

关于异常,来自Android文档:

if the given algorithm parameters are inappropriate for this cipher, or this cipher requires algorithm parameters and params is null, or the given algorithm parameters imply a cryptographic strength that would exceed the legal limits (as determined from the configured jurisdiction policy files).

我的问题是:这种行为有特定的原因吗?为什么Cipher的init方法没有识别params?

我甚至尝试过加密而不给出特定的IV:

c.init(Cipher.ENCRYPT_MODE, getSecretKey(context));

一旦我尝试以相同的方式解密:

c.init(Cipher.DECRYPT_MODE, getSecretKey(context));

它抛出相同的异常(InvalidAlgorithmParameterException),表示解密需要GCMParameterSpec.

我尝试仅将GCMParameterSpec提供给解密,并且我获得了未知参数类型异常.

任何帮助表示赞赏

最佳答案 可能是Android中提供程序中的CipherSpi实现可能还不支持GCMParameterSpec.定义API与在底层加密提供程序中为其提供支持不同.

相反,您也可以使用为其他模式提供的标准IvParameterSpec.只需将您的GCMParamterSpec的(12)IV / nonce字节直接用作IV.

由于您具有标准标记大小,因此您的实现不会产生任何问题.

如果标签大小不同,则解决方案变得更加复杂,因为验证将仅使用结果标签的最左侧字节.遗憾的是,标签生成和验证隐藏在Cipher类的API设计中.

点赞