Generate authenticated CMSEnvelopedData Messages with bouncycastle

Posted by levinalex on Stack Overflow See other posts from Stack Overflow or by levinalex
Published on 2009-08-06T17:22:26Z Indexed on 2010/05/20 22:50 UTC
Read the original article Hit count: 900

I am trying to encrypt data with a password and store it inside a ASN.1 encoded CMS message (using C# and BouncyCastle 1.4)

The code I have seems to have two problems:

  • the data does not seem to be signed with a HMAC, so when I tamper with the encodedData (by enabling the commented out line), the decryption still succeeds.

  • when I decrypt the data I have tampered with, I get beck corrupted plain text. However only a two blocks of plaintext data are corrupted. This seems to suggest that the encryption does not actually use CBC mode.

    (edit: disregard the second point, this is exactly how CBC is supposed to work)

This is what I am testing with:

public void TestMethod1()
{
    byte[] data = new byte[1024]; // plaintext: a list of zeroes

    CmsEnvelopedDataGenerator generator = new CmsEnvelopedDataGenerator();
    CmsPbeKey encryptionKey = new Pkcs5Scheme2PbeKey("foo", new byte[] { 1, 2, 3 }, 2048);
    generator.AddPasswordRecipient(encryptionKey, CmsEnvelopedDataGenerator.Aes256Cbc);
    CmsProcessableByteArray cmsByteArray = new CmsProcessableByteArray(data);
    CmsEnvelopedData envelopeData = generator.Generate(cmsByteArray, CmsEnvelopedDataGenerator.Aes256Cbc);

    byte[] encodedData = envelopeData.GetEncoded();

    // encodedData[500] = 10; // tamper with the data

    RecipientID recipientID = new RecipientID();
    CmsEnvelopedData decodedEnvelopeData = new CmsEnvelopedData(encodedData);
    RecipientInformation recipient = decodedEnvelopeData.GetRecipientInfos().GetFirstRecipient(recipientID);

    byte[] data2 = recipient.GetContent(encryptionKey);

    CollectionAssert.AreEqual(data, data2);
}

What am I doing wrong? What would be the correct way to write this?

© Stack Overflow or respective owner

Related posts about bouncycastle

Related posts about c#