コード例 #1
0
        public static bool VerifyDetached(byte[] data, byte[] signature)
        {
            var content = new ContentInfo(data);

            var signedMessage = new SignedCms(content, true);

            signedMessage.Decode(signature);

            try
            {
                signedMessage.CheckSignature(false);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
コード例 #2
0
        public static void Decode_IgnoresExtraData()
        {
            byte[] basis = SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber;
            byte[] data = new byte[basis.Length + 60];
            data.AsSpan(basis.Length).Fill(0x5E);
            basis.AsSpan().CopyTo(data);

            SignedCms cms = new SignedCms();
            cms.Decode(data);

            // Assert.NotThrows
            cms.CheckSignature(true);

            byte[] encoded = cms.Encode();

            Assert.Equal(basis.Length, encoded.Length);
            Assert.Equal(basis.ByteArrayToHex(), encoded.ByteArrayToHex());
        }
コード例 #3
0
        public static void SignerInfo_RemoveNonMatchingUnsignedAttributesFromCounterSigner_Throws()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);

            int numberOfAttributes = cms.SignerInfos[0].UnsignedAttributes.Count;

            Assert.NotEqual(0, numberOfAttributes);

            AsnEncodedData fakeAttribute = new AsnEncodedData(
                cms.SignerInfos[0].UnsignedAttributes[0].Oid,
                cms.SignerInfos[0].UnsignedAttributes[0].Values[0].RawData.Skip(1).ToArray());

            Assert.Throws <CryptographicException>(() => cms.SignerInfos[0].CounterSignerInfos[0].RemoveUnsignedAttribute(fakeAttribute));

            Assert.Equal(numberOfAttributes, cms.SignerInfos[0].UnsignedAttributes.Count);
        }
コード例 #4
0
        public static SignerInfo VerifyDetachedCmsSignature(byte[] data, byte[] signature, bool skipCertValidation)
        {
            ContentInfo contentInfo = new ContentInfo(data);
            SignedCms   signedCms   = new SignedCms(contentInfo, true);

            signedCms.Decode(signature);

            try
            {
                signedCms.CheckSignature(skipCertValidation);
            }
            catch (Exception ex)
            {
                throw new InvalidSignatureException(ex);
            }

            return(signedCms.SignerInfos[0]);
        }
コード例 #5
0
        private bool VerifySignature()
        {
            SignedCms signedCms = new SignedCms();

            signedCms.Decode(_peFile.WinCertificate.bCertificate);

            try
            {
                // Throws an exception if the signature is invalid.
                signedCms.CheckSignature(true);
            }
            catch (Exception)
            {
                return(false);
            }

            return(true);
        }
コード例 #6
0
        /// <summary>
        /// Asynchronously reads a <see cref="ProvisioningProfile"/> off a <see cref="Stream"/>.
        /// </summary>
        /// <param name="stream">
        /// A <see cref="Stream"/> which represents the provisioning profile.
        /// </param>
        /// <param name="cancellationToken">
        /// A <see cref="CancellationToken"/> which can be used to cancel the asynchronous operation.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> which represents the asynchronous operation, and returns a <see cref="ProvisioningProfile"/>
        /// when completed.
        /// </returns>
        public static async Task <ProvisioningProfile> ReadAsync(Stream stream, CancellationToken cancellationToken)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            var length = (int)stream.Length;

            byte[] data = new byte[length];
            await stream.ReadBlockAsync(data.AsMemory(0, length), cancellationToken).ConfigureAwait(false);

            SignedCms signedCms = new SignedCms();

            signedCms.Decode(data);

            return(Read(signedCms));
        }
コード例 #7
0
        public static void Decode_OverwritesAttachedContentInfo()
        {
            ContentInfo original = new ContentInfo(new byte [] { 1, 2, 3, 4, 5 });
            SignedCms   cms      = new SignedCms(original, false);

            Assert.False(cms.Detached);

            cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);

            Assert.False(cms.Detached);

            ContentInfo newInfo  = cms.ContentInfo;
            ContentInfo newInfo2 = cms.ContentInfo;

            Assert.NotSame(original, newInfo);
            Assert.Same(newInfo, newInfo2);
            Assert.NotEqual(original.Content, newInfo.Content);
        }
