问题描述
我正在做Android数据加密以保存在SharedPreferences中。 GCMParameterSpec在Android中引入了API 19,我正在使用 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文档:
我的问题是:这个行为有特定的原因吗?为什么来自Cipher的 init
方法不能识别参数?
我甚至尝试加密而不给出特定的IV :
c.init(Cipher.ENCRYPT_MODE,getSecretKey(context));
一旦我尝试以同样的方式解密:
c.init(Cipher.DECRYPT_MODE,getSecretKey(context));
它抛出相同的异常(InvalidAlgorithmParameterException),说出一个 GCMParameterSpec
需要解密。
我尝试只向解密提供 GCMParameterSpec
,而且我得到了未知的参数类型异常。 >
任何帮助都赞赏
可能是 CipherSpi
在Android提供商中的实现可能不支持 GCMParameterSpec
。定义API与底层加密提供程序中提供的支持不一样。
相反,您可以使用标准的 IvParameterSpec
为其他模式提供。只需将您的 GCMParamterSpec
的(12)IV /随机字节直接用作您的IV。
标准标签大小这应该对您的实施没有任何问题。
如果标签大小不同,则解决方案变得更加复杂因为验证将仅使用结果标签的最左边的字节。不幸的是,代码生成和验证隐藏在 Cipher
类的API设计中。
I am doing android data encryption to save in SharedPreferences. GCMParameterSpec was introduced in Android in API 19 which I'm using for AES/GCM/NoPadding
encryption. This is how I'm implementing it:
Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
c.init(Cipher.ENCRYPT_MODE, getSecretKey(context),new GCMParameterSpec(128,Base64.decode(myGeneratedIV, Base64.DEFAULT)));
My problem is, in Android 4.4.2 (API 19) I get the error mentioned thrown, but from API 21 it works.
About the exception, from the Android docs:
My question is: Is there a specific reason for this behaviour? Why doesn't the init
method from Cipher identify the params?
I even tried encrypting without giving a specific IV:
c.init(Cipher.ENCRYPT_MODE, getSecretKey(context));
And once I tried to decrypt the same way:
c.init(Cipher.DECRYPT_MODE, getSecretKey(context));
It throws the same exception(InvalidAlgorithmParameterException) saying a GCMParameterSpec
is needed for decryption.
I tried giving the GCMParameterSpec
only to the decryption, and I get the unknown parameter type exception.
Any help is appreciated
It may be that the CipherSpi
implementation within the provider in Android may not support GCMParameterSpec
yet. Defining an API is not the same thing as providing support for it within the underlying cryptography provider.
Instead you can use the standard IvParameterSpec
provided for the other modes as well. Simply use the (12) IV/nonce bytes for your GCMParamterSpec
directly as your IV.
As you have the standard tag size this should pose no problem with your implementation.
In case the tag size differs then the solution becomes more complicated as verification will only use the leftmost bytes of the resulting tag. Unfortunately the tag generation and verification is hidden within the API design of the Cipher
class.
这篇关于GCMParameterSpec抛出InvalidAlgorithmParameterException:未知参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!