public static void SignerInfo_AddRemoveUnsignedAttributes_JoinCounterSignaturesAttributesIntoOne() { byte[] message = { 1, 2, 3, 4, 5 }; ContentInfo content = new ContentInfo(message); SignedCms cms = new SignedCms(content); using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert); cms.ComputeSignature(signer); } using (X509Certificate2 counterSigner1cert = Certificates.Dsa1024.TryGetCertificateWithPrivateKey()) { CmsSigner counterSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner1cert); counterSigner.IncludeOption = X509IncludeOption.EndCertOnly; counterSigner.DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1); cms.SignerInfos[0].ComputeCounterSignature(counterSigner); } using (X509Certificate2 counterSigner2cert = Certificates.ECDsaP256Win.TryGetCertificateWithPrivateKey()) { CmsSigner counterSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner2cert); cms.SignerInfos[0].ComputeCounterSignature(counterSigner); } Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[1].Values.Count); cms.CheckSignature(true); AsnEncodedData counterSignature = cms.SignerInfos[0].UnsignedAttributes[0].Values[0]; cms.SignerInfos[0].RemoveUnsignedAttribute(counterSignature); cms.SignerInfos[0].AddUnsignedAttribute(counterSignature); Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count); Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count); cms.CheckSignature(true); }
public void SignedCmsRoundTripWithBouncyCastleLocalCertificate() { var content = "This is some content"; // Get cert var netcert = GetLocalSignerCert(); var chain = new X509Chain(); chain.Build(netcert); // Get the chain without the root CA var additionals = chain.ChainElements.Cast <X509ChainElement>() .Where(ce => ce.Certificate.Issuer != ce.Certificate.SubjectName.Name) .Select(ce => DotNetUtilities.FromX509Certificate(ce.Certificate)) .ToList(); chain.Dispose(); var bcCer = DotNetUtilities.FromX509Certificate(netcert); var bcKey = DotNetUtilities.GetRsaKeyPair(netcert.GetRSAPrivateKey()); var store = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(additionals)); var generator = new CmsSignedDataGenerator(); var builder = new SignerInfoGeneratorBuilder(); var b = builder.Build(new Asn1SignatureFactory("SHA256WITHRSA", bcKey.Private), bcCer); generator.AddSignerInfoGenerator(b); // generator.AddSigner(bcKey.Private, bcCer, CmsSignedDataGenerator.DigestSha256); generator.AddCertificates(store); var msg = new CmsProcessableByteArray(Encoding.UTF8.GetBytes(content)); var data = generator.Generate(msg, true); var encoded = data.GetEncoded(); var signedCms = new SignedCms(); signedCms.Decode(encoded); signedCms.CheckSignature(true); // don't validate the certiciate itself here var cContent = signedCms.ContentInfo.Content; var str = Encoding.UTF8.GetString(cContent); Assert.Equal(content, str); }
public static void ReadAndWriteDocumentWithIndefiniteLengthContent(bool checkSignature) { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.IndefiniteLengthContentDocument); if (checkSignature) { cms.CheckSignature(true); } cms.Encode(); }
public static void RemoveCounterSignature_EncodedInSingleAttribute(int indexToRemove) { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1TwoCounterSignaturesInSingleAttribute); SignerInfo signerInfo = cms.SignerInfos[0]; Assert.Equal(2, signerInfo.CounterSignerInfos.Count); signerInfo.RemoveCounterSignature(indexToRemove); Assert.Equal(1, signerInfo.CounterSignerInfos.Count); cms.CheckSignature(true); }
public void CheckSignatureDetachedSignedCms() { string path = Path.Combine("Test", "System.Security.Cryptography.Pkcs"); var signedBytes = File.ReadAllBytes(Path.Combine(path, "detached.data")); var bytes = File.ReadAllBytes(Path.Combine(path, "detached.p7")); var oid = new Oid("1.2.840.113549.1.7.2"); var contentInfo = new ContentInfo(oid, signedBytes); var signedCms = new SignedCms(contentInfo, true); signedCms.Decode(bytes); signedCms.CheckSignature(true); }
private void BtnVerifica_Click(object sender, RoutedEventArgs e) { SignedCms signedCms = new SignedCms(); try { signedCms.Decode(Convert.FromBase64String(txtSalida.Text)); signedCms.CheckSignature(true); txtVerificar.Text = "Valido"; consola.Text = Encoding.UTF8.GetString(signedCms.ContentInfo.Content); } catch (Exception ex) { txtVerificar.Text = "Invalido"; } }
private bool verifySignedCms(byte[] dataSignature, SignedCms signedCms) { bool result = false; //取得首張簽章者憑證 _cert = signedCms.SignerInfos[0].Certificate; X509Certificate2 cert2 = signedCms.SignerInfos[0].Certificate; // new X509Certificate2(_cert); if (dataSignature != null) { beforeVerify(System.Text.Encoding.Default.GetString(signedCms.ContentInfo.Content), Convert.ToBase64String(dataSignature), cert2); } else { beforeVerify(System.Text.Encoding.Default.GetString(signedCms.ContentInfo.Content), String.Empty, cert2); } #region 驗簽 try { signedCms.CheckSignature(true); if (VerifySignatureOnly) { result = true; } else { result = verifySignerCertificate(cert2); } } catch (Exception ex) { Logger.Error(ex); _log.Message = "簽章驗證失敗:" + ex.Message; } #endregion if (result) { Logger.Info(_ds); } else { Logger.Warn(_ds); } return(result); }
private static async Task <KrbAuthPack> ValidateAuthPack(IKerberosPrincipal principal, KrbPaPkAsReq pkreq) { SignedCms signedCms = new SignedCms(); signedCms.Decode(pkreq.SignedAuthPack.ToArray()); signedCms.CheckSignature(verifySignatureOnly: true); await principal.Validate(signedCms.Certificates); var authPack = KrbAuthPack.Decode(signedCms.ContentInfo.Content); return(authPack); }
public static void AddFirstCounterSigner_NoSignature() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); SignerInfo firstSigner = cms.SignerInfos[0]; // A certificate shouldn't really be required here, but on .NET Framework // it will prompt for the counter-signer's certificate if it's null, // even if the signature type is NoSignature. using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { firstSigner.ComputeCounterSignature( new CmsSigner( SubjectIdentifierType.NoSignature, cert) { IncludeOption = X509IncludeOption.None, }); } Assert.ThrowsAny <CryptographicException>(() => cms.CheckSignature(true)); cms.CheckHash(); byte[] encoded = cms.Encode(); cms = new SignedCms(); cms.Decode(encoded); Assert.ThrowsAny <CryptographicException>(() => cms.CheckSignature(true)); cms.CheckHash(); firstSigner = cms.SignerInfos[0]; firstSigner.CheckSignature(verifySignatureOnly: true); Assert.ThrowsAny <CryptographicException>(() => firstSigner.CheckHash()); SignerInfo firstCounterSigner = firstSigner.CounterSignerInfos[0]; Assert.ThrowsAny <CryptographicException>(() => firstCounterSigner.CheckSignature(true)); if (PlatformDetection.IsFullFramework) { // NetFX's CheckHash only looks at top-level SignerInfos to find the // crypt32 CMS signer ID, so it fails on any check from a countersigner. Assert.ThrowsAny <CryptographicException>(() => firstCounterSigner.CheckHash()); } else { firstCounterSigner.CheckHash(); } }
public void TestInvalidContent() { // changed "foobar" to "modified content" ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes("modified content")); SignedCms signedCms = new SignedCms(contentInfo, true); signedCms.Decode(Convert.FromBase64String(ValidSig.signature)); // Check without verifying cert signedCms.CheckSignature(true); // Should throw an exception and stop }
private TimestampInformation GetTimestampInformation(X509Native.AXL_AUTHENTICODE_TIMESTAMPER_INFO timestamper, XmlElement licenseNode) { Debug.Assert(licenseNode != null, "licenseNode != null"); TimestampInformation timestamp = null; // If the timestamper is a trusted publisher, then CAPI has done the work for us; // If the leaf certificate is not explicitly a trusted publisher, CAPI will not process // the timestamp information so we will verify it ourselves. In any other case, we will // return no timestamp information. if (timestamper.dwError == (int)SignatureVerificationResult.Valid) { timestamp = new TimestampInformation(timestamper); } else if (timestamper.dwError == (int)SignatureVerificationResult.CertificateNotExplicitlyTrusted || timestamper.dwError == (int)SignatureVerificationResult.MissingSignature) { XmlElement timestampElement = licenseNode.SelectSingleNode("r:issuer/ds:Signature/ds:Object/as:Timestamp", m_namespaceManager) as XmlElement; if (timestampElement != null) { // The timestamp is held as a parameter of a base64 encoded PKCS7 message in the signature byte[] timestampBlob = Convert.FromBase64String(timestampElement.InnerText); try { SignedCms timestampCms = new SignedCms(); timestampCms.Decode(timestampBlob); timestampCms.CheckSignature(true); // The SignedCms class does not expose a way to read arbitrary properties from the // message, nor does it expose the HCRYPTMSG to P/Invoke with. We cannot access the // actual timestamp because of this, so for signatures which are not created by a // trusted publisher, we will return a null timestamp. This should be corrected in // v3 of the CLR, as we can extend SignedCms to have the properties we need to // pull all of this information. timestamp = null; } catch (CryptographicException e) { timestamp = new TimestampInformation((SignatureVerificationResult)Marshal.GetHRForException(e)); } } } else { timestamp = null; } return(timestamp); }
public void TestInvalidSignature() { ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes("foobar")); SignedCms signedCms = new SignedCms(contentInfo, true); // Mess up the signature signedCms.Decode(Convert.FromBase64String(ValidSig.signature.Replace('A', 'B'))); // Check without verifying cert signedCms.CheckSignature(true); // Should throw an exception and stop }
public static void AddCounterSignerToUnsortedAttributeSignature() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.DigiCertTimeStampToken); // Assert.NoThrows cms.CheckSignature(true); SignerInfoCollection signers = cms.SignerInfos; Assert.Equal(1, signers.Count); SignerInfo signerInfo = signers[0]; using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { signerInfo.ComputeCounterSignature( new CmsSigner( SubjectIdentifierType.IssuerAndSerialNumber, cert)); signerInfo.ComputeCounterSignature( new CmsSigner( SubjectIdentifierType.SubjectKeyIdentifier, cert)); } // Assert.NoThrows cms.CheckSignature(true); byte[] exported = cms.Encode(); cms = new SignedCms(); cms.Decode(exported); // Assert.NoThrows cms.CheckSignature(true); }
public async void SignedCmsRoundTripWithKeyVault() { using (var materialized = await KeyVaultConfigurationDiscoverer.Materialize(certificateConfiguration)) { var content = "This is some content"; var publicCert = materialized.PublicCertificate; // Get cert var chain = new X509Chain(); chain.Build(publicCert); // Get the chain without the root CA var additionals = chain.ChainElements.Cast <X509ChainElement>() .Where(ce => ce.Certificate.Issuer != ce.Certificate.SubjectName.Name) .Select(ce => DotNetUtilities.FromX509Certificate(ce.Certificate)) .ToList(); chain.Dispose(); var bcCer = DotNetUtilities.FromX509Certificate(publicCert); var store = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(additionals)); var generator = new CmsSignedDataGenerator(); var builder = new SignerInfoGeneratorBuilder(); var b = builder.Build(new RsaSignatureFactory("SHA256WITHRSA", materialized.ToRSA()), bcCer); generator.AddSignerInfoGenerator(b); generator.AddCertificates(store); var msg = new CmsProcessableByteArray(Encoding.UTF8.GetBytes(content)); var data = generator.Generate(msg, true); var encoded = data.GetEncoded(); var signedCms = new SignedCms(); signedCms.Decode(encoded); signedCms.CheckSignature(true); // don't validate the certiciate itself here var cContent = signedCms.ContentInfo.Content; var str = Encoding.UTF8.GetString(cContent); Assert.Equal(content, str); } }
static void Test_CheckSignature1(byte[] encodedMessage) { //<Snippet1> // Create a new, nondetached SignedCms message. SignedCms signedCms = new SignedCms(); // encodedMessage is the encoded message received from // the sender. signedCms.Decode(encodedMessage); // Verify the signature without validating the // certificate. signedCms.CheckSignature(true); //</Snippet1> }
public static bool IsVerified(this X509Certificate2 iCertificate, byte[] iSignature) { SignedCms verifyCms = new SignedCms(); verifyCms.Decode(iSignature); try { verifyCms.CheckSignature(new X509Certificate2Collection(iCertificate), false); return(true); } catch (CryptographicException) { return(false); } }
public static byte[] VerifyAndRemoveSignature(byte[] data) { var signedMessage = new SignedCms(); signedMessage.Decode(data); signedMessage.CheckSignature(false); foreach (SignerInfo signer in signedMessage.SignerInfos) { Console.WriteLine("Subject: {0}", signer.Certificate.Subject); } return(signedMessage.ContentInfo.Content); }
public void CheckSignatureCmsSignerUnknown() { byte[] signature = { 0x30, 0x82, 0x03, 0x4C, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02, 0xA0, 0x82, 0x03, 0x3D, 0x30, 0x82, 0x03, 0x39, 0x02, 0x01, 0x01, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x30, 0x11, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x04, 0x04, 0x02, 0x05, 0x00, 0xA0, 0x82, 0x02, 0x2E, 0x30, 0x82, 0x02, 0x2A, 0x30, 0x82, 0x01, 0x97, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x10, 0x91, 0xC4, 0x4B, 0x0D, 0xB7, 0xD8, 0x10, 0x84, 0x42, 0x26, 0x71, 0xB3, 0x97, 0xB5, 0x00, 0x97, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1D, 0x05, 0x00, 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, 0x30, 0x1E, 0x17, 0x0D, 0x30, 0x33, 0x30, 0x38, 0x31, 0x33, 0x30, 0x30, 0x34, 0x33, 0x34, 0x37, 0x5A, 0x17, 0x0D, 0x33, 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5A, 0x30, 0x13, 0x31, 0x11, 0x30, 0x0F, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x08, 0x46, 0x41, 0x52, 0x53, 0x43, 0x41, 0x50, 0x45, 0x30, 0x81, 0x9F, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8D, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xD2, 0xCB, 0x47, 0x21, 0xF5, 0x62, 0xDD, 0x35, 0xBF, 0x1D, 0xEC, 0x9A, 0x4C, 0x07, 0x2C, 0x01, 0xF0, 0x28, 0xC2, 0x82, 0x17, 0x8E, 0x58, 0x32, 0xD5, 0x4C, 0xAC, 0x86, 0xB4, 0xC9, 0xEB, 0x21, 0x26, 0xF3, 0x22, 0x30, 0xC5, 0x7A, 0xA3, 0x5A, 0xDD, 0x53, 0xAB, 0x1C, 0x06, 0x3E, 0xB2, 0x13, 0xC4, 0x05, 0x1D, 0x95, 0x8B, 0x0A, 0x71, 0x71, 0x11, 0xA7, 0x47, 0x26, 0x61, 0xF1, 0x76, 0xBE, 0x35, 0x72, 0x32, 0xC5, 0xCB, 0x47, 0xA4, 0x22, 0x41, 0x1E, 0xAD, 0x29, 0x11, 0x0D, 0x39, 0x22, 0x0C, 0x79, 0x90, 0xC6, 0x52, 0xA1, 0x10, 0xF6, 0x55, 0x09, 0x4E, 0x51, 0x26, 0x47, 0x0E, 0x94, 0xE6, 0x81, 0xF5, 0x18, 0x6B, 0x99, 0xF0, 0x76, 0xF3, 0xB2, 0x4C, 0x91, 0xE9, 0xBA, 0x3B, 0x3F, 0x6E, 0x63, 0xDA, 0x12, 0xD1, 0x0B, 0x73, 0x0E, 0x12, 0xC7, 0x70, 0x77, 0x22, 0x03, 0x9D, 0x5D, 0x02, 0x03, 0x01, 0x00, 0x01, 0xA3, 0x72, 0x30, 0x70, 0x30, 0x13, 0x06, 0x03, 0x55, 0x1D, 0x25, 0x04, 0x0C, 0x30, 0x0A, 0x06, 0x08, 0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x30, 0x59, 0x06, 0x03, 0x55, 0x1D, 0x01, 0x04, 0x52, 0x30, 0x50, 0x80, 0x10, 0xAE, 0xD7, 0x80, 0x88, 0xA6, 0x3D, 0xBA, 0x50, 0xA1, 0x7E, 0x57, 0xE5, 0x40, 0xC9, 0x6F, 0xC5, 0xA1, 0x2A, 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, 0x82, 0x10, 0x9D, 0xAE, 0xA3, 0x39, 0x47, 0x0E, 0xD4, 0xA2, 0x49, 0x78, 0xEA, 0x6C, 0xBA, 0x0D, 0xDE, 0x9C, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1D, 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x32, 0x8A, 0x7E, 0xAD, 0xE7, 0x67, 0x9E, 0x5C, 0x4C, 0xD8, 0x33, 0x59, 0x68, 0xCF, 0x94, 0xC0, 0x36, 0x47, 0x7A, 0xA7, 0x85, 0xC2, 0xDD, 0xD8, 0xDA, 0x11, 0x3C, 0x66, 0xC1, 0x83, 0xE3, 0xAB, 0x33, 0x06, 0x7C, 0xE3, 0x6A, 0x15, 0x72, 0xB8, 0x83, 0x3D, 0x0B, 0xAB, 0x3C, 0xEE, 0x75, 0x13, 0xBD, 0x5C, 0x96, 0x25, 0x56, 0x36, 0x05, 0xFA, 0xAE, 0xD4, 0xF4, 0xCF, 0x52, 0xEC, 0x11, 0xB5, 0xEA, 0x9F, 0x20, 0xA3, 0xC8, 0x34, 0x72, 0x59, 0x09, 0x51, 0xE7, 0x36, 0x87, 0x86, 0x86, 0x98, 0xB5, 0x30, 0x7B, 0xFB, 0x3D, 0xCC, 0x5E, 0xE8, 0xC9, 0x49, 0xE0, 0xC6, 0xEA, 0x02, 0x76, 0x01, 0xE0, 0xBB, 0x8A, 0x70, 0xEB, 0x07, 0x86, 0xE8, 0x04, 0xE7, 0x48, 0xE4, 0x6C, 0x90, 0xE6, 0x16, 0x42, 0xB4, 0xBB, 0xC0, 0xC4, 0x82, 0x5F, 0xF8, 0xFB, 0x7E, 0xB2, 0x9E, 0xC2, 0x78, 0x26, 0x86, 0x31, 0x81, 0xE1, 0x30, 0x81, 0xDE, 0x02, 0x01, 0x01, 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, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x81, 0x80, 0x45, 0x88, 0x80, 0x58, 0xC7, 0x4F, 0xE4, 0xD8, 0x88, 0xB0, 0xC0, 0x08, 0x70, 0x84, 0xCC, 0x8E, 0xA7, 0xF1, 0xA4, 0x07, 0x41, 0x14, 0x3E, 0xF5, 0xEA, 0x6E, 0x05, 0x75, 0xB8, 0x58, 0xAA, 0x5C, 0x0E, 0xFD, 0x7A, 0x07, 0x09, 0xE1, 0x80, 0x94, 0xBD, 0xAA, 0x45, 0xBB, 0x55, 0x9C, 0xC2, 0xD9, 0x72, 0x14, 0x4B, 0xA4, 0x64, 0xFB, 0x38, 0x9F, 0xD3, 0x22, 0xED, 0xB3, 0x0B, 0xF7, 0xAE, 0x4D, 0xE6, 0x65, 0x4D, 0x2A, 0x31, 0x18, 0xB5, 0xB4, 0x2D, 0x9E, 0x4E, 0xD7, 0xC0, 0x44, 0x5F, 0xAC, 0x43, 0xDC, 0x4F, 0x3D, 0x6D, 0x2C, 0x8C, 0xA1, 0xFE, 0x08, 0x38, 0xB7, 0xC4, 0xC4, 0x08, 0xDB, 0xF8, 0xF0, 0xC1, 0x55, 0x54, 0x49, 0x9D, 0xA4, 0x7F, 0x76, 0xDE, 0xF4, 0x29, 0x1C, 0x0B, 0x95, 0x10, 0x90, 0xB5, 0x0A, 0x9A, 0xEC, 0xCA, 0x89, 0x9A, 0x85, 0x92, 0x76, 0x78, 0x6F, 0x97, 0x67 }; SignedCms sp = new SignedCms(); sp.Decode(signature); sp.CheckSignature(true); CheckSignatureProperties(sp, 1); }
public void ParsePaPkAsRep_SignedDHRep_KDCDHKeyInfo() { KrbPaPkAsRep asrep = KrbPaPkAsRep.Decode(signedPkAsRep); Assert.IsNotNull(asrep); SignedCms signed = new SignedCms(); signed.Decode(asrep.DHInfo.DHSignedData.ToArray()); signed.CheckSignature(verifySignatureOnly: true); KrbKdcDHKeyInfo keyInfo = KrbKdcDHKeyInfo.Decode(signed.ContentInfo.Content); Assert.IsNotNull(keyInfo); }
public bool Verify(byte[] data, byte[] signature) { var signedCms = new SignedCms(); signedCms.Decode(signature); try { signedCms.CheckSignature(_certificate2Collection, false); } catch (Exception e) { return(false); } return(signedCms.ContentInfo.Content.SequenceEqual(_md5.ComputeHash(data))); }
private void ButtonVerifySignatureWithoutData_Click(object sender, EventArgs e) { ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(textBoxInfo.Text)); SignedCms signedCms = new SignedCms(contentInfo, true); try { signedCms.Decode(this.tempDigitalSignature); signedCms.CheckSignature(false); // false = integridade + autenticação // true = integridade MessageBox.Show("Valid signature"); } catch (Exception ex) { MessageBox.Show("Invalid Signature"); } }
public async Task TimestampSignatureAsync_TimestampingCountersignature_Succeeds() { var logger = new TestLogger(); var timestampService = await _testFixture.GetDefaultTrustedTimestampServiceAsync(); var timestampProvider = new Rfc3161TimestampProvider(timestampService.Url); var signatureContent = new SignatureContent(SigningSpecifications.V1, Common.HashAlgorithmName.SHA256, "Test data to be signed and timestamped"); using (var authorCert = new X509Certificate2(_trustedTestCert.Source.Cert)) { var timestampHashAlgorithm = Common.HashAlgorithmName.SHA256; var signedCms = SigningTestUtility.GenerateRepositoryCountersignedSignedCms(authorCert, signatureContent.GetBytes()); var signature = PrimarySignature.Load(signedCms.Encode()); var signatureValue = signature.GetSignatureValue(); var messageHash = timestampHashAlgorithm.ComputeHash(signatureValue); var request = new TimestampRequest( SigningSpecifications.V1, messageHash, timestampHashAlgorithm, SignaturePlacement.Countersignature); // Act var primarySignature = await timestampProvider.TimestampSignatureAsync(signature, request, logger, CancellationToken.None); var repositoryCountersignature = RepositoryCountersignature.GetRepositoryCountersignature(primarySignature); // Assert repositoryCountersignature.Should().NotBeNull(); repositoryCountersignature.SignerInfo.Should().NotBeNull(); repositoryCountersignature.SignerInfo.UnsignedAttributes.Count.Should().BeGreaterOrEqualTo(1); var hasTimestampUnsignedAttribute = false; var timestampCms = new SignedCms(); foreach (var attr in repositoryCountersignature.SignerInfo.UnsignedAttributes) { if (string.Compare(attr.Oid.Value, Oids.SignatureTimeStampTokenAttribute, CultureInfo.CurrentCulture, CompareOptions.Ordinal) == 0) { hasTimestampUnsignedAttribute = true; timestampCms.Decode(attr.Values[0].RawData); } } hasTimestampUnsignedAttribute.Should().BeTrue(); timestampCms.CheckSignature(verifySignatureOnly: true); } }
public static void AddCounterSigner_DuplicateCert_RSA() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); Assert.Single(cms.Certificates); SignerInfo firstSigner = cms.SignerInfos[0]; Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert); firstSigner.ComputeCounterSignature(signer); } Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); SignerInfo firstSigner2 = cms.SignerInfos[0]; Assert.Single(firstSigner2.CounterSignerInfos); Assert.Single(firstSigner2.UnsignedAttributes); SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0]; Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, counterSigner.SignerIdentifier.Type); // On NetFx there will be two attributes, because Windows emits the // content-type attribute even for counter-signers. int expectedAttrCount = 1; // One of them is a V3 signer. #if netfx expectedAttrCount = 2; #endif Assert.Equal(expectedAttrCount, counterSigner.SignedAttributes.Count); Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedAttrCount - 1].Oid.Value); Assert.Equal(firstSigner2.Certificate, counterSigner.Certificate); Assert.Single(cms.Certificates); counterSigner.CheckSignature(true); firstSigner2.CheckSignature(true); cms.CheckSignature(true); }
public override bool VerifyFile(string filePath, ref List <KeyValuePair <X509Certificate2, bool> > verifiedCMS) { byte[] DataDigest = new byte[0]; byte[] EncodedCMS = new byte[0]; //digest of the data without the signature(s) DataDigest = Hash(filePath); //signatures found in the file List <String> Signatures = ExtractAllSignatures(filePath); if (Signatures.Count < 1) { throw new NoSignatureFoundException(filePath); } //Content information created from the data digest ContentInfo StepContent = new ContentInfo(DataDigest); SignedCms SignedCMS = new SignedCms(StepContent, true); List <KeyValuePair <X509Certificate2, bool> > UsedCertificates = new List <KeyValuePair <X509Certificate2, bool> >(); bool Validation = true; foreach (String Signature in Signatures) { SignedCMS.Decode(Convert.FromBase64String(Signature)); SignerInfoEnumerator Enumerator = SignedCMS.SignerInfos.GetEnumerator(); if (!Enumerator.MoveNext()) { throw new InvalidSignerInformationException(Signature); } try { //after decoding the signed cms, we check the signature SignedCMS.CheckSignature(true); UsedCertificates.Add(new KeyValuePair <X509Certificate2, bool>(Enumerator.Current.Certificate, true)); } catch (System.Security.Cryptography.CryptographicException e) { //signature can't be verified UsedCertificates.Add(new KeyValuePair <X509Certificate2, bool>(Enumerator.Current.Certificate, false)); Validation = false; } } verifiedCMS = UsedCertificates; return(Validation); }
public static void VerifyUnsortedAttributeSignature_ImportExportImport() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.DigiCertTimeStampToken); // Assert.NoThrows cms.CheckSignature(true); byte[] exported = cms.Encode(); cms = new SignedCms(); cms.Decode(exported); // Assert.NoThrows cms.CheckSignature(true); }
private void ButtonVerifySignatureWithData_Click(object sender, EventArgs e) { SignedCms signedCms = new SignedCms(); try { signedCms.Decode(tempDigitalSignature); signedCms.CheckSignature(true); string data = Encoding.UTF8.GetString(signedCms.ContentInfo.Content); MessageBox.Show("Assinatura Válida." + Environment.NewLine + data); } catch (Exception) { MessageBox.Show("Assinatura Inválida!"); throw; } }
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)); }
public static void AddCounterSigner_RSA(SubjectIdentifierType identifierType) { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); Assert.Single(cms.Certificates); SignerInfo firstSigner = cms.SignerInfos[0]; Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(identifierType, signerCert); firstSigner.ComputeCounterSignature(signer); } Assert.Empty(firstSigner.CounterSignerInfos); Assert.Empty(firstSigner.UnsignedAttributes); SignerInfo firstSigner2 = cms.SignerInfos[0]; Assert.Single(firstSigner2.CounterSignerInfos); Assert.Single(firstSigner2.UnsignedAttributes); SignerInfo counterSigner = firstSigner2.CounterSignerInfos[0]; Assert.Equal(identifierType, counterSigner.SignerIdentifier.Type); // On .NET Framework there will be two attributes, because Windows emits the // content-type attribute even for counter-signers. int expectedCount = 1; #if NETFRAMEWORK expectedCount = 2; #endif Assert.Equal(expectedCount, counterSigner.SignedAttributes.Count); Assert.Equal(Oids.MessageDigest, counterSigner.SignedAttributes[expectedCount - 1].Oid.Value); Assert.NotEqual(firstSigner2.Certificate, counterSigner.Certificate); Assert.Equal(2, cms.Certificates.Count); counterSigner.CheckSignature(true); firstSigner2.CheckSignature(true); cms.CheckSignature(true); }
public static SignatureResponse Sign(byte[] data) { // TODO: // padding configuration // algorithm configuration // encoding configuration /* * SHA1Managed sha1 = new SHA1Managed(); * byte[] hash = sha1.ComputeHash(data); * * var sig = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); * //sig = csp.SignData(Encoding.UTF8.GetBytes(text), CryptoConfig.MapNameToOID("SHA1")); * * MessageBox.Show("SignData"); */ var content = new ContentInfo(data); var cms = new SignedCms(content, true); // TODO detached config var signer = new CmsSigner(); signer.IncludeOption = X509IncludeOption.EndCertOnly; cms.ComputeSignature(signer, false); var sig = cms.Encode(); //ensure my signature is correct before continuing. cms.CheckSignature(true); var newCMS = new SignedCms(content, false); newCMS.Decode(sig); newCMS.CheckSignature(true); var cert = cms.Certificates[0]; CheckSig(sig, data); return(new SignatureResponse { publicKey = Convert.ToBase64String(cert.PublicKey.EncodedKeyValue.RawData), signature = Convert.ToBase64String(sig), fullSig = null // TODO }); }
public static void AddFirstSigner_RSA(SubjectIdentifierType identifierType, bool detached) { ContentInfo contentInfo = new ContentInfo(new byte[] { 9, 8, 7, 6, 5 }); SignedCms cms = new SignedCms(contentInfo, detached); using (X509Certificate2 signerCert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey()) { CmsSigner signer = new CmsSigner(identifierType, signerCert); cms.ComputeSignature(signer); } Assert.Same(contentInfo.Content, cms.ContentInfo.Content); Assert.Single(cms.SignerInfos); Assert.Single(cms.Certificates); int expectedVersion = identifierType == SubjectIdentifierType.SubjectKeyIdentifier ? 3 : 1; Assert.Equal(expectedVersion, cms.Version); SignerInfo firstSigner = cms.SignerInfos[0]; Assert.Equal(identifierType, firstSigner.SignerIdentifier.Type); Assert.NotNull(firstSigner.Certificate); Assert.NotSame(cms.Certificates[0], firstSigner.Certificate); Assert.Equal(cms.Certificates[0], firstSigner.Certificate); cms.CheckSignature(true); byte[] encoded = cms.Encode(); cms = new SignedCms(); cms.Decode(encoded); Assert.Single(cms.SignerInfos); Assert.Single(cms.Certificates); Assert.Equal(expectedVersion, cms.Version); Assert.Equal(identifierType, cms.SignerInfos[0].SignerIdentifier.Type); Assert.Equal(firstSigner.Certificate, cms.SignerInfos[0].Certificate); if (detached) { Assert.Throws <CryptographicException>(() => cms.CheckSignature(true)); cms = new SignedCms(contentInfo, detached); cms.Decode(encoded); } cms.CheckSignature(true); }