/// <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 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 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); }
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 void VerifySimpleDecrypt(byte[] encodedMessage, CertLoader certLoader, ContentInfo expectedContent) { EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = certLoader.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(cert); ecms.Decrypt(extraStore); ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal(expectedContent.ContentType.Value, contentInfo.ContentType.Value); Assert.Equal <byte>(expectedContent.Content, contentInfo.Content); } }
public static void TestUnprotectedAttributes_AlwaysReturnsPkcs9AttributeObject() { byte[] encodedMessage = CreateEcmsWithAttributes( new AsnEncodedData(new Oid(Oids.Pkcs7Data), new byte[] { 4, 3, 6, 7, 8 }) ); // ecms.Decode() always populates UnprotectedAttribute objects with Pkcs9AttributeObjects (or one of its derived classes) rather than // AsnEncodedData instances. Verify that any new implementation does this as someone out there is probably // casting to Pkcs9AttributeObject without checking. EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); AsnEncodedData[] attributes = ecms.UnprotectedAttributes.FlattenAndSort(); Assert.Equal(1, attributes.Length); AsnEncodedData a = attributes[0]; Assert.True(a is Pkcs9AttributeObject); }
public static void EnvelopedCmsDecryptNullExtraStore() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfo recipientInfo = ecms.RecipientInfos[0]; X509Certificate2Collection extraStore = null; Assert.Throws <ArgumentNullException>(() => ecms.Decrypt(extraStore)); Assert.Throws <ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore)); }
/// <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 store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var certCollection = store.Certificates; 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)); }
/// <summary> /// Decrypt the encoded EnvelopedCms message. /// </summary> /// <param name="encodedEnvelopedCms">Array of bytes containing the encrypted message</param> /// <returns>Array of bytes containing the decrypted message</returns> protected Byte[] DecryptMsg(byte[] encodedEnvelopedCms) { // Prepare object in which to decode and decrypt. EnvelopedCms envelopedCms = new EnvelopedCms(); // Decode the message. envelopedCms.Decode(encodedEnvelopedCms); // Display the number of recipients the message is enveloped for; it should be 1 for this example. //DisplayEnvelopedCms(envelopedCms, false); // Decrypt the message for the single recipient. Note that the following call to the Decrypt method // accomplishes the same result: envelopedCms.Decrypt(); //Console.Write("Decrypting Data ... "); envelopedCms.Decrypt(envelopedCms.RecipientInfos[0]); //Console.WriteLine("Done."); return(envelopedCms.Encode()); }
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 ISecurable DecryptContent(ISecurable pStr) { byte[] sBytes = pStr.GetBytes(); byte[] content = StringSecurer.FromBase64BytesToBytes(sBytes); var cms = new EnvelopedCms(); cms.Decode(content); try { cms.Decrypt(); } catch (Exception ex) { throw new ProtectedStringDecryptionException(ex); } var pts = StringSecurer.FromBase64Bytes(cms.ContentInfo.Content); return(pts); }
private static void VerifyRecipients3(byte[] encodedMessage) { string[] expectedIssuers = s_certs.Select(c => c.Issuer).OrderBy(s => s).ToArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); RecipientInfoCollection col = ecms.RecipientInfos; int numRecipients = col.Count; Assert.Equal(3, numRecipients); RecipientInfo[] recipients = new RecipientInfo[numRecipients]; col.CopyTo(recipients, 0); string[] actualIssuers = recipients.Select(r => r.RecipientIdentifier.Value).Cast <X509IssuerSerial>().Select(xis => xis.IssuerName).OrderBy(s => s).ToArray(); Assert.Equal <string>(expectedIssuers, actualIssuers); }
public static void DecodeAlgorithmRc4_40_FixedValue() { byte[] encodedMessage = ("3082011006092A864886F70D010703A08201013081FE0201003181CC3081C90201003032301E311C301A060" + "355040313135253414B65795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA30" + "0D06092A864886F70D01010105000481809D242C1517B82A58335E0337B0B2CE97B2789AF31A6B31311417B" + "A069D0D76FD08AE5B4F58C290116667FFD00319AA7AFED4EEAD9D5031C0D17A48E6CB39A5EB62C8BD7F4C2C" + "BE8E581EF8B7FF7BA9376923A367B9B7E031F630E4CA6ADCB31209B04B03E64076FB0465E7E437B13D4AEA2" + "70CA89EB58C1A598F0AC88DCB4024302A06092A864886F70D010701301706082A864886F70D0304040B4B5A" + "8F64D714F933642D4A8004C68A936F").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); AlgorithmIdentifier algorithm = ecms.ContentEncryptionAlgorithm; Assert.NotNull(algorithm.Oid); Assert.Equal(Oids.Rc4, algorithm.Oid.Value); Assert.Equal(40, algorithm.KeyLength); }
/// <summary> /// Decrypts the contents of the decoded enveloped CMS/PKCS #7 message by using the private key associated with the certificate identified. /// </summary> /// <param name="encodedMessage">An array of byte values that represent the information to be decoded.</param> /// <param name="certificate">The certificate used to decrypt the encoded message.</param> /// <returns>Cryptographic message syntax information.</returns> public CmsInfo Decrypt(byte[] encodedMessage, X509Certificate2 certificate) { // Decode and decrypt. _cms.Decode(encodedMessage); _cms.Decrypt(new X509Certificate2Collection(certificate)); // CMS information. Cryptography.CmsInfo cmsInfo = new Cryptography.CmsInfo(); // Set the newly set members, cmsInfo.Certificates = _cms.Certificates; cmsInfo.ContentEncryptionAlgorithm = _cms.ContentEncryptionAlgorithm; cmsInfo.ContentInfo = _cms.ContentInfo; cmsInfo.RecipientInfos = _cms.RecipientInfos; cmsInfo.UnprotectedAttributes = _cms.UnprotectedAttributes; cmsInfo.Version = _cms.Version; // Return the information. return(cmsInfo); }
public static string Decrypt(string fullMessage) { string messageContent = GetContentInBase64(fullMessage); // Load envelope and decrypt EnvelopedCms envelope = new EnvelopedCms(); envelope.Decode(Convert.FromBase64String(messageContent)); envelope.Decrypt(); // Get original bytes byte[] decryptedBytes = envelope.ContentInfo.Content; string decryptedText = Encoding.ASCII.GetString(decryptedBytes); // Get processed Base64 content byte[] decryptedContentBytes = Convert.FromBase64String(GetContentInBase64(decryptedText)); string decryptedContentText = Encoding.UTF8.GetString(decryptedContentBytes); return(decryptedContentText); }
private static void ValidateZeroLengthContent(byte[] encodedMessage) { EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey()) { if (cert == null) { return; } X509Certificate2Collection extraStore = new X509Certificate2Collection(cert); ecms.Decrypt(extraStore); ContentInfo contentInfo = ecms.ContentInfo; byte[] content = contentInfo.Content; int expected = PlatformDetection.IsFullFramework ? 6 : 0; // Desktop bug gives 6 Assert.Equal(expected, content.Length); } }
public static void Encrypt_Data_DoesNotIncreaseInSize() { byte[] content = new byte[15]; // One short of AES block size boundary ContentInfo contentInfo = new ContentInfo(content); AlgorithmIdentifier identifier = new AlgorithmIdentifier(new Oid(Oids.Aes128)); EnvelopedCms ecms = new EnvelopedCms(contentInfo, identifier); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient recipient = new CmsRecipient(cert); ecms.Encrypt(recipient); } byte[] encoded = ecms.Encode(); EnvelopedCms reDecoded = new EnvelopedCms(); reDecoded.Decode(encoded); int expectedSize = PlatformDetection.IsNetFramework ? 22 : 16; //NetFx compat. Assert.Equal(expectedSize, reDecoded.ContentInfo.Content.Length); }
/// <summary> /// Расшифровать данные и получить массив байт /// </summary> /// <param name="data"></param> /// <returns></returns> public byte[] DecryptByteArray(byte[] data) { byte[] byteResult = null; try { EnvelopedCms envelopedCms = new EnvelopedCms(); envelopedCms.Decode(data); envelopedCms.Decrypt(envelopedCms.RecipientInfos[0]); byteResult = envelopedCms.ContentInfo.Content; } catch (Exception exp) { Log.DssLogger.Error($"Ошибка при зашифровании строки: {exp}"); byteResult = null; } return(byteResult); }
/// <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()))); }
/// <summary> /// Decrypts the specified encryptedData to an output stream. /// </summary> /// <remarks> /// Decrypts the specified encryptedData to an output stream. /// </remarks> /// <param name="encryptedData">The encrypted data.</param> /// <param name="output">The output stream.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="encryptedData"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="output"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.Security.Cryptography.CryptographicException"> /// An error occurred in the cryptographic message syntax subsystem. /// </exception> public override void DecryptTo(Stream encryptedData, Stream output) { if (encryptedData == null) { throw new ArgumentNullException(nameof(encryptedData)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } var enveloped = new EnvelopedCms(); enveloped.Decode(ReadAllBytes(encryptedData)); enveloped.Decrypt(); var decryptedData = enveloped.Encode(); output.Write(decryptedData, 0, decryptedData.Length); }
private void ButtonDecryptFromStore_Click(object sender, EventArgs e) { EnvelopedCms envelopedCms = new EnvelopedCms(); try { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certs = X509Certificate2UI.SelectFromCollection(store.Certificates, "Certificates", "Choose one certificate...", X509SelectionFlag.SingleSelection); store.Close(); if (certs.Count == 1) { envelopedCms.Decode(tempEnvelope); envelopedCms.Decrypt(certs); MessageBox.Show("Message decrypted!" + Environment.NewLine + Encoding.UTF8.GetString(envelopedCms.ContentInfo.Content)); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static void PostDecode_ContentInfo() { byte[] encodedMessage = ("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253" + "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e" + "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c" + "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4" + "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d" + "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); // This gets you the encrypted inner content. ContentInfo contentInfo = ecms.ContentInfo; Assert.Equal(Oids.Pkcs7Data, contentInfo.ContentType.Value); byte[] expectedGarbage = "35edc437e31d0b70".HexToByteArray(); AssertEncryptedContentEqual(expectedGarbage, contentInfo.Content); }
/// <summary> /// Decrypts the given data with the given certificate /// </summary> /// <param name="toDecrypt">Data to encrypt</param> /// <param name="decryptionCert">Certificate to encrypt with</param> /// <returns>The decrypted data</returns> public byte[] DecryptWithCertificate(byte[] toDecrypt, X509Certificate2 decryptionCert) { if (toDecrypt == null) { throw new ArgumentNullException(nameof(toDecrypt)); } if (decryptionCert == null) { throw new ArgumentNullException(nameof(decryptionCert)); } X509Certificate2Collection decryptCerts = new X509Certificate2Collection(decryptionCert); ContentInfo contentInfo = new ContentInfo(toDecrypt); EnvelopedCms cms = new EnvelopedCms(contentInfo); cms.Decode(contentInfo.Content); cms.Decrypt(decryptCerts); return(cms.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 #if !NETCOREAPP EnvelopedCms ec = new EnvelopedCms(); ec.Decode(encryptedMessageBytes); ec.Decrypt(fcollection); byte[] decryptedData = ec.ContentInfo.Content; return(System.Text.Encoding.ASCII.GetString(decryptedData)); #else throw new XstException("CMS decoding not supported on this platform"); #endif }
public static void DecodeAlgorithmRc2_40_RoundTrip() { ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3, 4 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(new Oid(Oids.Rc2), 40)); using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert)); } byte[] encodedMessage = ecms.Encode(); ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); AlgorithmIdentifier algorithm = ecms.ContentEncryptionAlgorithm; Assert.NotNull(algorithm.Oid); Assert.Equal(Oids.Rc2, algorithm.Oid.Value); Assert.Equal(40, algorithm.KeyLength); }
public static void PostDecrypt_RecipientInfos() { 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 col1 = ecms.RecipientInfos; ecms.Decrypt(col1[0], extraStore); // Make sure we can still RecipientInfos after a Decrypt() RecipientInfoCollection col2 = ecms.RecipientInfos; Assert.Equal(col1.Count, col2.Count); RecipientInfo r1 = col1[0]; RecipientInfo r2 = col2[0]; X509IssuerSerial is1 = (X509IssuerSerial)(r1.RecipientIdentifier.Value); X509IssuerSerial is2 = (X509IssuerSerial)(r2.RecipientIdentifier.Value); Assert.Equal(is1.IssuerName, is2.IssuerName); Assert.Equal(is1.SerialNumber, is2.SerialNumber); } }
public static void DecodeAlgorithmRc2_40_FixedValue() { ContentInfo expectedContentInfo = new ContentInfo(new byte[] { 1, 2, 3, 4 }); byte[] encodedMessage = ("3082011806092A864886F70D010703A0820109308201050201003181CC3081C90201003032301E311C301A0" + "60355040313135253414B65795472616E73666572436170693102105D2FFFF863BABC9B4D3C80AB178A4CCA" + "300D06092A864886F70D010101050004818004E46A48651034B01134B0D4F665C9E85F6C45B58458ECDBAFE" + "B6B55CBFA9AEBEFA52BCBEF3C8811B5118970562623FC35D4B733B55CBC50DA4F49822E1D198834897D3540" + "7B329FECF49277159F2FEAB31173004776B03746381E0DA660B6D656A861E54E79186F36F450105DEB2714D" + "02DB5500921EBE4F1A7D3DFB07E4EE9303106092A864886F70D010701301A06082A864886F70D0302300E02" + "0200A00408D621253C94AF659B800802930ACE6A997122").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encodedMessage); AlgorithmIdentifier algorithm = ecms.ContentEncryptionAlgorithm; Assert.NotNull(algorithm.Oid); Assert.Equal(Oids.Rc2, algorithm.Oid.Value); Assert.Equal(40, algorithm.KeyLength); }
/// <summary> /// Расшифровать массив данных /// </summary> /// <param name="data"></param> /// <returns></returns> public string[] DecryptStringArray(byte[] data) { string[] result = null; try { EnvelopedCms envelopedCms = new EnvelopedCms(); envelopedCms.Decode(data); envelopedCms.Decrypt(envelopedCms.RecipientInfos[0]); byte[] byteResult = envelopedCms.ContentInfo.Content; result = new List <string>(byteResult.BytesToList <string>()).ToArray(); } catch (Exception exp) { Log.DssLogger.Error($"Ошибка при зашифровании строки: {exp}"); result = null; } return(result); }
public static void PostEncode_DifferentData() { // This ensures that the decoding and encoding output different values to make sure Encrypt changes the state of the data. byte[] encoded = ("3082010206092A864886F70D010703A081F43081F10201003181C83081C5020100302E301A311830160603550403130F" + "5253414B65795472616E7366657231021031D935FB63E8CFAB48A0BF7B397B67C0300D06092A864886F70D0101010500" + "04818009C16B674495C2C3D4763189C3274CF7A9142FBEEC8902ABDC9CE29910D541DF910E029A31443DC9A9F3B05F02" + "DA1C38478C400261C734D6789C4197C20143C4312CEAA99ECB1849718326D4FC3B7FBB2D1D23281E31584A63E99F2C17" + "132BCD8EDDB632967125CD0A4BAA1EFA8CE4C855F7C093339211BDF990CEF5CCE6CD74302106092A864886F70D010701" + "301406082A864886F70D03070408779B3DE045826B18").HexToByteArray(); EnvelopedCms ecms = new EnvelopedCms(); ecms.Decode(encoded); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { ecms.Encrypt(new CmsRecipient(cert)); } byte[] encrypted = ecms.Encode(); Assert.NotEqual <byte>(encoded, encrypted); }
public void Decode() { byte[] encoded = { 0x30, 0x82, 0x01, 0x1C, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x03, 0xA0, 0x82, 0x01, 0x0D, 0x30, 0x82, 0x01, 0x09, 0x02, 0x01, 0x00, 0x31, 0x81, 0xD6, 0x30, 0x81, 0xD3, 0x02, 0x01, 0x00, 0x30, 0x3C, 0x30, 0x28, 0x31, 0x26, 0x30, 0x24, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x1D, 0x4D, 0x6F, 0x74, 0x75, 0x73, 0x20, 0x54, 0x65, 0x63, 0x68, 0x6E, 0x6F, 0x6C, 0x6F, 0x67, 0x69, 0x65, 0x73, 0x20, 0x69, 0x6E, 0x63, 0x2E, 0x28, 0x74, 0x65, 0x73, 0x74, 0x29, 0x02, 0x10, 0x91, 0xC4, 0x4B, 0x0D, 0xB7, 0xD8, 0x10, 0x84, 0x42, 0x26, 0x71, 0xB3, 0x97, 0xB5, 0x00, 0x97, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x81, 0x80, 0xCA, 0x4B, 0x97, 0x9C, 0xAB, 0x79, 0xC6, 0xDF, 0x6A, 0x27, 0xC7, 0x24, 0xC4, 0x5E, 0x3B, 0x31, 0xAD, 0xBC, 0x25, 0xE6, 0x38, 0x5E, 0x79, 0x26, 0x0E, 0x68, 0x46, 0x1D, 0x21, 0x81, 0x38, 0x92, 0xEC, 0xCB, 0x7C, 0x91, 0xD6, 0x09, 0x38, 0x91, 0xCE, 0x50, 0x5B, 0x70, 0x31, 0xB0, 0x9F, 0xFC, 0xE2, 0xEE, 0x45, 0xBC, 0x4B, 0xF8, 0x9A, 0xD9, 0xEE, 0xE7, 0x4A, 0x3D, 0xCD, 0x8D, 0xFF, 0x10, 0xAB, 0xC8, 0x19, 0x05, 0x54, 0x5E, 0x40, 0x7A, 0xBE, 0x2B, 0xD7, 0x22, 0x97, 0xF3, 0x23, 0xAF, 0x50, 0xF5, 0xEB, 0x43, 0x06, 0xC3, 0xFB, 0x17, 0xCA, 0xBD, 0xAD, 0x28, 0xD8, 0x10, 0x0F, 0x61, 0xCE, 0xF8, 0x25, 0x70, 0xF6, 0xC8, 0x1E, 0x7F, 0x82, 0xE5, 0x94, 0xEB, 0x11, 0xBF, 0xB8, 0x6F, 0xEE, 0x79, 0xCD, 0x63, 0xDD, 0x59, 0x8D, 0x25, 0x0E, 0x78, 0x55, 0xCE, 0x21, 0xBA, 0x13, 0x6B, 0x30, 0x2B, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01, 0x30, 0x14, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x03, 0x07, 0x04, 0x08, 0x8C, 0x5D, 0xC9, 0x87, 0x88, 0x9C, 0x05, 0x72, 0x80, 0x08, 0x2C, 0xAF, 0x82, 0x91, 0xEC, 0xAD, 0xC5, 0xB5 }; EnvelopedCms ep = new EnvelopedCms(); ep.Decode(encoded); // properties Assert.AreEqual(0, ep.Certificates.Count, "Certificates"); Assert.AreEqual(192, ep.ContentEncryptionAlgorithm.KeyLength, "ContentEncryptionAlgorithm.KeyLength"); Assert.AreEqual(tdesName, ep.ContentEncryptionAlgorithm.Oid.FriendlyName, "ContentEncryptionAlgorithm.Oid.FriendlyName"); Assert.AreEqual(tdesOid, ep.ContentEncryptionAlgorithm.Oid.Value, "ContentEncryptionAlgorithm.Oid.Value"); Assert.AreEqual(16, ep.ContentEncryptionAlgorithm.Parameters.Length, "ContentEncryptionAlgorithm.Parameters"); Assert.AreEqual(p7DataName, ep.ContentInfo.ContentType.FriendlyName, "ContentInfo.ContentType.FriendlyName"); Assert.AreEqual(p7DataOid, ep.ContentInfo.ContentType.Value, "ContentInfo.ContentType.Value"); Assert.AreEqual(14, ep.ContentInfo.Content.Length, "ContentInfo.Content"); Assert.AreEqual(1, ep.RecipientInfos.Count, "RecipientInfos"); RecipientInfo ri = ep.RecipientInfos [0]; Assert.IsTrue((ri is KeyTransRecipientInfo), "RecipientInfos is KeyTransRecipientInfo"); Assert.AreEqual(0, ep.UnprotectedAttributes.Count, "UnprotectedAttributes"); Assert.AreEqual(0, ep.Version, "Version"); }