AES-GCM解密错误iaik.cms.CMSException:无法解密加密的内容加密密钥:无效的填充

时间:2019-02-22 13:55:12

标签: aes-gcm

我正在使用以下代码通过AES-GCM加密数据:

// the stream to which to write the EnvelopedData
ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
EnvelopedDataOutputStream envelopedData;

//  wrap EnvelopedData into a ContentInfo 
ContentInfoOutputStream contentInfoStream = 
  new ContentInfoOutputStream(ObjectID.cms_envelopedData, resultStream);
// create a new EnvelopedData object encrypted with AES
try {
 envelopedData = new EnvelopedDataOutputStream(contentInfoStream,                                                     
 (AlgorithmID)AlgorithmID.aes256_GCM.clone());
} catch (NoSuchAlgorithmException ex) {
 throw new CMSException("No implementation for AES.");
}

// create the recipient infos
RecipientInfo[] recipients = new RecipientInfo[1];
// user1 is the first receiver
recipients[0] = new KeyTransRecipientInfo(signCert, 
(AlgorithmID)AlgorithmID.rsaEncryption.clone()); 

// specify the recipients of the encrypted message
envelopedData.setRecipientInfos(recipients);
//int blockSize = 2048; // in real world we would use a block size like 2048
//  write in the data to be encrypted
//byte[] buffer = new byte[blockSize];
byte[] buffer = new byte[16];
//byte[] buffer;
int bytesRead;
while ((bytesRead = inputstream.read(buffer)) != -1) {
 envelopedData.write(buffer, 0, bytesRead);
}

但是在尝试使用以下代码解密相同内容时:

EnvelopedDataStream enveloped_data = new EnvelopedDataStream(is);
enveloped_data.setupCipher(privateSignKey, 0);
InputStream decrypted = enveloped_data.getInputStream();
ByteArrayOutputStream os = new ByteArrayOutputStream();      
ByteStreams.copy(decrypted, os);
os.close();

我遇到以下错误:

iaik.cms.CMSException: Unable to decrypt encrypted content-encryption key: Invalid padding!

我不确定要使用的块大小,这可能是导致错误的原因,但不确定。

此外,如果我将加密文件与正确文件进行比较,则会发现以下差异:

我的加密数据:

OBJECT IDENTIFIER 2.16.840.1.101.3.4.1.46 aes256-GCM (NIST Algorithm)
   SEQUENCE (1 elem)
     OCTET STRING (12 byte) FE5729470184A04A5AA30158

更正数据:

OBJECT IDENTIFIER 2.16.840.1.101.3.4.1.46 aes256-GCM (NIST Algorithm)
SEQUENCE (2 elem)
  OCTET STRING (12 byte) CA985F7EAFB709DF711DCA2A
  INTEGER 16

您能帮助我们使它正常工作吗?

0 个答案:

没有答案