コード例 #8
0
    static void Main(string[] args)
    {
        var data = ...;
        var cms  = new SignedCms();

        cms.Decode(data);
        var pbCmsgSignerInfo = typeof(SignerInfo).GetField("m_pbCmsgSignerInfo", BindingFlags.NonPublic | BindingFlags.Instance);
        var si = (SafeHandle)pbCmsgSignerInfo.GetValue(cms.SignerInfos[0]);
        var safeCryptMessageHandle = typeof(SignedCms).GetField("m_safeCryptMsgHandle", BindingFlags.NonPublic | BindingFlags.Instance);
        var hMsg = (SafeHandle)safeCryptMessageHandle.GetValue(cms);
        var vsi  = new CRYPTUI_VIEWSIGNERINFO_STRUCT {
            dwSize      = (uint)Marshal.SizeOf(typeof(CRYPTUI_VIEWSIGNERINFO_STRUCT)),
            pSignerInfo = si,
            hMsg        = hMsg,
        };

        CryptUIDlgViewSignerInfo(ref vsi);
    }
コード例 #9
0
        private static SignedCms EnsureCertificatesInCertificatesCollection(
            SignedCms timestampCms,
            IReadOnlyList <X509Certificate2> chain)
        {
            using (var timestampNativeCms = NativeCms.Decode(timestampCms.Encode()))
            {
                timestampNativeCms.AddCertificates(
                    chain.Where(certificate => !timestampCms.Certificates.Contains(certificate))
                    .Select(certificate => certificate.RawData));

                var bytes      = timestampNativeCms.Encode();
                var updatedCms = new SignedCms();

                updatedCms.Decode(bytes);

                return(updatedCms);
            }
        }
コード例 #10
0
        public static void AddCertificate()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner);

            int numOfCerts = cms.Certificates.Count;

            using (X509Certificate2 newCert = Certificates.RSAKeyTransfer1.GetCertificate())
            {
                cms.AddCertificate(newCert);

                Assert.Equal(numOfCerts + 1, cms.Certificates.Count);
                Assert.True(cms.Certificates.Contains(newCert));

                cms.CheckSignature(true);
            }
        }
コード例 #11
0
ファイル: SignService.cs プロジェクト: maurbone/DocSuitePA
        //  Verify the encoded SignedCms message and return a Boolean
        //  value that specifies whether the verification was successful.
        static public bool VerifyMsg(byte[] encodedSignedCms)
        {
            //  Prepare an object in which to decode and verify.
            SignedCms signedCms = new SignedCms();

            signedCms.Decode(encodedSignedCms);

            //  Catch a verification exception if you want to
            //  advise the message recipient that
            //  security actions might be appropriate.
            try
            {
                //  Verify signature. Do not validate signer
                //  certificate for the purposes of this example.
                //  Note that in a production environment, validating
                //  the signer certificate chain will probably
                //  be necessary.
#if DEBUG
                System.Diagnostics.Trace.Write("Checking signature on message ... ");
#endif
                signedCms.CheckSignature(true);
#if DEBUG
                System.Diagnostics.Trace.WriteLine("Done.");
#endif
            }
            catch (System.Security.Cryptography.CryptographicException e)
            {
#if DEBUG
                System.Diagnostics.Trace.WriteLine("VerifyMsg caught exception:  {0}",
                                                   e.Message);
                System.Diagnostics.Trace.WriteLine("Verification of the signed PKCS #7 " +
                                                   "failed. The message, signatures, or " +
                                                   "countersignatures may have been modified " +
                                                   "in transit or storage. The message signers or " +
                                                   "countersigners may not be who they claim to be. " +
                                                   "The message's authenticity or integrity, " +
                                                   "or both, are not guaranteed.");
#endif          //LP20071214 x motivi di firma debole con certificato scadut faccio passare il check
                //return false;
                return(true);
            }

            return(true);
        }
コード例 #12
0
        /// <summary>
        /// Common code for both the attached/detached cases. It will verify that the signatures are valid for the data.
        /// </summary>
        /// <param name="signedCms">The signed CMS which we will validate.</param>
        /// <param name="body">The bytes we want to validate against.</param>
        /// <param name="verifySignatureOnly">If we should verify the signature only. Useful for testing only.</param>
        internal static void VerifySignedData(SignedCms signedCms, byte[] body, bool verifySignatureOnly = false)
        {
            try
            {
                signedCms.Decode(body);

                signedCms.CheckSignature(verifySignatureOnly);

                if (signedCms.SignerInfos.Count == 0)
                {
                    throw new SignClientException(Resources.InvalidSigningInfo);
                }

                var issuedCertificate = signedCms.SignerInfos[0].Certificate;

                foreach (var signedInfo in signedCms.SignerInfos)
                {
                    if (TimeStamper.CheckRFC3161Timestamp(signedInfo, issuedCertificate.NotBefore, issuedCertificate.NotAfter) == false)
                    {
                        throw new SignClientException(Resources.InvalidTimestamp);
                    }
                }

                WriteGpgCertificateData(true, signedCms.Certificates);
                WriteSigningInformation(issuedCertificate, true, signedCms);

                GpgOutputHelper.WriteLine($"{FullyTrusted} 0 shell"); // This indicates we fully trust using the x509 model.
            }
            catch (Exception)
            {
                if (signedCms.Certificates.Count == 0)
                {
                    GpgOutputHelper.WriteLine(ErrorSignature);
                }
                else
                {
                    var issuedCertificate = signedCms.SignerInfos[0].Certificate;
                    WriteGpgCertificateData(false, signedCms.Certificates);
                    WriteSigningInformation(issuedCertificate, false, signedCms);
                }

                throw;
            }
        }
