/// <summary> /// Decrypts the specified string. /// </summary> /// <param name="ciphertext">The ciphertext to be decrypted.</param> /// <param name="certificates">A set of certificates containing the one that was used to encrypt the ciphertext.</param> /// <returns>The decrypted text.</returns> public static string Decrypt(this string ciphertext, params X509Certificate2[] certificates) { var certCollection = new X509Certificate2Collection(Settings.GetCertificatesFromStore().ToArray()); if (certificates != null && certificates.Length > 0) { certCollection.AddRange(certificates); } var envelopedCms = new EnvelopedCms(); envelopedCms.Decode(Convert.FromBase64String(ciphertext)); envelopedCms.Decrypt(certCollection); return(Encoding.UTF8.GetString(envelopedCms.ContentInfo.Content)); }
public static void DecodeRecipients3_RoundTrip() { ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo, KeyAgreeRecipientInfoTests.TripleDesAlgId); CmsRecipientCollection recipients = new CmsRecipientCollection(); foreach (X509Certificate2 cert in s_certs) { recipients.Add(new CmsRecipient(cert)); } ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); VerifyRecipients3(encodedMessage); }
public static void TestKeyAgreement_PlatformNotSupported() { ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.DHKeyAgree1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); CryptographicException e = Assert.Throws <CryptographicException>(() => ecms.Encrypt(cmsRecipient)); Assert.Contains(cert.GetKeyAlgorithm(), e.Message); } }
public static string Encrypt(string thumbprint, string value) { X509Certificate2 cert = GetCertificate(thumbprint); if (null != cert) { byte[] data = Encoding.UTF8.GetBytes(value); ContentInfo contentInfo = new ContentInfo(data); EnvelopedCms cms = new EnvelopedCms(contentInfo); CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert); cms.Encrypt(recipient); return(Convert.ToBase64String(cms.Encode())); } return(string.Empty); }
public static void EnvelopedCmsDecryptNullary() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); Assert.ThrowsAny <CryptographicException>(() => ecms.Decrypt()); }
/// <summary> /// Отображает содержимое CMS /// </summary> /// <param name="e"></param> /// <param name="displayContent"></param> private static void DisplayEnvelopedCms(EnvelopedCms e, Boolean displayContent) { //Console.WriteLine("\nEnveloped PKCS #7 Message Information:"); //Console.WriteLine("\tThe number of recipients for the Enveloped PKCS #7 " + "is: {0}", e.RecipientInfos.Count); /*for (int i = 0; i < e.RecipientInfos.Count; i++) * { * Console.WriteLine("\tRecipient #{0} has type {1}.", i + 1, e.RecipientInfos[i].RecipientIdentifier.Type); * }*/ if (displayContent) { DisplayEnvelopedCmsContent("Enveloped PKCS #7 Content", e); } //Console.WriteLine(); }
private byte[] Protect(byte[] data, X509Certificate2 encryptionCertificate) { // first we sign the message SignedCms signedCms = new SignedCms(new ContentInfo(data)); signedCms.ComputeSignature(new CmsSigner(SigningCertificate)); byte[] signedData = signedCms.Encode(); // then we encrypt it CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, encryptionCertificate); EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(signedData)); envelopedCms.Encrypt(cmsRecipient); return(envelopedCms.Encode()); }
public static byte[] DekrypterData(byte[] kryptertData) { /* Dette krever at man har lagret private key i lokal keystore (currentuser=>Personal) * openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 9999 -config C:\Slettmeg\openssl.cfg * openssl pkcs12 -inkey key.pem -in cert.pem -export -out cert.pfx * Eventuelt kan man bruke: * envelopedCms.Decrypt(envelopedCms.RecipientInfos[0],new X509Certificate2Collection(new X509Certificate2(@"..\..\..\cert.pfx","1234");)); * */ var envelopedCms = new EnvelopedCms(); envelopedCms.Decode(kryptertData); envelopedCms.Decrypt(envelopedCms.RecipientInfos[0]); return(envelopedCms.ContentInfo.Content); }
public static void PostEncrypt_Certs() { ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo); ecms.Certificates.Add(Certificates.RSAKeyTransfer2.GetCertificate()); ecms.Certificates.Add(Certificates.RSAKeyTransfer3.GetCertificate()); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(cert)); } Assert.Equal(Certificates.RSAKeyTransfer2.GetCertificate(), ecms.Certificates[0]); Assert.Equal(Certificates.RSAKeyTransfer3.GetCertificate(), ecms.Certificates[1]); }
public static void PostEncrypt_ContentInfo() { ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(expectedContentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(cert)); } // Encrypting does not update ContentInfo. ContentInfo actualContentInfo = ecms.ContentInfo; Assert.Equal(expectedContentInfo.ContentType, actualContentInfo.ContentType); Assert.Equal <byte>(expectedContentInfo.Content, actualContentInfo.Content); }
/// <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 void ButtonEncryptWithCER_Click(object sender, EventArgs e) { byte[] data = Encoding.UTF8.GetBytes(textBoxInfo.Text); ContentInfo contentInfo = new ContentInfo(data); X509Certificate2 cert = new X509Certificate2(fileCertCER); CmsRecipient cmsRecipient = new CmsRecipient(cert); EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo); envelopedCms.Encrypt(cmsRecipient); this.tempEnvelope = envelopedCms.Encode(); MessageBox.Show(Convert.ToBase64String(this.tempEnvelope)); }
public ActionResult SignAndEncrypt(SignedAsymmetricModel model) { if (model.Action == "encrypt") { var plainTextAsBytes = Encoding.Unicode.GetBytes(model.PlainText); var recipientCertificate = LoadCertificate(model.RecipientThumbprint); var signingCertificate = LoadCertificate(model.SenderThumbprint); // Sign message var signatureContentInfo = new ContentInfo(plainTextAsBytes); var signedCms = new SignedCms(signatureContentInfo); var cmsSigner = new CmsSigner(signingCertificate); signedCms.ComputeSignature(cmsSigner); var signedMessageAsBytes = signedCms.Encode(); // Encrypt var encryptedContentInfo = new ContentInfo(signedMessageAsBytes); var envelopedCms = new EnvelopedCms(encryptedContentInfo); var cmsRecipient = new CmsRecipient(recipientCertificate); envelopedCms.Encrypt(cmsRecipient); var envelopeAsBytes = envelopedCms.Encode(); model.Envelope = Convert.ToBase64String(envelopeAsBytes); model.PlainText = string.Empty; } else if (model.Action == "decrypt") { // Decrypt var cipherTextAsBytes = Convert.FromBase64String(model.Envelope); var envelopedCms = new EnvelopedCms(); envelopedCms.Decode(cipherTextAsBytes); envelopedCms.Decrypt(); var encodedSignedCMS = envelopedCms.Encode(); var signedCms = new SignedCms(); signedCms.Decode(encodedSignedCMS); signedCms.CheckSignature(true); var plainTextAsBytes = signedCms.ContentInfo.Content; model.PlainText = UnicodeEncoding.Unicode.GetString(plainTextAsBytes); model.SenderSubject = signedCms.SignerInfos[0].Certificate.Subject; model.Envelope = string.Empty; } model.RecipientThumbprint = RecipientThumbprint; model.SenderThumbprint = SenderThumbprint; ModelState.Clear(); return(View(model)); }
/// <summary> /// Metodo para desencriptar el certificado de seguridad /// </summary> /// <param name="bytDatos"></param> /// <returns></returns> ///<remarks> /// Autor: José Faustino Posas /// Company: Ssoft Colombia /// Fecha: 2012-01-16 /// ------------------- /// Control de Cambios /// ------------------- /// Autor: /// Fecha: /// Descripción: /// </remarks> public byte[] setCertificateFirmaEncryptedDecode(byte[] bytDatos) { try { EnvelopedCms objEncryptedData = new EnvelopedCms(); //Leemos los datos encriptados objEncryptedData.Decode(bytDatos); //Desencriptamos los datos objEncryptedData.Decrypt(); //Documento original byte[] bytDoc = objEncryptedData.ContentInfo.Content; return(bytDoc); //Mostramos el resultado //Debug.Print("Datos desencriptados: " + Encoding.ASCII.GetString(bytDoc)); } catch { return(null); } }
//Не производит обработку ошибок, выкидывает криптографические исключения public MimeReader Decrypt(X509Certificate2Collection certificates) { //необязательный параметр if (certificates == null) { certificates = new X509Certificate2Collection(); } var encodedEncryptedMessage = this.GetContent(); var envelopedCms = new EnvelopedCms(); envelopedCms.Decode(encodedEncryptedMessage); envelopedCms.Decrypt(certificates); var decryptedData = envelopedCms.Encode(); verifyValidCertificate(envelopedCms, certificates); return(createMimeReader(decryptedData)); }
public static void PostDecrypt_Decrypt() { byte[] expectedContent = { 6, 3, 128, 33, 44 }; byte[] encodedMessage = ("308202b006092a864886f70d010703a08202a13082029d020100318202583081c5020100302e301a31183016060355040313" + "0f5253414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004" + "81801026d9fb60d1a55686b73cf859c8bd66b58defda5e23e3da5f535f1427e3c5f7a4a2a94373e8e3ba5488a7c6a1059bfb" + "57301156698e7fca62671426d388fb3fb4373c9cb53132fda067598256bbfe8491b14dadaaf04d5fdfb2463f358ad0d6a594" + "bf6a4fbab6b3d725f08032e601492265e6336d5a638096f9975025ccd6393081c5020100302e301a31183016060355040313" + "0f5253414b65795472616e736665723202102bce9f9ece39f98044f0cd2faa9a14e7300d06092a864886f70d010101050004" + "8180b6497a2b789728f200ca1f974a676c531a4769f03f3929bd7526e7333ea483b4abb530a49c8532db5d4a4df66f173e3e" + "a4ba9e4814b584dc987ac87c46bb131daab535140968aafad8808100a2515e9c6d0c1f382b024992ce36b70b841628e0eb43" + "4db89545d702a8fbd3403188e7de7cb4bc1dcc3bc325467570654aaf2ee83081c5020100302e301a31183016060355040313" + "0f5253414b65795472616e736665723302104497d870785a23aa4432ed0106ef72a6300d06092a864886f70d010101050004" + "81807517e594c353d41abff334c6162988b78e05df7d79457c146fbc886d2d8057f594fa3a96cd8df5842c9758baac1fcdd5" + "d9672a9f8ef9426326cccaaf5954f2ae657f8c7b13aef2f811adb4954323aa8319a1e8f2ad4e5c96c1d3fbe413ae479e471b" + "b701cbdfa145c9b64f5e1f69f472804995d56c31351553f779cf8efec237303c06092a864886f70d010701301d0609608648" + "01650304012a041023a114c149d7d4017ce2f5ec7c5d53f980104e50ab3c15533743dd054ef3ff8b9d83").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert1 = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) using (X509Certificate2 cert2 = Certificates.RSAKeyTransfer2.TryGetCertificateWithPrivateKey()) using (X509Certificate2 cert3 = Certificates.RSAKeyTransfer3.TryGetCertificateWithPrivateKey()) { if (cert1 == null || cert2 == null || cert3 == 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(cert1); extraStore.Add(cert2); extraStore.Add(cert3); RecipientInfoCollection r = ecms.RecipientInfos; ecms.Decrypt(r[0], extraStore); ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal <byte>(expectedContent, contentInfo.Content); // Though this doesn't seem like a terribly unreasonable thing to attempt, attempting to call Decrypt() again // after a successful Decrypt() throws a CryptographicException saying "Already decrypted." Assert.ThrowsAny <CryptographicException>(() => ecms.Decrypt(r[1], extraStore)); } }
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); }
internal byte[] SignProject(ExcelVbaProject proj) { if (!Certificate.HasPrivateKey) { //throw (new InvalidOperationException("The certificate doesn't have a private key")); Certificate = null; return(null); } var hash = GetContentHash(proj); BinaryWriter bw = new BinaryWriter(new MemoryStream()); bw.Write((byte)0x30); //Constructed Type bw.Write((byte)0x32); //Total length bw.Write((byte)0x30); //Constructed Type bw.Write((byte)0x0E); //Length SpcIndirectDataContent bw.Write((byte)0x06); //Oid Tag Indentifier bw.Write((byte)0x0A); //Lenght OId bw.Write(new byte[] { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x1D }); //Encoded Oid 1.3.6.1.4.1.311.2.1.29 bw.Write((byte)0x04); //Octet String Tag Identifier bw.Write((byte)0x00); //Zero length bw.Write((byte)0x30); //Constructed Type (DigestInfo) bw.Write((byte)0x20); //Length DigestInfo bw.Write((byte)0x30); //Constructed Type (Algorithm) bw.Write((byte)0x0C); //length AlgorithmIdentifier bw.Write((byte)0x06); //Oid Tag Indentifier bw.Write((byte)0x08); //Lenght OId bw.Write(new byte[] { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05 }); //Encoded Oid for 1.2.840.113549.2.5 (AlgorithmIdentifier MD5) bw.Write((byte)0x05); //Null type identifier bw.Write((byte)0x00); //Null length bw.Write((byte)0x04); //Octet String Identifier bw.Write((byte)hash.Length); //Hash length bw.Write(hash); //Content hash ContentInfo contentInfo = new ContentInfo(((MemoryStream)bw.BaseStream).ToArray()); contentInfo.ContentType.Value = "1.3.6.1.4.1.311.2.1.4"; Verifier = new EnvelopedCms(contentInfo); var r = new CmsRecipient(Certificate); Verifier.Encrypt(r); return(Verifier.Encode()); }
/// <summary> /// Gets the CMS Message object. /// </summary> protected override void EndProcessing() { string actualContent = null; // Read in the content if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase)) { actualContent = _contentBuffer.ToString(); } else { actualContent = System.IO.File.ReadAllText(_resolvedPath); } // Extract out the bytes and Base64 decode them int startIndex, endIndex; byte[] contentBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out startIndex, out endIndex); if (contentBytes == null) { ErrorRecord error = new ErrorRecord( new ArgumentException(CmsCommands.InputContainedNoEncryptedContent), "InputContainedNoEncryptedContent", ErrorCategory.ObjectNotFound, null); ThrowTerminatingError(error); } EnvelopedCms cms = new EnvelopedCms(); cms.Decode(contentBytes); PSObject result = new PSObject(cms); List <object> recipients = new List <object>(); foreach (RecipientInfo recipient in cms.RecipientInfos) { recipients.Add(recipient.RecipientIdentifier.Value); } result.Properties.Add( new PSNoteProperty("Recipients", recipients)); result.Properties.Add( new PSNoteProperty("Content", actualContent)); WriteObject(result); }
public void EncryptAnswer(byte[] answerData) { X509Certificate2 certificate = GetAnswerCertificate(); ContentInfo contentInfo = new ContentInfo(answerData); EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo); CmsRecipient recipient = new CmsRecipient( SubjectIdentifierType.IssuerAndSerialNumber, certificate); envelopedCms.Encrypt(recipient); byte[] answer = envelopedCms.Encode(); dataEncrypted = Convert.ToBase64String(answer); sessionKeyIV = String.Empty; sessionKeyDiversData = String.Empty; encryptedSessionKey = String.Empty; }
/// <summary> /// Encrypts raw data and returns a <see cref="EnvelopedCms"/> instance with the encrypted data. /// </summary> /// <param name="content">The content to encrypt</param> /// <param name="encryptingCertificates">The collection of certificate used for encrytion</param> /// <returns>The encrypted <see cref="EnvelopedCms"/> instance.</returns> public EnvelopedCms CreateEncryptedEnvelope(byte[] content, X509Certificate2Collection encryptingCertificates) { if (content == null) { throw new EncryptionException(EncryptionError.NullContent); } if (encryptingCertificates == null || encryptingCertificates.Count == 0) { throw new EncryptionException(EncryptionError.NoCertificates); } CmsRecipientCollection recipients = new CmsRecipientCollection(SubjectIdentifierType.IssuerAndSerialNumber, encryptingCertificates); EnvelopedCms dataEnvelope = new EnvelopedCms(CreateDataContainer(content), ToAlgorithmID(m_encryptionAlgorithm)); dataEnvelope.Encrypt(recipients); return(dataEnvelope); }
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); }
public static void EnvelopedCmsEmptyDecode(bool useSpan) { EnvelopedCms cms = new EnvelopedCms(); if (useSpan) { #if !NET472 Assert.ThrowsAny <CryptographicException>(() => cms.Decode(ReadOnlySpan <byte> .Empty)); #else throw new Xunit.Sdk.XunitException( "This test should not evaluate for .NET Framework, the API is missing."); #endif } else { Assert.ThrowsAny <CryptographicException>(() => cms.Decode(Array.Empty <byte>())); } }
/// <summary> /// Decrypt a message using a private key available on the system. /// </summary> /// <param name="encodedEnvelopedCms">Encrypted blob</param> /// <returns>Decrypted data, or null if there was an error</returns> static public byte[] DecryptMsg(byte[] encodedEnvelopedCms) { // Prepare object in which to decode and decrypt. EnvelopedCms envelopedCms = new EnvelopedCms(); // Decode the message. envelopedCms.Decode(encodedEnvelopedCms); X509Store myStore = new X509Store(StoreName.My, StoreLocation.CurrentUser); myStore.Open(OpenFlags.ReadOnly); envelopedCms.Decrypt(myStore.Certificates); myStore.Close(); // The decrypted message occupies the ContentInfo property // after the Decrypt method is invoked. return(envelopedCms.ContentInfo.Content); }
//decrpts mime message bytes with a valid cert in the user cert store // returns the decrypted message as a string private string DecryptMessage(byte[] encryptedMessageBytes) { //get cert store and collection of valid certs X509Store store = new X509Store("MY", StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection fcollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByTimeValid, DateTime.Now, false); //decrypt bytes with EnvelopedCms EnvelopedCms ec = new EnvelopedCms(); ec.Decode(encryptedMessageBytes); ec.Decrypt(fcollection); byte[] decryptedData = ec.ContentInfo.Content; return(System.Text.Encoding.ASCII.GetString(decryptedData)); }
/// <summary> /// Encrypts the string supplied as -content on cmd-line, and encodes in base64 /// </summary> private static string Encrypt() { X509Certificate2 cert = new X509Certificate2(certFileName); string content = GetString(contentToEncrypt); var contentBytes = Encoding.UTF8.GetBytes(content); ContentInfo contentInfo = new ContentInfo(contentBytes); content = null; contentBytes = null; EnvelopedCms envelope = new EnvelopedCms(contentInfo); envelope.Encrypt(new CmsRecipient(cert)); string encryptedContent = Convert.ToBase64String(envelope.Encode()); return(encryptedContent); }
public static string Decrypt(string value) { try { byte[] data = Convert.FromBase64String(value); EnvelopedCms cms = new EnvelopedCms(); cms.Decode(data); var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); cms.Decrypt(store.Certificates); return(Encoding.UTF8.GetString(cms.Encode())); } catch (Exception ex) { Trace.TraceError(ex.Message); } return(string.Empty); }
public static void PostDecrypt_Encode(bool useExplicitPrivateKey) { 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. } RecipientInfoCollection r = ecms.RecipientInfos; if (useExplicitPrivateKey) { #if NETCOREAPP ecms.Decrypt(r[0], cer.GetRSAPrivateKey()); #else Assert.True(false, "Should not run on this platform"); #endif } else { X509Certificate2Collection extraStore = new X509Certificate2Collection(cer); 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 EncryptionAlgorithmAes128_IgnoresKeyLength() { // For .NET Framework compat, static key length ciphers ignore the key lengths supplied AlgorithmIdentifier algorithm = new AlgorithmIdentifier(new Oid(Oids.Aes128), 3); 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(); ecms.Decode(encodedMessage); Assert.Equal(Oids.Aes128, ecms.ContentEncryptionAlgorithm.Oid.Value); Assert.Equal(0, ecms.ContentEncryptionAlgorithm.KeyLength); }
public void EncryptToNegativeSerialNumber() { CertLoader negativeSerial = Certificates.NegativeSerialNumber; const string expectedSerial = "FD319CB1514B06AF49E00522277E43C8"; byte[] content = { 1, 2, 3 }; ContentInfo contentInfo = new ContentInfo(content); EnvelopedCms cms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = negativeSerial.GetCertificate()) { Assert.Equal(expectedSerial, cert.SerialNumber); CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert); cms.Encrypt(recipient); } EnvelopedCms cms2 = new EnvelopedCms(); cms2.Decode(cms.Encode()); RecipientInfoCollection recipients = cms2.RecipientInfos; Assert.Equal(1, recipients.Count); RecipientInfo recipientInfo = recipients[0]; Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, recipientInfo.RecipientIdentifier.Type); X509IssuerSerial issuerSerial = (X509IssuerSerial)recipientInfo.RecipientIdentifier.Value; Assert.Equal(expectedSerial, issuerSerial.SerialNumber); using (X509Certificate2 cert = negativeSerial.TryGetCertificateWithPrivateKey()) { Assert.Equal(expectedSerial, cert.SerialNumber); cms2.Decrypt(new X509Certificate2Collection(cert)); } Assert.Equal(content, cms2.ContentInfo.Content); }
private static unsafe int GetCspParams(RecipientInfo recipientInfo, X509Certificate2Collection extraStore, ref EnvelopedCms.CMSG_DECRYPT_PARAM cmsgDecryptParam) { int num = -2146889717; System.Security.Cryptography.SafeCertContextHandle certContextHandle = System.Security.Cryptography.SafeCertContextHandle.InvalidHandle; System.Security.Cryptography.SafeCertStoreHandle hCertStore = EnvelopedCms.BuildDecryptorStore(extraStore); switch (recipientInfo.Type) { case RecipientInfoType.KeyTransport: if (recipientInfo.SubType == RecipientSubType.Pkcs7KeyTransport) { certContextHandle = CAPI.CertFindCertificateInStore(hCertStore, 65537U, 0U, 720896U, recipientInfo.pCmsgRecipientInfo.DangerousGetHandle(), System.Security.Cryptography.SafeCertContextHandle.InvalidHandle); break; } else { CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO transRecipientInfo = (CAPI.CMSG_KEY_TRANS_RECIPIENT_INFO)recipientInfo.CmsgRecipientInfo; certContextHandle = CAPI.CertFindCertificateInStore(hCertStore, 65537U, 0U, 1048576U, new IntPtr((void*)&transRecipientInfo.RecipientId), System.Security.Cryptography.SafeCertContextHandle.InvalidHandle); break; } case RecipientInfoType.KeyAgreement: CAPI.CERT_ID recipientId = ((KeyAgreeRecipientInfo)recipientInfo).RecipientId; certContextHandle = CAPI.CertFindCertificateInStore(hCertStore, 65537U, 0U, 1048576U, new IntPtr((void*)&recipientId), System.Security.Cryptography.SafeCertContextHandle.InvalidHandle); break; default: num = -2147483647; break; } if (certContextHandle != null && !certContextHandle.IsInvalid) { SafeCryptProvHandle invalidHandle = SafeCryptProvHandle.InvalidHandle; uint pdwKeySpec = 0U; bool pfCallerFreeProv = false; CspParameters parameters = new CspParameters(); if (!X509Utils.GetPrivateKeyInfo(certContextHandle, ref parameters)) throw new CryptographicException(Marshal.GetLastWin32Error()); if (string.Compare(parameters.ProviderName, "Microsoft Base Cryptographic Provider v1.0", StringComparison.OrdinalIgnoreCase) == 0 && (CAPI.CryptAcquireContext(out invalidHandle, parameters.KeyContainerName, "Microsoft Enhanced Cryptographic Provider v1.0", 1U, 0U) || CAPI.CryptAcquireContext(out invalidHandle, parameters.KeyContainerName, "Microsoft Strong Cryptographic Provider", 1U, 0U))) cmsgDecryptParam.safeCryptProvHandle = invalidHandle; cmsgDecryptParam.safeCertContextHandle = certContextHandle; cmsgDecryptParam.keySpec = (uint)parameters.KeyNumber; num = 0; if (invalidHandle == null || invalidHandle.IsInvalid) { if (CAPI.CAPISafe.CryptAcquireCertificatePrivateKey(certContextHandle, 6U, IntPtr.Zero, out invalidHandle, out pdwKeySpec, out pfCallerFreeProv)) { if (!pfCallerFreeProv) GC.SuppressFinalize((object)invalidHandle); cmsgDecryptParam.safeCryptProvHandle = invalidHandle; } else num = Marshal.GetHRForLastWin32Error(); } } return num; }
private static unsafe void SetCmsRecipientParams(CmsRecipientCollection recipients, X509Certificate2Collection certificates, CryptographicAttributeObjectCollection unprotectedAttributes, AlgorithmIdentifier contentEncryptionAlgorithm, ref EnvelopedCms.CMSG_ENCRYPT_PARAM encryptParam) { uint[] numArray = new uint[recipients.Count]; int length = 0; int num1 = recipients.Count * Marshal.SizeOf(typeof(CAPI.CMSG_RECIPIENT_ENCODE_INFO)); int num2 = num1; for (int index = 0; index < recipients.Count; ++index) { numArray[index] = (uint)PkcsUtils.GetRecipientInfoType(recipients[index].Certificate); if ((int)numArray[index] == 1) { num2 += Marshal.SizeOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO)); } else { if ((int)numArray[index] != 2) throw new CryptographicException(-2146889726); ++length; num2 += Marshal.SizeOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO)); } } encryptParam.rgpRecipients = CAPI.LocalAlloc(64U, new IntPtr(num2)); encryptParam.rgCertEncoded = SafeLocalAllocHandle.InvalidHandle; encryptParam.rgUnprotectedAttr = SafeLocalAllocHandle.InvalidHandle; encryptParam.rgSubjectKeyIdentifier = new SafeLocalAllocHandle[recipients.Count]; encryptParam.rgszObjId = new SafeLocalAllocHandle[recipients.Count]; if (length > 0) { encryptParam.rgszKeyWrapObjId = new SafeLocalAllocHandle[length]; encryptParam.rgKeyWrapAuxInfo = new SafeLocalAllocHandle[length]; encryptParam.rgEphemeralIdentifier = new SafeLocalAllocHandle[length]; encryptParam.rgszEphemeralObjId = new SafeLocalAllocHandle[length]; encryptParam.rgUserKeyingMaterial = new SafeLocalAllocHandle[length]; encryptParam.prgpEncryptedKey = new SafeLocalAllocHandle[length]; encryptParam.rgpEncryptedKey = new SafeLocalAllocHandle[length]; } if (certificates.Count > 0) { encryptParam.rgCertEncoded = CAPI.LocalAlloc(64U, new IntPtr(certificates.Count * Marshal.SizeOf(typeof(CAPI.CRYPTOAPI_BLOB)))); for (int index = 0; index < certificates.Count; ++index) { CAPI.CERT_CONTEXT certContext = (CAPI.CERT_CONTEXT)Marshal.PtrToStructure(X509Utils.GetCertContext(certificates[index]).DangerousGetHandle(), typeof(CAPI.CERT_CONTEXT)); CAPI.CRYPTOAPI_BLOB* cryptoapiBlobPtr = (CAPI.CRYPTOAPI_BLOB*)(void*)new IntPtr((long)encryptParam.rgCertEncoded.DangerousGetHandle() + (long)(index * Marshal.SizeOf(typeof(CAPI.CRYPTOAPI_BLOB)))); cryptoapiBlobPtr->cbData = certContext.cbCertEncoded; cryptoapiBlobPtr->pbData = certContext.pbCertEncoded; } } if (unprotectedAttributes.Count > 0) encryptParam.rgUnprotectedAttr = new SafeLocalAllocHandle(PkcsUtils.CreateCryptAttributes(unprotectedAttributes)); int index1 = 0; IntPtr num3 = new IntPtr((long)encryptParam.rgpRecipients.DangerousGetHandle() + (long)num1); for (int index2 = 0; index2 < recipients.Count; ++index2) { CmsRecipient cmsRecipient = recipients[index2]; X509Certificate2 certificate = cmsRecipient.Certificate; CAPI.CERT_INFO certInfo = (CAPI.CERT_INFO)Marshal.PtrToStructure(((CAPI.CERT_CONTEXT)Marshal.PtrToStructure(X509Utils.GetCertContext(certificate).DangerousGetHandle(), typeof(CAPI.CERT_CONTEXT))).pCertInfo, typeof(CAPI.CERT_INFO)); CAPI.CMSG_RECIPIENT_ENCODE_INFO* recipientEncodeInfoPtr = (CAPI.CMSG_RECIPIENT_ENCODE_INFO*)(void*)new IntPtr((long)encryptParam.rgpRecipients.DangerousGetHandle() + (long)(index2 * Marshal.SizeOf(typeof(CAPI.CMSG_RECIPIENT_ENCODE_INFO)))); recipientEncodeInfoPtr->dwRecipientChoice = numArray[index2]; recipientEncodeInfoPtr->pRecipientInfo = num3; if ((int)numArray[index2] == 1) { Marshal.WriteInt32(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO), "cbSize")), Marshal.SizeOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO))); IntPtr num4 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO), "KeyEncryptionAlgorithm")); byte[] bytes = Encoding.ASCII.GetBytes(certInfo.SubjectPublicKeyInfo.Algorithm.pszObjId); encryptParam.rgszObjId[index2] = CAPI.LocalAlloc(64U, new IntPtr(bytes.Length + 1)); Marshal.Copy(bytes, 0, encryptParam.rgszObjId[index2].DangerousGetHandle(), bytes.Length); Marshal.WriteIntPtr(new IntPtr((long)num4 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "pszObjId")), encryptParam.rgszObjId[index2].DangerousGetHandle()); IntPtr num5 = new IntPtr((long)num4 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "Parameters")); IntPtr ptr1 = new IntPtr((long)num5 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData")); Marshal.WriteInt32(ptr1, (int)certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.cbData); IntPtr ptr2 = new IntPtr((long)num5 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData")); Marshal.WriteIntPtr(ptr2, certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.pbData); IntPtr num6 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO), "RecipientPublicKey")); ptr1 = new IntPtr((long)num6 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "cbData")); Marshal.WriteInt32(ptr1, (int)certInfo.SubjectPublicKeyInfo.PublicKey.cbData); ptr2 = new IntPtr((long)num6 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "pbData")); Marshal.WriteIntPtr(ptr2, certInfo.SubjectPublicKeyInfo.PublicKey.pbData); Marshal.WriteInt32(new IntPtr((long)num6 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "cUnusedBits")), (int)certInfo.SubjectPublicKeyInfo.PublicKey.cUnusedBits); IntPtr num7 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO), "RecipientId")); if (cmsRecipient.RecipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier) { uint pcbData = 0U; SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle; if (!CAPI.CAPISafe.CertGetCertificateContextProperty(X509Utils.GetCertContext(certificate), 20U, invalidHandle, out pcbData)) throw new CryptographicException(Marshal.GetLastWin32Error()); SafeLocalAllocHandle pvData = CAPI.LocalAlloc(64U, new IntPtr((long)pcbData)); if (!CAPI.CAPISafe.CertGetCertificateContextProperty(X509Utils.GetCertContext(certificate), 20U, pvData, out pcbData)) throw new CryptographicException(Marshal.GetLastWin32Error()); encryptParam.rgSubjectKeyIdentifier[index2] = pvData; Marshal.WriteInt32(new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "dwIdChoice")), 2); IntPtr num8 = new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "Value")); ptr1 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData")); Marshal.WriteInt32(ptr1, (int)pcbData); ptr2 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData")); Marshal.WriteIntPtr(ptr2, pvData.DangerousGetHandle()); } else { Marshal.WriteInt32(new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "dwIdChoice")), 1); IntPtr num8 = new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "Value")); IntPtr num9 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ISSUER_SERIAL_NUMBER), "Issuer")); ptr1 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData")); Marshal.WriteInt32(ptr1, (int)certInfo.Issuer.cbData); ptr2 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData")); Marshal.WriteIntPtr(ptr2, certInfo.Issuer.pbData); IntPtr num10 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ISSUER_SERIAL_NUMBER), "SerialNumber")); ptr1 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData")); Marshal.WriteInt32(ptr1, (int)certInfo.SerialNumber.cbData); ptr2 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData")); Marshal.WriteIntPtr(ptr2, certInfo.SerialNumber.pbData); } num3 = new IntPtr((long)num3 + (long)Marshal.SizeOf(typeof(CAPI.CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO))); } else if ((int)numArray[index2] == 2) { IntPtr ptr1 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "cbSize")); Marshal.WriteInt32(ptr1, Marshal.SizeOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO))); IntPtr num4 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "KeyEncryptionAlgorithm")); byte[] bytes1 = Encoding.ASCII.GetBytes("1.2.840.113549.1.9.16.3.5"); encryptParam.rgszObjId[index2] = CAPI.LocalAlloc(64U, new IntPtr(bytes1.Length + 1)); Marshal.Copy(bytes1, 0, encryptParam.rgszObjId[index2].DangerousGetHandle(), bytes1.Length); IntPtr ptr2 = new IntPtr((long)num4 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "pszObjId")); Marshal.WriteIntPtr(ptr2, encryptParam.rgszObjId[index2].DangerousGetHandle()); IntPtr num5 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "KeyWrapAlgorithm")); uint num6 = X509Utils.OidToAlgId(contentEncryptionAlgorithm.Oid.Value); byte[] source = (int)num6 != 26114 ? Encoding.ASCII.GetBytes("1.2.840.113549.1.9.16.3.6") : Encoding.ASCII.GetBytes("1.2.840.113549.1.9.16.3.7"); encryptParam.rgszKeyWrapObjId[index1] = CAPI.LocalAlloc(64U, new IntPtr(source.Length + 1)); Marshal.Copy(source, 0, encryptParam.rgszKeyWrapObjId[index1].DangerousGetHandle(), source.Length); ptr2 = new IntPtr((long)num5 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "pszObjId")); Marshal.WriteIntPtr(ptr2, encryptParam.rgszKeyWrapObjId[index1].DangerousGetHandle()); if ((int)num6 == 26114) Marshal.WriteIntPtr(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "pvKeyWrapAuxInfo")), encryptParam.pvEncryptionAuxInfo.DangerousGetHandle()); Marshal.WriteInt32(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "dwKeyChoice")), 1); IntPtr ptr3 = new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "pEphemeralAlgorithmOrSenderId")); encryptParam.rgEphemeralIdentifier[index1] = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER)))); Marshal.WriteIntPtr(ptr3, encryptParam.rgEphemeralIdentifier[index1].DangerousGetHandle()); byte[] bytes2 = Encoding.ASCII.GetBytes(certInfo.SubjectPublicKeyInfo.Algorithm.pszObjId); encryptParam.rgszEphemeralObjId[index1] = CAPI.LocalAlloc(64U, new IntPtr(bytes2.Length + 1)); Marshal.Copy(bytes2, 0, encryptParam.rgszEphemeralObjId[index1].DangerousGetHandle(), bytes2.Length); ptr2 = new IntPtr((long)encryptParam.rgEphemeralIdentifier[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "pszObjId")); Marshal.WriteIntPtr(ptr2, encryptParam.rgszEphemeralObjId[index1].DangerousGetHandle()); IntPtr num7 = new IntPtr((long)encryptParam.rgEphemeralIdentifier[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_ALGORITHM_IDENTIFIER), "Parameters")); IntPtr ptr4 = new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData")); Marshal.WriteInt32(ptr4, (int)certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.cbData); IntPtr ptr5 = new IntPtr((long)num7 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData")); Marshal.WriteIntPtr(ptr5, certInfo.SubjectPublicKeyInfo.Algorithm.Parameters.pbData); Marshal.WriteInt32(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "cRecipientEncryptedKeys")), 1); encryptParam.prgpEncryptedKey[index1] = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(IntPtr)))); Marshal.WriteIntPtr(new IntPtr((long)num3 + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO), "rgpRecipientEncryptedKeys")), encryptParam.prgpEncryptedKey[index1].DangerousGetHandle()); encryptParam.rgpEncryptedKey[index1] = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO)))); Marshal.WriteIntPtr(encryptParam.prgpEncryptedKey[index1].DangerousGetHandle(), encryptParam.rgpEncryptedKey[index1].DangerousGetHandle()); ptr1 = new IntPtr((long)encryptParam.rgpEncryptedKey[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO), "cbSize")); Marshal.WriteInt32(ptr1, Marshal.SizeOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO))); IntPtr num8 = new IntPtr((long)encryptParam.rgpEncryptedKey[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO), "RecipientPublicKey")); ptr4 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "cbData")); Marshal.WriteInt32(ptr4, (int)certInfo.SubjectPublicKeyInfo.PublicKey.cbData); ptr5 = new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "pbData")); Marshal.WriteIntPtr(ptr5, certInfo.SubjectPublicKeyInfo.PublicKey.pbData); Marshal.WriteInt32(new IntPtr((long)num8 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPT_BIT_BLOB), "cUnusedBits")), (int)certInfo.SubjectPublicKeyInfo.PublicKey.cUnusedBits); IntPtr num9 = new IntPtr((long)encryptParam.rgpEncryptedKey[index1].DangerousGetHandle() + (long)Marshal.OffsetOf(typeof(CAPI.CMSG_RECIPIENT_ENCRYPTED_KEY_ENCODE_INFO), "RecipientId")); IntPtr ptr6 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "dwIdChoice")); if (cmsRecipient.RecipientIdentifierType == SubjectIdentifierType.SubjectKeyIdentifier) { Marshal.WriteInt32(ptr6, 2); IntPtr num10 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "Value")); uint pcbData = 0U; SafeLocalAllocHandle invalidHandle = SafeLocalAllocHandle.InvalidHandle; if (!CAPI.CAPISafe.CertGetCertificateContextProperty(X509Utils.GetCertContext(certificate), 20U, invalidHandle, out pcbData)) throw new CryptographicException(Marshal.GetLastWin32Error()); SafeLocalAllocHandle pvData = CAPI.LocalAlloc(64U, new IntPtr((long)pcbData)); if (!CAPI.CAPISafe.CertGetCertificateContextProperty(X509Utils.GetCertContext(certificate), 20U, pvData, out pcbData)) throw new CryptographicException(Marshal.GetLastWin32Error()); encryptParam.rgSubjectKeyIdentifier[index1] = pvData; ptr4 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData")); Marshal.WriteInt32(ptr4, (int)pcbData); ptr5 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData")); Marshal.WriteIntPtr(ptr5, pvData.DangerousGetHandle()); } else { Marshal.WriteInt32(ptr6, 1); IntPtr num10 = new IntPtr((long)num9 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ID), "Value")); IntPtr num11 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ISSUER_SERIAL_NUMBER), "Issuer")); ptr4 = new IntPtr((long)num11 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData")); Marshal.WriteInt32(ptr4, (int)certInfo.Issuer.cbData); ptr5 = new IntPtr((long)num11 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData")); Marshal.WriteIntPtr(ptr5, certInfo.Issuer.pbData); IntPtr num12 = new IntPtr((long)num10 + (long)Marshal.OffsetOf(typeof(CAPI.CERT_ISSUER_SERIAL_NUMBER), "SerialNumber")); ptr4 = new IntPtr((long)num12 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "cbData")); Marshal.WriteInt32(ptr4, (int)certInfo.SerialNumber.cbData); ptr5 = new IntPtr((long)num12 + (long)Marshal.OffsetOf(typeof(CAPI.CRYPTOAPI_BLOB), "pbData")); Marshal.WriteIntPtr(ptr5, certInfo.SerialNumber.pbData); } ++index1; num3 = new IntPtr((long)num3 + (long)Marshal.SizeOf(typeof(CAPI.CMSG_KEY_AGREE_RECIPIENT_ENCODE_INFO))); } } }
private static void SetCspParams(AlgorithmIdentifier contentEncryptionAlgorithm, ref EnvelopedCms.CMSG_ENCRYPT_PARAM encryptParam) { encryptParam.safeCryptProvHandle = SafeCryptProvHandle.InvalidHandle; encryptParam.pvEncryptionAuxInfo = SafeLocalAllocHandle.InvalidHandle; SafeCryptProvHandle invalidHandle = SafeCryptProvHandle.InvalidHandle; if (!CAPI.CryptAcquireContext(ref invalidHandle, IntPtr.Zero, IntPtr.Zero, 1U, 4026531840U)) throw new CryptographicException(Marshal.GetLastWin32Error()); uint algId = X509Utils.OidToAlgId(contentEncryptionAlgorithm.Oid.Value); switch (algId) { case 26114U: case 26625U: CAPI.CMSG_RC2_AUX_INFO cmsgRc2AuxInfo = new CAPI.CMSG_RC2_AUX_INFO(Marshal.SizeOf(typeof(CAPI.CMSG_RC2_AUX_INFO))); uint num = (uint)contentEncryptionAlgorithm.KeyLength; if ((int)num == 0) num = (uint)PkcsUtils.GetMaxKeyLength(invalidHandle, algId); cmsgRc2AuxInfo.dwBitLen = num; SafeLocalAllocHandle localAllocHandle = CAPI.LocalAlloc(64U, new IntPtr(Marshal.SizeOf(typeof(CAPI.CMSG_RC2_AUX_INFO)))); Marshal.StructureToPtr((object)cmsgRc2AuxInfo, localAllocHandle.DangerousGetHandle(), false); encryptParam.pvEncryptionAuxInfo = localAllocHandle; break; } encryptParam.safeCryptProvHandle = invalidHandle; }
private static void SetPkcs7RecipientParams(CmsRecipientCollection recipients, ref EnvelopedCms.CMSG_ENCRYPT_PARAM encryptParam) { uint num = (uint)(recipients.Count * Marshal.SizeOf(typeof(IntPtr))); encryptParam.rgpRecipients = CAPI.LocalAlloc(64U, new IntPtr((long)num)); IntPtr ptr = encryptParam.rgpRecipients.DangerousGetHandle(); for (int index = 0; index < recipients.Count; ++index) { CAPI.CERT_CONTEXT certContext = (CAPI.CERT_CONTEXT)Marshal.PtrToStructure(X509Utils.GetCertContext(recipients[index].Certificate).DangerousGetHandle(), typeof(CAPI.CERT_CONTEXT)); Marshal.WriteIntPtr(ptr, certContext.pCertInfo); ptr = new IntPtr((long)ptr + (long)Marshal.SizeOf(typeof(IntPtr))); } }