public static void Rc4AndCngWrappersDontMixTest() { // // Combination of RC4 over a CAPI certificate. // // This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG), // the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG. // byte[] content = { 6, 3, 128, 33, 44 }; AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4)); EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4); CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate())); ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { if (cert == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(); extraStore.Add(cert); ecms.Decrypt(extraStore); } ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(content, contentInfo.Content); }
private byte[] EncryptedBytes(byte[] bytes) { var contentInfo = new ContentInfo(bytes); var encryptAlgoOid = new Oid("2.16.840.1.101.3.4.1.42"); // AES-256-CBC var envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(encryptAlgoOid)); var recipient = new CmsRecipient(CryptographicCertificate); envelopedCms.Encrypt(recipient); return envelopedCms.Encode(); }
public byte[] encrypt(byte[] plainTest) { envelopedContentInfo = new ContentInfo(plainTest); envelopedCms = new EnvelopedCms(envelopedContentInfo); envelopeCmsResipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cryptographyClientCert); envelopedCms.Encrypt(envelopeCmsResipient); return envelopedCms.Encode(); }
/// <summary> /// Encrypts the specified string. /// </summary> /// <param name="plaintext">The plaintext to be encrypted.</param> /// <param name="certificate">The certificate to be used for encryption.</param> /// <returns>The encrypted text.</returns> public static string Encrypt(this string plaintext, X509Certificate2 certificate) { var contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(plaintext)); var envelopedCms = new EnvelopedCms(contentInfo); var cmsRecipient = new CmsRecipient(certificate); envelopedCms.Encrypt(cmsRecipient); return Convert.ToBase64String(envelopedCms.Encode()); }
private byte[] Envelope(byte[] contentBytes) { Pkcs.ContentInfo content = new Pkcs.ContentInfo(contentBytes); Pkcs.EnvelopedCms envMsg = new Pkcs.EnvelopedCms(content); Pkcs.CmsRecipient recipient = new Pkcs.CmsRecipient(Pkcs.SubjectIdentifierType.IssuerAndSerialNumber, _recipientCert); envMsg.Encrypt(recipient); byte[] encryptedBytes = envMsg.Encode(); return(encryptedBytes); }
public static void DecodeCertificates0_RoundTrip() { ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); VerifyCertificates0(encodedMessage); }
public static void DecodeAlgorithmDes_RoundTrip() { AlgorithmIdentifier algorithm = new AlgorithmIdentifier(new Oid(Oids.Des)); ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo, algorithm); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); VerifyAlgorithmDes(encodedMessage); }
public static void DecodeRecipients3_RoundTrip() { ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); CmsRecipientCollection recipients = new CmsRecipientCollection(); foreach (X509Certificate2 cert in s_certs) { recipients.Add(new CmsRecipient(cert)); } ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); VerifyRecipients3(encodedMessage); }
/// <summary> /// Decrypts enveloped mime content. /// </summary> /// <param name="cert">Decrypting certificate.</param> /// <returns>Returns decrypted enveloped mime content.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>cert</b> is null reference.</exception> /// <exception cref="InvalidOperationException">Is raised when <b>smime-type != enveloped-data</b>.</exception> public MIME_Message GetEnvelopedMime(X509Certificate2 cert) { if(cert == null){ throw new ArgumentNullException("cert"); } if(!string.Equals(this.Entity.ContentType.Parameters["smime-type"],"enveloped-data",StringComparison.InvariantCultureIgnoreCase)){ throw new InvalidOperationException("The VerifySignature method is only valid if Content-Type parameter smime-type=enveloped-data."); } EnvelopedCms envelopedCms = new EnvelopedCms(); envelopedCms.Decode(this.Data); X509Certificate2Collection certificates = new X509Certificate2Collection(cert); envelopedCms.Decrypt(certificates); return MIME_Message.ParseFromStream(new MemoryStream(envelopedCms.Encode())); }
public static void ZeroLengthContent_RoundTrip() { ContentInfo contentInfo = new ContentInfo(Array.Empty<byte>()); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); try { ecms.Encrypt(cmsRecipient); } catch (CryptographicException e) { throw new Exception("ecms.Encrypt() threw " + e.Message + ".\nIf you're running on the desktop CLR, this is actually an expected result."); } } byte[] encodedMessage = ecms.Encode(); ValidateZeroLengthContent(encodedMessage); }
public static void PostDecode_Encode() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); // This should really have thrown an InvalidOperationException. Instead, you get... something back. byte[] expectedGarbage = "35edc437e31d0b70".HexToByteArray(); byte[] garbage = ecms.Encode(); AssertEncryptedContentEqual(expectedGarbage, garbage); }
/// <summary> /// Encrypt payload string into a base 64-encoded string using the certificate. /// This is suitable for encrypting storage account keys for later use as a job argument. /// </summary> /// <param name="cert"> /// Certificate used to encrypt the payload. /// </param> /// <param name="payload"> /// Value to encrypt. /// </param> /// <returns> /// Encrypted payload. /// </returns> public static string EncryptAsBase64String(X509Certificate2 cert, string payload) { var ci = new ContentInfo(Encoding.UTF8.GetBytes(payload)); var env = new EnvelopedCms(ci); env.Encrypt(new CmsRecipient(cert)); return Convert.ToBase64String(env.Encode()); }
private string Encrypt(string password, X509Certificate2 cert) { byte[] bytes = Encoding.UTF8.GetBytes(password); EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(bytes)); envelopedCms.Encrypt(new CmsRecipient(cert)); return Convert.ToBase64String(envelopedCms.Encode()); }
private static KeyTransRecipientInfo EncodeKeyTransl(SubjectIdentifierType type = SubjectIdentifierType.IssuerAndSerialNumber) { ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(type, cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); EnvelopedCms ecms2 = new EnvelopedCms(); ecms2.Decode(encodedMessage); RecipientInfoCollection recipients = ecms2.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; Assert.True(recipientInfo is KeyTransRecipientInfo); return (KeyTransRecipientInfo)recipientInfo; }
private byte[] KrypterteBytes(byte[] bytes) { Logging.Log(TraceEventType.Information, Manifest.Forsendelse.KonversasjonsId, string.Format("Krypterer dokumentpakke med sertifikat {0}.", _krypteringssertifikat.Thumbprint)); var contentInfo = new ContentInfo(bytes); var encryptAlgoOid = new Oid("2.16.840.1.101.3.4.1.42"); // AES-256-CBC var envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(encryptAlgoOid)); var recipient = new CmsRecipient(_krypteringssertifikat); envelopedCms.Encrypt(recipient); return envelopedCms.Encode(); }
/// <summary> /// Decrypt the encrypted data. /// </summary> /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns> /// <param name="encryptedData">The encrypted data.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="encryptedData"/> is <c>null</c>. /// </exception> /// <exception cref="System.Security.Cryptography.CryptographicException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override MimeEntity Decrypt(Stream encryptedData) { if (encryptedData == null) throw new ArgumentNullException ("encryptedData"); var enveloped = new EnvelopedCms (); enveloped.Decode (ReadAllBytes (encryptedData)); var store = new X509Store (StoreName.My, StoreLocation); store.Open (OpenFlags.ReadOnly); enveloped.Decrypt (); store.Close (); var decryptedData = enveloped.Encode (); using (var memory = new MemoryStream (decryptedData, false)) { return MimeEntity.Load (memory); } }
private static void HandleCertificateOperations(Options options, AuthenticationContext authContext, AuthenticationResult token) { using (var client = new KeyVaultManagementClient(new TokenCloudCredentials(options.SubscriptionId, token.AccessToken))) { if (!string.IsNullOrEmpty(options.ResourceGroup)) { if (!string.IsNullOrEmpty(options.Vault)) { var vaultInfo = client.Vaults.Get(options.ResourceGroup, options.Vault); var vaultToken = authContext.AcquireToken("https://vault.azure.net", "1950a258-227b-4e31-a9cf-717495945fc2", new Uri("urn:ietf:wg:oauth:2.0:oob")); var keyvaultClient = new KeyVaultClient((_, b, c) => Task.FromResult(vaultToken.AccessToken)); if (!string.IsNullOrEmpty(options.ExportCert)) { var secret = keyvaultClient.GetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.ExportCert).GetAwaiter().GetResult(); var cert = new X509Certificate2(Convert.FromBase64String(secret.Value), new SecureString(), X509KeyStorageFlags.Exportable); File.WriteAllBytes(options.Out, cert.Export(X509ContentType.Pfx)); } if (!string.IsNullOrEmpty(options.Encrypt)) { var secret = keyvaultClient.GetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.CertificateName).GetAwaiter().GetResult(); var cert = new X509Certificate2(Convert.FromBase64String(secret.Value)); byte[] encoded = System.Text.UTF8Encoding.UTF8.GetBytes(options.Encrypt); var content = new ContentInfo(encoded); var env = new EnvelopedCms(content); env.Encrypt(new CmsRecipient(cert)); string encrypted64 = Convert.ToBase64String(env.Encode()); Console.WriteLine("Encrypting: {0}", options.Encrypt); Console.WriteLine("Encrypted Base64 String: {0}", encrypted64); } if (!string.IsNullOrEmpty(options.Decrypt)) { var secret = keyvaultClient.GetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.CertificateName).GetAwaiter().GetResult(); var cert = new X509Certificate2(Convert.FromBase64String(secret.Value)); var encryptedBytes = Convert.FromBase64String(options.Decrypt); var envelope = new EnvelopedCms(); envelope.Decode(encryptedBytes); envelope.Decrypt(new X509Certificate2Collection(cert)); Console.WriteLine("Decrypting: {0}", options.Decrypt); Console.WriteLine("Decrypted String: {0}", Encoding.UTF8.GetString(envelope.ContentInfo.Content)); } if (options.MakeCert) { var cert = Convert.ToBase64String(Certificate.CreateSelfSignCertificatePfx(string.Format("CN={0}", options.CertificateName), DateTime.UtcNow, DateTime.UtcNow.AddYears(2))); var cert1 = new X509Certificate2(Convert.FromBase64String(cert)); var secrets = keyvaultClient.GetSecretsAsync(vaultInfo.Vault.Properties.VaultUri).GetAwaiter().GetResult(); if (secrets.Value == null || !secrets.Value.Any(s => s.Id == vaultInfo.Vault.Properties.VaultUri + "secrets/" + options.CertificateName)) { Console.WriteLine( JsonConvert.SerializeObject(keyvaultClient.SetSecretAsync(vaultInfo.Vault.Properties.VaultUri, options.CertificateName, cert, null, "application/pkcs12").GetAwaiter().GetResult() , Formatting.Indented)); } } } } } }
public void EncodeEmpty () { EnvelopedCms ep = new EnvelopedCms (); byte[] encoded = ep.Encode (); }
public static void ReuseEnvelopeCmsEncodeThenDecode() { // Test ability to encrypt, encode and decode all in one EnvelopedCms instance. ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); }
/// <summary> /// Decrypt the encrypted data. /// </summary> /// <remarks> /// Decrypt the encrypted data. /// </remarks> /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns> /// <param name="encryptedData">The encrypted data.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="encryptedData"/> is <c>null</c>. /// </exception> /// <exception cref="System.Security.Cryptography.CryptographicException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override MimeEntity Decrypt (Stream encryptedData) { if (encryptedData == null) throw new ArgumentNullException ("encryptedData"); var enveloped = new EnvelopedCms (); enveloped.Decode (ReadAllBytes (encryptedData)); enveloped.Decrypt (); var decryptedData = enveloped.Encode (); var memory = new MemoryStream (decryptedData, false); return MimeEntity.Load (memory, true); }
private static byte[] CreateEcmsWithAttributes(params AsnEncodedData[] attributes) { ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); foreach (AsnEncodedData attribute in attributes) { ecms.UnprotectedAttributes.Add(attribute); } using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); return encodedMessage; }
private static void TestSimpleDecrypt_RoundTrip(CertLoader certLoader, ContentInfo contentInfo, string algorithmOidValue, SubjectIdentifierType type) { // Deep-copy the contentInfo since the real ContentInfo doesn't do this. This defends against a bad implementation changing // our "expectedContentInfo" to match what it produces. ContentInfo expectedContentInfo = new ContentInfo(new Oid(contentInfo.ContentType), (byte[])(contentInfo.Content.Clone())); string certSubjectName; byte[] encodedMessage; using (X509Certificate2 certificate = certLoader.GetCertificate()) { certSubjectName = certificate.Subject; AlgorithmIdentifier alg = new AlgorithmIdentifier(new Oid(algorithmOidValue)); EnvelopedCms ecms = new EnvelopedCms(contentInfo, alg); CmsRecipient cmsRecipient = new CmsRecipient(type, certificate); ecms.Encrypt(cmsRecipient); encodedMessage = ecms.Encode(); } // We don't pass "certificate" down because it's expected that the certificate used for encrypting doesn't have a private key (part of the purpose of this test is // to ensure that you don't need the recipient's private key to encrypt.) The decrypt phase will have to locate the matching cert with the private key. VerifySimpleDecrypt(encodedMessage, certLoader, expectedContentInfo); }
public static void DecryptMultipleRecipients() { // Force Decrypt() to try multiple recipients. Ensure that a failure to find a matching cert in one doesn't cause it to quit early. CertLoader[] certLoaders = new CertLoader[] { Certificates.RSAKeyTransfer1, Certificates.RSAKeyTransfer2, Certificates.RSAKeyTransfer3, }; byte[] content = { 6, 3, 128, 33, 44 }; EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), new AlgorithmIdentifier(new Oid(Oids.Aes256))); CmsRecipientCollection recipients = new CmsRecipientCollection(); foreach (CertLoader certLoader in certLoaders) { recipients.Add(new CmsRecipient(certLoader.GetCertificate())); } ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); // How do we know that Decrypt() tries receipients in the order they appear in ecms.RecipientInfos? Because we wrote the implementation. // Not that some future implementation can't ever change it but it's the best guess we have. RecipientInfo me = ecms.RecipientInfos[2]; CertLoader matchingCertLoader = null; for (int index = 0; index < recipients.Count; index++) { if (recipients[index].Certificate.Issuer == ((X509IssuerSerial)(me.RecipientIdentifier.Value)).IssuerName) { matchingCertLoader = certLoaders[index]; break; } } Assert.NotNull(matchingCertLoader); using (X509Certificate2 cert = matchingCertLoader.TryGetCertificateWithPrivateKey()) { if (cert == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(); extraStore.Add(cert); ecms.Decrypt(extraStore); } ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal<byte>(content, contentInfo.Content); }
private byte[] Envelope(byte[] contentBytes) { Pkcs.ContentInfo content = new Pkcs.ContentInfo(contentBytes); Pkcs.EnvelopedCms envMsg = new Pkcs.EnvelopedCms(content); Pkcs.CmsRecipient recipient = new Pkcs.CmsRecipient(Pkcs.SubjectIdentifierType.IssuerAndSerialNumber, _recipientCert); envMsg.Encrypt(recipient); byte[] encryptedBytes = envMsg.Encode(); return encryptedBytes; }
public static void PostDecrypt_Encode() { byte[] expectedContent = { 6, 3, 128, 33, 44 }; EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(expectedContent)); ecms.Encrypt(new CmsRecipient(Certificates.RSAKeyTransfer1.GetCertificate())); byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818067" + "6bada56dcaf2e65226941242db73b5a5420a6212cd6af662db52fdc0ca63875cb69066f7074da0fc009ce724e2d73fb19380" + "2deea8d92b069486a41c7c4fc3cd0174a918a559f79319039b40ae797bcacc909c361275ee2a5b1f0ff09fb5c19508e3f5ac" + "051ac0f03603c27fb8993d49ac428f8bcfc23a90ef9b0fac0f423a302b06092a864886f70d010701301406082a864886f70d" + "0307040828dc4d72ca3132e48008546cc90f2c5d4b79").HexToByteArray(); ecms.Decode(encodedMessage); using (X509Certificate2 cer = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { if (cer == null) return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can. X509Certificate2Collection extraStore = new X509Certificate2Collection(cer); RecipientInfoCollection r = ecms.RecipientInfos; ecms.Decrypt(r[0], extraStore); // Desktop compat: Calling Encode() at this point should have thrown an InvalidOperationException. Instead, it returns // the decrypted inner content (same as ecms.ContentInfo.Content). This is easy for someone to take a reliance on // so for compat sake, we'd better keep it. byte[] encoded = ecms.Encode(); Assert.Equal<byte>(expectedContent, encoded); } }
public static void ReuseEnvelopeCmsDecodeThenEncode() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } encodedMessage = ecms.Encode(); ecms.Decode(encodedMessage); RecipientInfoCollection recipients = ecms.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo; Assert.NotNull(recipientInfo); SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier; object value = subjectIdentifier.Value; Assert.True(value is X509IssuerSerial); X509IssuerSerial xis = (X509IssuerSerial)value; Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName); Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber); }
public static void PostCtor_Encode() { EnvelopedCms ecms = new EnvelopedCms(); Assert.Throws<InvalidOperationException>(() => ecms.Encode()); }
/// <summary> /// Encrypts the message and envelopes it for multiple recipients. /// </summary> /// <param name="recipients">An object containing the recipients' certificates with public keys.</param> /// <example> /// <code> /// [C#] /// /// CmsRecipientCollection recipients = new CmsRecipientCollection(); /// /// recipients.Add(new CmsRecipient(new X509Certificate2("C:\\recipient1.cer"))); /// recipients.Add(new CmsRecipient(new X509Certificate2("C:\\recipient2.cer"))); /// /// message.SmimeEnvelopeAndEncryptFor(recipients); /// </code> /// </example> public void SmimeEnvelopeAndEncryptFor(CmsRecipientCollection recipients) { string mimeString = this.ToMimeString(); byte[] toencrypt = Encoding.ASCII.GetBytes(mimeString); EnvelopedCms cms = new EnvelopedCms(new ContentInfo(toencrypt)); cms.Encrypt(recipients); MimePart envelope = new MimePart(); envelope.ContentType.MimeType = "application/pkcs7-mime"; envelope.ContentType.Parameters.Add("smime-type", "encrypted-data"); envelope.ContentType.Parameters.Add("name", "smime.p7m"); envelope.ContentDisposition.Disposition = "attachment"; envelope.ContentDisposition.FileName = "smime.p7m"; envelope.ContentTransferEncoding = ContentTransferEncoding.Base64; envelope.BinaryContent = cms.Encode(); this.PartTreeRoot = envelope; this.ContentType = this.PartTreeRoot.ContentType; this.ContentDisposition = this.PartTreeRoot.ContentDisposition; this.ContentTransferEncoding = this.PartTreeRoot.ContentTransferEncoding; }
public static byte[] Encrypt(byte[] data, X509Certificate2 encryptingCert) { ContentInfo plainContent = new ContentInfo(data); EnvelopedCms encryptedData = new EnvelopedCms(plainContent); CmsRecipient recipient = new CmsRecipient(encryptingCert); encryptedData.Encrypt(recipient); byte[] encryptedBytes = encryptedData.Encode(); return encryptedBytes; }
public void EncryptCmsRecipientUnknown () { ContentInfo ci = new ContentInfo (asnNull); EnvelopedCms ep = new EnvelopedCms (SubjectIdentifierType.IssuerAndSerialNumber, ci); X509Certificate2 x509 = GetCertificate (false); CmsRecipient p7r = new CmsRecipient (SubjectIdentifierType.Unknown, x509); ep.Encrypt (p7r); byte[] encoded = ep.Encode (); #if DEBUG FileStream fs = File.OpenWrite ("EncryptCmsRecipientUnknown.der"); fs.Write (encoded, 0, encoded.Length); fs.Close (); #endif RoundTrip (encoded); }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="encryptionCertificates"></param> /// <returns></returns> internal static byte[] EncryptMessage(Byte[] message, X509Certificate2Collection encryptionCertificates) { EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(message)); CmsRecipientCollection recipients = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, encryptionCertificates); envelopedCms.Encrypt(recipients); return envelopedCms.Encode(); }