コード例 #13
0
        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);
        }
コード例 #14
0
 public static byte[]? ExtractPadding(string filePath)
 {
     using (var file = new PortableExecutable(filePath))
     {
         var dosHeader         = file.GetDosHeader();
         var peHeader          = file.GetPEHeader(dosHeader);
         var signatureLocation = peHeader.DataDirectories[ImageDataDirectoryEntry.IMAGE_DIRECTORY_ENTRY_SECURITY];
         using (var signatureData = file.ReadDataDirectory(signatureLocation))
         {
             using (var reader = new BinaryReader(signatureData))
             {
                 var winCertLength   = reader.ReadUInt32();
                 var winCertRevision = reader.ReadUInt16();
                 var winCertType     = reader.ReadUInt16();
                 if (winCertRevision != 0x200 && winCertRevision != 0x100)
                 {
                     return(null);
                 }
                 if (winCertType != 0x0002)
                 {
                     return(null);
                 }
                 using (var memoryStream = new MemoryStream())
                 {
                     int         read;
                     Span <byte> buffer = stackalloc byte[0x400];
                     while ((read = reader.Read(buffer)) > 0)
                     {
                         memoryStream.Write(buffer.Slice(0, read));
                     }
                     var winCertificate = memoryStream.ToArray();
                     var signer         = new SignedCms();
                     signer.Decode(winCertificate);
                     var roundTrip      = signer.Encode();
                     var sizeDifference = winCertificate.Length - roundTrip.Length;
                     var difference     = new byte[sizeDifference];
                     Buffer.BlockCopy(winCertificate, roundTrip.Length, difference, 0, difference.Length);
                     return(difference);
                 }
             }
         }
     }
 }
コード例 #15
0
        public static void SignerInfo_AddRemoveUnsignedAttributeWithDetachtedSigner_Throws()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners);

            // Detatch signer (and its counter signers)
            SignerInfo counterSigner = cms.SignerInfos[0].CounterSignerInfos[0];

            cms.RemoveSignature(0);

            // we shouldn't throw
            Assert.Equal(0, counterSigner.UnsignedAttributes.Count);

            AsnEncodedData attribute = CreateTimestampToken(1);

            Assert.Throws <CryptographicException>(() => counterSigner.AddUnsignedAttribute(attribute));
            Assert.Throws <CryptographicException>(() => counterSigner.RemoveUnsignedAttribute(attribute));
        }
コード例 #16
0
ファイル: Program.cs プロジェクト: qiankai/ChromeCAC
        static void Main(string[] args)
        {
            var data     = "foobar";
            var response = CAC.Sign(data);

            ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes("foobar"));

            //SignedCms signedCms = new SignedCms(contentInfo, true);
            SignedCms signedCms = new SignedCms(contentInfo, true);

            signedCms.Decode(Convert.FromBase64String(response.signature));

            // This checks if the signature is valid, but doensn't actually verify the cert (TODO)
            signedCms.CheckSignature(true);



            signedCms.CheckSignature(false);
        }
コード例 #17
0
        /// <summary>
        /// Gets signed mime content. Value null means no content.
        /// </summary>
        /// <returns>Returns signed mime content. Value null means no content.</returns>
        /// <remarks>This method is valid only if <b>Content-Type</b> parameter <b>smime-type=signed-data</b>.</remarks>
        /// <exception cref="InvalidOperationException">Is raised when <b>smime-type != signed-data</b>.</exception>
        public MIME_Message GetSignedMime()
        {
            if (!string.Equals(this.Entity.ContentType.Parameters["smime-type"], "signed-data", StringComparison.InvariantCultureIgnoreCase))
            {
                throw new InvalidOperationException("The VerifySignature method is only valid if Content-Type parameter smime-type=signed-data.");
            }

            if (this.Data != null)
            {
                SignedCms signedCms = new SignedCms();
                signedCms.Decode(this.Data);

                return(MIME_Message.ParseFromStream(new MemoryStream(signedCms.ContentInfo.Content)));
            }
            else
            {
                return(null);
            }
        }
コード例 #18
0
        internal static byte[] ExtractEnvelopedData(byte[] signature)
        {
            if (signature == null)
            {
                throw new ArgumentNullException("signature");
            }

            // decode the signature
            SignedCms cms = new SignedCms();

            cms.Decode(signature);

            if (cms.Detached)
            {
                throw new InvalidOperationException("Cannot extract enveloped content from a detached signature.");
            }

            return(cms.ContentInfo.Content);
        }
コード例 #19
0
static void Test_CheckSignature2(byte[] innerContent, byte[] encodedMessage)
{
//<Snippet2>
// Create a ContentInfo object from the inner content obtained 
// independently from encodedMessage.
ContentInfo contentInfo = new ContentInfo(innerContent);

// Create a new, detached SignedCms message.
SignedCms signedCms = new SignedCms(contentInfo, true);

// encodedMessage is the encoded message received from 
// the sender.
signedCms.Decode(encodedMessage);

// Verify the signature without validating the 
// certificate.
signedCms.CheckSignature(true);
//</Snippet2>
}
コード例 #20
0
        internal static SignedCms RequestTimestamp(byte[] data, string hashAlgorithmOid, Uri timestampingAuthorityUrl)
        {
            var para = new CRYPT_TIMESTAMP_PARA()
            {
                fRequestCerts = true
            };

            IntPtr unmanagedContext = IntPtr.Zero;

            byte[] encodedResponse;
            try
            {
                NativeUtils.ThrowIfFailed(NativeMethods.CryptRetrieveTimeStamp(
                                              wszUrl: timestampingAuthorityUrl.ToString(),
                                              dwRetrievalFlags: NativeMethods.TIMESTAMP_VERIFY_CONTEXT_SIGNATURE,
                                              dwTimeout: 5 * 1000 /* 5 second timeout */,
                                              pszHashId: hashAlgorithmOid,
                                              pPara: ref para,
                                              pbData: data,
                                              cbData: (uint)data.Length,
                                              ppTsContext: out unmanagedContext,
                                              ppTsSigner: IntPtr.Zero,
                                              phStore: IntPtr.Zero));

                // Copy the encoded response out
                var context = (CRYPT_TIMESTAMP_CONTEXT)Marshal.PtrToStructure(unmanagedContext, typeof(CRYPT_TIMESTAMP_CONTEXT));
                encodedResponse = new byte[context.cbEncoded];
                Marshal.Copy(context.pbEncoded, encodedResponse, 0, (int)context.cbEncoded);
            }
            finally
            {
                if (unmanagedContext != IntPtr.Zero)
                {
                    NativeMethods.CryptMemFree(unmanagedContext);
                }
            }

            SignedCms cms = new SignedCms();

            cms.Decode(encodedResponse);
            return(cms);
        }
コード例 #21
0
        internal Rfc3161TimestampTokenInfo(IntPtr pTsContext)
        {
            var context = (Rfc3161TimestampWin32.CRYPT_TIMESTAMP_CONTEXT)Marshal.PtrToStructure(pTsContext, typeof(Rfc3161TimestampWin32.CRYPT_TIMESTAMP_CONTEXT));

            byte[] encoded = new byte[context.cbEncoded];
            Marshal.Copy(context.pbEncoded, encoded, 0, context.cbEncoded);

            var cms = new SignedCms();

            cms.Decode(encoded);

            if (!string.Equals(cms.ContentInfo.ContentType.Value, Oids.TSTInfoContentType, StringComparison.Ordinal))
            {
                throw new CryptographicException(Strings.InvalidAsn1);
            }

            RawData = cms.ContentInfo.Content;

            _decoded = TstInfo.Read(RawData);
        }
コード例 #22
0
 private static void ValidateAttestedData(AttestedDocument document)
 {
     try
     {
         byte[]    blob      = Convert.FromBase64String(document.Signature);
         SignedCms signedCms = new SignedCms();
         signedCms.Decode(blob);
         string result = Encoding.UTF8.GetString(signedCms.ContentInfo.Content);
         Console.WriteLine("Attested data: {0}", result);
         AttestedData data = SerializeObjectFromJsonString(typeof(AttestedData), result) as AttestedData;
         if (data.Nonce.Equals(NonceValue))
         {
             Console.WriteLine("Nonce values match");
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("Error checking signature blob: '{0}'", ex);
     }
 }
コード例 #23
0
        private (DateTimeOffset?, SignerInfo) GetTimestamp()
        {
            var authorUnsignedAttributes = signature.SignerInfo.UnsignedAttributes;
            var timestampCms             = new SignedCms();

            foreach (var attribute in authorUnsignedAttributes)
            {
                if (string.Equals(attribute.Oid.Value, Oids.SignatureTimeStampTokenAttributeOid))
                {
                    timestampCms.Decode(attribute.Values[0].RawData);

                    if (Rfc3161TimestampVerificationUtility.TryReadTSTInfoFromSignedCms(timestampCms, out var tstInfo))
                    {
                        return(tstInfo.Timestamp, timestampCms.SignerInfos[0]);
                    }
                }
            }

            return(null, null);
        }
コード例 #24
0
        public static void CreateSignature_RsaPss(string digestOid, bool assignByConstructor)
        {
            ContentInfo content = new ContentInfo(new byte[] { 1, 2, 3 });
            SignedCms   cms     = new SignedCms(content);

            byte[] cmsBytes;

            using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
            {
                CmsSigner signer;

                if (assignByConstructor)
                {
                    signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert, null, RSASignaturePadding.Pss);
                }
                else
                {
                    signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert);
                    signer.SignaturePadding = RSASignaturePadding.Pss;
                }

                signer.DigestAlgorithm = new Oid(digestOid, null);
                if (!SignatureSupport.SupportsRsaSha1Signatures &&
                    digestOid == Oids.Sha1)
                {
                    Assert.ThrowsAny <CryptographicException>(() => cms.ComputeSignature(signer));
                }
                else
                {
                    cms.ComputeSignature(signer);
                    cmsBytes = cms.Encode();
                    cms      = new SignedCms();
                    cms.Decode(cmsBytes);
                    cms.CheckSignature(true); // Assert.NoThrow
                    Assert.Single(cms.SignerInfos);

                    SignerInfo signerInfo = cms.SignerInfos[0];
                    Assert.Equal(Oids.RsaPss, signerInfo.SignatureAlgorithm.Value);
                }
            }
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: 0xBADCA7/roca
        static void TestPDF(string path)
        {
            Console.WriteLine("processing PDF");
            AcroFields    acroFields = new PdfReader(path).AcroFields;
            List <string> names      = acroFields.GetSignatureNames();

            foreach (var name in names)
            {
                try {
                    Console.WriteLine(name);
                    PdfDictionary dict = acroFields.GetSignatureDictionary(name);

                    PdfString contents = (PdfString)PdfReader.GetPdfObject(dict.Get(PdfName.CONTENTS));


                    byte[] PKCS7      = contents.GetOriginalBytes();
                    var    signedData = new SignedCms();
                    signedData.Decode(PKCS7);
                    Console.WriteLine(signedData.Certificates.Count);
                    int i = 0;
                    foreach (var certificate in signedData.Certificates)
                    {
                        i++;

                        X509CertificateParser x509CertificateParser = new X509CertificateParser();
                        X509Certificate       x509Certificate       = x509CertificateParser.ReadCertificate(certificate.GetRawCertData());
                        RsaKeyParameters      rsaKeyParameters      = x509Certificate.GetPublicKey() as RsaKeyParameters;
                        if (RocaTest.IsVulnerable(rsaKeyParameters))
                        {
                            Console.WriteLine("Cetificate #" + i + " is vulnerable. Cert Hash: " + certificate.GetCertHashString());
                        }
                        else
                        {
                            Console.WriteLine("Cetificate #" + i + " is NOT vulnerable");
                        }
                    }
                } catch (Exception exc) {
                    Console.WriteLine(exc.Message);
                }
            }
        }
コード例 #26
0
        public static void SignerInfo_AddUnsignedAttribute_Adds()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);

            Assert.Equal(0, cms.SignerInfos[0].UnsignedAttributes.Count);

            AsnEncodedData attribute1 = CreateTimestampToken(1);

            cms.SignerInfos[0].AddUnsignedAttribute(attribute1);

            Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count);
            Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count);
            VerifyAttributesAreEqual(cms.SignerInfos[0].UnsignedAttributes[0].Values[0], attribute1);

            ReReadSignedCms(ref cms);

            Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count);
            Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count);
            VerifyAttributesAreEqual(cms.SignerInfos[0].UnsignedAttributes[0].Values[0], attribute1);

            AsnEncodedData attribute2 = CreateTimestampToken(2);

            cms.SignerInfos[0].AddUnsignedAttribute(attribute2);

            var expectedAttributes = new List <AsnEncodedData>();

            expectedAttributes.Add(attribute1);
            expectedAttributes.Add(attribute2);

            Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count);
            Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count);
            VerifyAttributesContainsAll(cms.SignerInfos[0].UnsignedAttributes, expectedAttributes);

            ReReadSignedCms(ref cms);

            Assert.Equal(1, cms.SignerInfos[0].UnsignedAttributes.Count);
            Assert.Equal(2, cms.SignerInfos[0].UnsignedAttributes[0].Values.Count);
            VerifyAttributesContainsAll(cms.SignerInfos[0].UnsignedAttributes, expectedAttributes);
        }
コード例 #27
0
        /// <summary>
        /// Проверить сообщение, подписанное ЭП в формате PKCS#7.
        /// </summary>
        /// <param name="data">Оригинал сообщения.</param>
        /// <param name="encodedSignature">Подписанное сообщение/отделенная подпись в формате PKCS#7.</param>
        /// <param name="isDetached">Отсоединенная ли подпись.</param>
        /// <returns>Валидна ли подпись сообщения, т.е. не изменял ли его кто и правда ли оно принадлежит тому, кто говорит, что подписал его.</returns>
        public bool Verify(Byte[] data, byte[] encodedSignature, bool isDetached = false)
        {
            Argument.Require(data != null, "Оригинал сообщения пустой.");
            Argument.Require(encodedSignature != null, "Подписанное сообщение/отделенная подпись в формате PKCS#7 пустой.");

            ContentInfo contentInfo = new ContentInfo(data);
            SignedCms   signedCms   = new SignedCms(contentInfo, isDetached);

            signedCms.Decode(encodedSignature);

            try
            {
                signedCms.CheckSignature(true);
            }
            catch (System.Security.Cryptography.CryptographicException e)
            {
                return(false);
            }

            return(true);
        }
コード例 #28
0
        private static SignedCms ModifyUnsignedAttributes(SignedCms signedCms, Func <AttributeTable, AttributeTable> modify)
        {
            byte[] bytes = signedCms.Encode();

            var bcSignedCms = new CmsSignedData(bytes);
            SignerInformationStore signerInfos = bcSignedCms.GetSignerInfos();
            SignerInformation      signerInfo  = GetFirstSignerInfo(signerInfos);

            AttributeTable updatedAttributes = modify(signerInfo.UnsignedAttributes);

            SignerInformation updatedSignerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, updatedAttributes);
            var updatedSignerInfos = new SignerInformationStore(updatedSignerInfo);

            CmsSignedData updatedBcSignedCms = CmsSignedData.ReplaceSigners(bcSignedCms, updatedSignerInfos);

            var updatedSignedCms = new SignedCms();

            updatedSignedCms.Decode(updatedBcSignedCms.GetEncoded());

            return(updatedSignedCms);
        }
コード例 #29
0
        internal static ICms Create(byte[] cmsBytes)
        {
            if (cmsBytes == null)
            {
                throw new ArgumentNullException(nameof(cmsBytes));
            }
#if IS_SIGNING_SUPPORTED
            ICms cms = null;
#if IS_DESKTOP
            NativeCms nativeCms = NativeCms.Decode(cmsBytes);
            cms = new NativeCmsWrapper(nativeCms);
#else
            SignedCms signedCms = new SignedCms();
            signedCms.Decode(cmsBytes);
            cms = new ManagedCmsWrapper(signedCms);
#endif
            return(cms);
#else
            throw new NotSupportedException();
#endif
        }
コード例 #30
0
        public static byte[] FirmaFileBouncy(byte[] data, X509Certificate2 cert)
        {
            try
            {
                SHA256Managed        hashSha256 = new SHA256Managed();
                byte[]               certHash   = hashSha256.ComputeHash(cert.RawData);
                EssCertIDv2          essCert1   = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash);
                SigningCertificateV2 scv2       = new SigningCertificateV2(new EssCertIDv2[] { essCert1 });
                Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2));
                Asn1EncodableVector v = new Asn1EncodableVector();
                v.Add(CertHAttribute);
                Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v);

                CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp();

                var rsa = (RSACryptoServiceProvider)cert.PrivateKey;
                Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert);
                cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null);
                ArrayList certList = new ArrayList();
                certList.Add(certCopy);
                Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList);
                Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP);
                cms.AddCertificates(st1);
                //mi ricavo il file da firmare
                CmsSignedData Firmato = cms.Generate(new CmsProcessableByteArray(data), false);

                CmsSigner cmsSigner = new CmsSigner(cert);
                cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly;

                System.Security.Cryptography.Pkcs.ContentInfo contentInfo = new System.Security.Cryptography.Pkcs.ContentInfo(Firmato.GetEncoded());
                SignedCms signedCms = new SignedCms();
                signedCms.Decode(Firmato.GetEncoded());
                byte[] ret = signedCms.Encode();
                return(ret);
            }
            catch
            {
                return(null);
            }
        }
コード例 #31
0
ファイル: Form1.cs プロジェクト: scholtz/FastZep
        private void loadPolicy()
        {
            try
            {
                var client = new WebClient();
                byte[] data = null;

                try
                {
                    string trustedlistdata = FZRegistry.get("trustedlist.p7m");
                    if (trustedlistdata == null) throw new Exception("Dont have trusted list");
                    string[] trustedlistdataarr = trustedlistdata.Split(';');
                    data = Convert.FromBase64String(trustedlistdataarr[1]);
                    if (long.Parse(trustedlistdataarr[0]) < DateTime.Now.Ticks - (long) 24*3600*10000000) {
                        throw new Exception("Trusted list is too old");
                    }
                }
                catch{
                    byte[] data2 = client.DownloadData("http://www.nbusr.sk/ipublisher/files/nbusr.sk/sign_policy/trustedlist.p7m");
                    if (data2 != null)
                    {
                        try
                        {

                            data = data2;
                            FZRegistry.set("trustedlist.p7m", DateTime.Now.Ticks.ToString() + ";" + Convert.ToBase64String(data2));
                        }
                        catch(Exception exc){
                            MessageBox.Show("Chyba v stiahnutom súbore trustedlist.p7m: "+exc.Message);
                        }
                    }
                }
                SignedCms signedCms = new SignedCms();
                signedCms.Decode(data);

                var stream = new StreamReader(new MemoryStream(signedCms.ContentInfo.Content),System.Text.Encoding.UTF8);
                string line = null;
                byte[] file = null;
                string notafter = "";
                string oid = "";
                string FieldOfApplication = "";
                ASNNode der = null;
                string web = "";
                while ((line = stream.ReadLine()) != null)
                {
                    if (line.Substring(0, 5) == "FILE=") {

                        try
                        {
                            web = line.Substring(5);

                        }
                        catch (Exception exc) {
                            MessageBox.Show(exc.Message);
                        }
                    }
                    if (line.Substring(0, 7) == "NOTICE=") {
                        foreach (string data1 in line.Substring(7).Split(',')) {
                            string data2 = data1;
                            data2 = data2.Trim();
                            if (data2.Substring(data2.Length - 8) == "NotAfter")
                            {
                                notafter = data2.Substring(0, data2.Length - 8).Trim();
                            }
                            if (data2.Substring(0, 4) == "OID=")
                            {
                                oid = data2.Substring(4).Trim();
                            }
                            if (data2.Substring(0, 19) == "FieldOfApplication=")
                            {
                                FieldOfApplication = data2.Substring(19).Trim();
                            }

                        }

                        // spracuj zaznam

                        try
                        {
                            if (web == "") throw new Exception("Failed to parse trustedlist.p7m file");
                            string name = web.Substring(web.LastIndexOf('/') + 1);
                            string created = name.Substring(0, 8);
                            var crdate = DateTime.ParseExact(created, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
                            var todate = DateTime.ParseExact(notafter.Substring(0, 8), "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
                            if (crdate > DateTime.Now) continue;
                            if (todate < DateTime.Now) continue;

                            if (oid == "") {
                                oid = name.Substring(0, name.Length - 4);
                            }
                            if (oid == "") throw new Exception("Failed to parse trustedlist.p7m file. Missing oid.");
                            if (web.Substring(web.Length - ".der".Length) != ".der") continue;

                            if (!FZRegistry.isSet(oid + ".short.der"))
                            {
                                file = client.DownloadData(web);
                                //File.WriteAllBytes("d:/policy/" + name, file);
                                FZRegistry.set(oid+".der", Convert.ToBase64String(file));
                                //byte[] policy = createShortPolicy(file, false);
                                //FZRegistry.set(oid + ".short.der", Convert.ToBase64String(policy));
                                //File.WriteAllBytes("d:/policy/" + name + ".short.asn", policy);
                            }
                            else
                            {
                                //file = File.ReadAllBytes("d:/policy/" + name);
                                //byte[] policy = createShortPolicy(file, false);
                                //File.WriteAllBytes("d:/policy/" + name + ".short.asn", policy);
                            }
                            dataGridViewPolitiky.Rows.Add(new object[] { oid, FieldOfApplication, crdate.ToString("dd.mm.yyyy"), todate.ToString("dd.mm.yyyy") });

                            web = "";
                            oid = "";
                            FieldOfApplication = "";
                            notafter = "";

                        }
                        catch (Exception exc) {
                            MessageBox.Show(exc.Message);
                        }
                    }
                }
                    //File.WriteAllBytes("d:/test.txt", signedCms.ContentInfo.Content);
                //File.ReadAllLines()

            }
            catch (Exception exc) {
                MessageBox.Show("Chyba pri čítaní politiky: " + exc.Message);
            }

            //dataGridViewPolitiky.Rows.Add(new object[] { "policy1", "Zaručený elektronický podpis v súlade s legislatívou Slovenskej republiky.", "1.2.2010", "31.12.2010" });
            //dataGridViewPolitiky.Rows.Add(new object[] { "policy2", "Podpisová politika pre dokumenty podpísané ZEP v orgánoch štátnej správy.", "23.8.2010", "31.1.2014" });

            try
            {

                string sel = FZRegistry.get("savedPolicy");
                foreach(DataGridViewRow row in dataGridViewPolitiky.Rows){
                    if (row.Cells["id"].Value.ToString() == sel) row.Selected = true;
                }
            }
            catch { }
        }
コード例 #32
0
ファイル: Form1.cs プロジェクト: scholtz/FastZep
        private bool signFile(string file, string outFile, string algoritmus, bool detached)
        {
            try
            {
                string saveTo = Path.GetDirectoryName(file);
                string tmpDir = FastZep.FastZepFolder + "tmp";
                if (lbValue == "") {
                    return false;
                }
                if (Directory.Exists(tmpDir))
                {
                    Directory.Delete(tmpDir, true);
                }
                Directory.CreateDirectory(tmpDir);

                string date = DateTime.Now.Subtract(TimeSpan.FromHours(1)).ToString("yyyyMMddHHmmss") + "Z";

                Directory.CreateDirectory(tmpDir + "\\D" + date + "\\Policy\\");
                string certFile = tmpDir + "\\D" + date + "\\Policy\\P" + date + ".der";
                string sigFile = tmpDir + "\\D" + date + "\\S" + date + ".p7s";

                string emlFile = tmpDir + "\\D" + date + "\\M" + date + ".eml";
                Directory.CreateDirectory(tmpDir + "\\D" + date + "\\");
                TextWriter eml = new StreamWriter(emlFile);
                eml.WriteLine("MIME-Version: 1.0");
                eml.WriteLine("Content-Type: " + MimeType(file));
                eml.WriteLine("Content-Transfer-Encoding: base64");
                eml.WriteLine("Content-Disposition: filename=\"" + Path.GetFileName(file) + "\"");
                eml.WriteLine();
                FileStream fs = new FileStream(file, FileMode.Open);
                byte[] filebytes = new byte[fs.Length];
                fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
                string encodedData = Convert.ToBase64String(filebytes, Base64FormattingOptions.InsertLineBreaks);
                eml.Write(encodedData);
                eml.Close();
                fs.Close();

                byte[] buffer = File.ReadAllBytes(emlFile);
                ContentInfo contentInfo = new ContentInfo(buffer);
                X509Store store = new X509Store();
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySerialNumber, lbValue, false);
                int i = 0;
                foreach (X509Certificate2 cert in certs)
                {
                    i++;
                    SignedCms signedCms = new SignedCms(SubjectIdentifierType.IssuerAndSerialNumber, contentInfo, !detached);
                    CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert);

                    cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime());
                    cmsSigner.IncludeOption = X509IncludeOption.WholeChain;

                    ESSCertIDv2 cer2 = new ESSCertIDv2(cert);
                    X509Chain chain = new X509Chain();
                    chain.Build(cert);

                    /*

                    /**/

                    //cmsSigner.UnsignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.21", CertRefs.get(chain)));
                    //cmsSigner.UnsignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.22", CertCrls.get(chain)));
                    //cmsSigner.UnsignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.23", OtherCerts.get(chain)));
                    //cmsSigner.UnsignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.24", OtherCrls.get(chain)));
                    /**/
                    //cmsSigner.SignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.47", cer2.get()));
                    //cmsSigner.SignedAttributes.Add(new AsnEncodedData("1.2.840.113549.1.9.16.2.15", getPolicy(false)));

                    /**/
                    signedCms.ComputeSignature(cmsSigner, false);
                    File.WriteAllBytes(certFile, getPolicy(true));
                    File.WriteAllBytes(sigFile, signedCms.Encode());
                }
                if (i == 0)
                {
                    throw new Exception("Failed" + Marshal.GetLastWin32Error().ToString());
                }
                SignedCms signedCms2 = new SignedCms();

                byte[] encodedMessage = File.ReadAllBytes(sigFile);
                signedCms2.Decode(encodedMessage);

                BHI.Rats.RatsCompressionManager.Zip(tmpDir, outFile);
                Directory.Delete(tmpDir, true);
                return true;
            }
            catch (CryptographicException e)
            {
                var error = e.Message.ToString();
                if (error == "Unknown error \"-1073741275\".") {
                    error = "Nepodarilo sa načítať certifikát. odpojte a pripojte čítačku.";
                }
                if (error == "An internal error occurred.\r\n") {
                    error = "Došlo ku chybe pri podpisovaní. Pravdepodobne nemáte pripojený USB kľúč alebo čítačku kariet.";
                }
                Console.WriteLine("Signing failed: " + error.ToString());
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner Exception: " + e.InnerException.ToString());
                }
                MessageBox.Show(error, "Chyba pri podpisovaní", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }catch (Exception exc)
            {
                MessageBox.Show(exc.Message + "\n" + Marshal.GetLastWin32Error().ToString(), "Chyba pri podpisovaní", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return false;
        }