Skip to content

Encrypt and Decrypt email using AES-GCM #1838

Description

@vbrandl

Hey

I want do encrypt and decrypt an email using AES128-GCM. I generated a keypair for testing using openssl req -newkey rsa:2048 -nodes -keyout key.pem -x509 -days 365 -out certificate.pem. Encrypting and then decrypting does work fine within BouncyCastle, but I cannot decrypt the message using OpenSSL

I have the following functions for en- and decryption:

private static void encrypt(final X509Certificate[] chain, final byte[] content, final Path out) throws Exception {
  final var recpInfo = new JceKeyTransRecipientInfoGenerator(chain[0]);
  final var envelopedGenerator = new CMSEnvelopedDataStreamGenerator();
  envelopedGenerator.addRecipientInfoGenerator(recpInfo);
  final var encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_GCM).setProvider(BC_PROV).build();
  try (final var outFile = Files.newOutputStream(out, StandardOpenOption.CREATE_NEW);
  final var envOut = envelopedGenerator.open(outFile, encryptor);
  final var data = new ByteArrayInputStream(content)) {
    data.transferTo(envOut);
  }
}

private static void decrypt(final PrivateKey privKey, final byte[] encrypted, final Path out) throws Exception {
  final var parser = new CMSEnvelopedDataParser(encrypted);
  final var recipients = parser.getRecipientInfos();
  final var recipient = recipients.getRecipients().iterator().next();
  final var keyRecip = new JceKeyTransEnvelopedRecipient(privKey).setProvider(BC_PROV);
  try (final var outFile = Files.newOutputStream(out, StandardOpenOption.CREATE_NEW);
  final var contentIn = recipient.getContentStream(keyRecip).getContentStream()) {
    contentIn.transferTo(outFile);
  }
}

OpenSSL gives me the following error:

$ openssl cms -inkey key.pem -recip certificate.pem -decrypt -in encrypted.mime
Error reading SMIME Content Info
4017FF8F667F0000:error:068000D1:asn1 encoding routines:SMIME_read_ASN1_ex:no content type:crypto/asn1/asn_mime.c:420:

How can I generate a SMIME email, that can also be decrypted using OpenSSL?

Attached you can find my example keys as well as encrypted.mime and decrypted.mime.

example.zip

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestsupport requestCommunity assistance requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions