简体   繁体   中英

BouncyCastle create PKCS 7 Encrypted File? C#

I am trying to use BouncyCastle to encrypt a file using the PKCS 7 file standard. Here is the code I have which outputs a p7m file. When I go to decrypt the file (using Entrust) I am prompted for my key store password, so it knows the file was encrypted for me using AES 128, but it cannot decrypt the body of the file. Something has to be going wrong on the encrypt.

byte[] fileContent = readFile(filename);

FileStream outStream = null;
Stream cryptoStream = null;
BinaryWriter binWriter = null;

try
{
    CmsEnvelopedDataStreamGenerator dataGenerator = new CmsEnvelopedDataStreamGenerator();
    dataGenerator.AddKeyTransRecipient(cert); //cert is the user's x509cert that i am encrypting for
    outStream = new FileStream(filename + ".p7m", FileMode.Create);
    cryptoStream = dataGenerator.Open(outStream, CmsEnvelopedGenerator.Aes128Cbc);
    binWriter = new BinaryWriter(cryptoStream);

    binWriter.Write(fileContent);
}

And when i try and decrypt the file using BouncyCastle I get this error when i pass the file contents to a CMSEnveloped Object:

IOException converting stream to byte array: Attempted to read past the end of the stream.

Any ideas whats going on here?

I used the EnvelopedCMS class to accomplish this.

http://msdn.microsoft.com/en-us/library/bb924575(VS.90).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM