DECRIPT PKCS7 data with Bouncycastle
843811Jun 10 2005 — edited Jun 10 2005Hello
I�m trying to encrypt and decrypt a PKCS7 XML message. I successfully encrypt it , but when I run the decrypt method with the encrypted result, I receive a java.lang.NegativeArraySizeException at org.bouncycastle.asn1.DERInputStream.readObject(DERInputStream.java:266) when I try to read the DERObject with the readObject() method of the DERInputStream.
I�m doing the right thing? Is my decode method ok?
Thanks a lot
Fabi�n
public String encode(String certificateFile, String xmlFile )throws Exception{
Security.addProvider(new BouncyCastleProvider());
FileInputStream fis = new FileInputStream(certificateFile);
CertificateFactory cf = CertificateFactory.getInstance("X509", "BC");
X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);
fis.close();
File f = new File(xmlFile) ;
int sizecontent = ((int) f.length());
byte[] contentbytes = new byte[sizecontent];
FileInputStream freader = new FileInputStream(f);
freader.close();
String algorithm = CMSEnvelopedDataGenerator.DES_EDE3_CBC;
CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator();
fact.addKeyTransRecipient(cert);
CMSProcessableByteArray content = new CMSProcessableByteArray(contentbytes);
CMSEnvelopedData envdata = fact.generate(content, algorithm, "BC");
byte[] enveloped = envdata.getEncoded();
enveloped = Base64.encode(enveloped);
return new String(enveloped);
}
public String decode(String dataEnc)throws Exception{
Security.addProvider(new BouncyCastleProvider());
byte[] data = Base64.decode(dataEnc);
DERInputStream din = new DERInputStream(new ByteArrayInputStream(data));
DERObject pkcs;
pkcs = din.readObject();
if (!(pkcs instanceof DERConstructedSequence))
throw new SecurityException("Not a valid PKCS#7 object - not a sequence");
ContentInfo content = ContentInfo.getInstance(pkcs);
if(!content.getContentType().equals(PKCSObjectIdentifiers.signedData))
throw new SecurityException("Not a valid PKCS#7 signed-data object - wrong header " + content.getContentType().getId());
SignedData sdata = SignedData.getInstance(content.getContent());
content = sdata.getEncapContentInfo();
if(!content.getContentType().equals(PKCSObjectIdentifiers.data))
throw new SecurityException("Not a valid PKCS#7 data object - not an attached signature");
byte[] dataresp = ((ASN1OctetString)content.getContent()).getOctets();
return new String (dataresp);
}