/// <summary>
        /// Sign the content using the specified signer.
        /// </summary>
        /// <remarks>
        /// Sign the content using the specified signer.
        /// </remarks>
        /// <returns>A new <see cref="MimeKit.MimePart"/> instance
        /// containing the detached signature data.</returns>
        /// <param name="signer">The signer.</param>
        /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
        /// <param name="content">The content.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="signer"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="content"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="digestAlgo"/> is out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
        /// </exception>
        /// <exception cref="CertificateNotFoundException">
        /// A signing certificate could not be found for <paramref name="signer"/>.
        /// </exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        public override MimePart Sign(MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
        {
            if (signer == null)
            {
                throw new ArgumentNullException("signer");
            }

            if (content == null)
            {
                throw new ArgumentNullException("content");
            }

            var contentInfo = new ContentInfo(ReadAllBytes(content));
            var cmsSigner   = GetRealCmsSigner(signer, digestAlgo);
            var signed      = new SignedCms(contentInfo, true);

            signed.ComputeSignature(cmsSigner);
            var signedData = signed.Encode();

            return(new ApplicationPkcs7Signature(new MemoryStream(signedData, false)));
        }
        private static byte[] GenerateSignatureBlock(SignerConfig signerConfig, byte[] signatureFileBytes)
        {
            var signerCert      = signerConfig.Certificate;
            var digestAlgorithm = signerConfig.SignatureDigestAlgorithm;

            var digestAlgorithmId = digestAlgorithm.Oid;

            var content   = new ContentInfo(DataOid, signatureFileBytes);
            var signedCms = new SignedCms(content, true);

            var signer = new CmsSigner(signerCert)
            {
                DigestAlgorithm = digestAlgorithmId
            };

            signedCms.ComputeSignature(signer);

            var encoded = signedCms.Encode();

            return(encoded);
        }
        public static void BuildFromSignerInfo()
        {
            ContentInfo content = new ContentInfo(new byte[] { 1, 2, 3, 4 });
            SignedCms   cms     = new SignedCms(content, false);

            using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
            {
                CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, signerCert);
                signer.SignedAttributes.Add(new Pkcs9SigningTime());
                cms.ComputeSignature(signer);
            }

            SignerInfo signerInfo = cms.SignerInfos[0];

            byte[] sig = signerInfo.GetSignature();

            Rfc3161TimestampRequest fromSigner = Rfc3161TimestampRequest.CreateFromSignerInfo(signerInfo, HashAlgorithmName.SHA256);
            Rfc3161TimestampRequest fromData   = Rfc3161TimestampRequest.CreateFromData(sig, HashAlgorithmName.SHA256);

            Assert.Equal(fromData.Encode().ByteArrayToHex(), fromSigner.Encode().ByteArrayToHex());
        }
Beispiel #4
0
        public byte[] GetSignedCms(Stream stream)
        {
            var range = new byte[stream.Length];

            stream.Position = 0;
            stream.Read(range, 0, range.Length);



            var contentInfo = new ContentInfo(range);

            SignedCms signedCms = new SignedCms(contentInfo, true);
            CmsSigner signer    = new CmsSigner(Certificate);

            signer.UnsignedAttributes.Add(new Pkcs9SigningTime());

            signedCms.ComputeSignature(signer, true);
            var bytes = signedCms.Encode();

            return(bytes);
        }
        /// <summary>
        /// Sign and encapsulate the content using the specified signer.
        /// </summary>
        /// <remarks>
        /// Sign and encapsulate the content using the specified signer.
        /// </remarks>
        /// <returns>A new <see cref="MimeKit.Cryptography.ApplicationPkcs7Mime"/> instance
        /// containing the detached signature data.</returns>
        /// <param name="signer">The signer.</param>
        /// <param name="digestAlgo">The digest algorithm to use for signing.</param>
        /// <param name="content">The content.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="signer"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="content"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// <paramref name="digestAlgo"/> is out of range.
        /// </exception>
        /// <exception cref="System.NotSupportedException">
        /// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
        /// </exception>
        /// <exception cref="CertificateNotFoundException">
        /// A signing certificate could not be found for <paramref name="signer"/>.
        /// </exception>
        /// <exception cref="System.Security.Cryptography.CryptographicException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        public override ApplicationPkcs7Mime EncapsulatedSign(MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
        {
            if (signer == null)
            {
                throw new ArgumentNullException(nameof(signer));
            }

            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            var contentInfo = new ContentInfo(ReadAllBytes(content));
            var cmsSigner   = GetRealCmsSigner(signer, digestAlgo);
            var signed      = new SignedCms(contentInfo, false);

            signed.ComputeSignature(cmsSigner);
            var signedData = signed.Encode();

            return(new ApplicationPkcs7Mime(SecureMimeType.SignedData, new MemoryStream(signedData, false)));
        }
Beispiel #6
0
        private static PrimarySignature CreatePrimarySignature(CmsSigner cmsSigner, SignPackageRequest request, byte[] signingData)
        {
            var contentInfo = new ContentInfo(signingData);
            var cms         = new SignedCms(contentInfo);

            try
            {
                cms.ComputeSignature(cmsSigner);
            }
            catch (CryptographicException ex) when(ex.HResult == INVALID_PROVIDER_TYPE_HRESULT)
            {
                var exceptionBuilder = new StringBuilder();

                exceptionBuilder.AppendLine(Strings.SignFailureCertificateInvalidProviderType);
                exceptionBuilder.AppendLine(CertificateUtility.X509Certificate2ToString(request.Certificate, Common.HashAlgorithmName.SHA256));

                throw new SignatureException(NuGetLogCode.NU3001, exceptionBuilder.ToString());
            }

            return(PrimarySignature.Load(cms));
        }
Beispiel #7
0
        public void ComputeSignatureCmsSignerSubjectKeyIdentifier()
        {
            ContentInfo ci = new ContentInfo(asnNull);
            SignedCms   sp = new SignedCms(ci);

            CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, GetCertificate(true));

            signer.Certificates.Add(new X509Certificate2(intca_cer));
            signer.Certificates.Add(new X509Certificate2(root_cer));
            sp.ComputeSignature(signer);

            byte[] encoded = sp.Encode();
            string s       = BitConverter.ToString(encoded);

#if DEBUG
            FileStream fs = File.OpenWrite("ComputeSignaturePkcs7SignerSubjectKeyIdentifier.der");
            fs.Write(encoded, 0, encoded.Length);
            fs.Close();
#endif
            RoundTrip(encoded);
        }
Beispiel #8
0
    static void Example4()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var document = PdfDocument.Load("Reading.pdf"))
        {
            // Add an invisible signature field to the PDF document.
            var signatureField = document.Form.Fields.AddSignature();

            // Initiate signing of a PDF file with the specified signer delegate.
            signatureField.Sign(pdfFileStream =>
            {
                // Create a signed CMS object using the content that should be signed,
                // but not included in the signed CMS object (detached: true).
                var content = new byte[pdfFileStream.Length];
                pdfFileStream.Read(content, 0, content.Length);
                var signedCms = new SignedCms(new ContentInfo(content), detached: true);

                X509Certificate2 certificate = null;
                try
                {
                    // Compute the signature using the specified digital ID file and the password.
                    certificate = new X509Certificate2("GemBoxExampleExplorer.pfx", "GemBoxPassword");
                    signedCms.ComputeSignature(new CmsSigner(certificate));
                }
                finally
                {
                    // Starting with the .NET Framework 4.6, this type implements the IDisposable interface.
                    (certificate as IDisposable)?.Dispose();
                }

                // Return the signature encoded into a CMS/PKCS #7 message.
                return(signedCms.Encode());
            }, PdfSignatureFormat.PKCS7, 2199);

            // Finish signing of a PDF file.
            document.Save("External Digital Signature.pdf");
        }
    }
Beispiel #9
0
        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);
        }
Beispiel #10
0
        public byte[] GetSignature(byte[] content)
        {
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }

            var certificate = _CertificateProvider.GetCertificate();

            if (!certificate.HasPrivateKey)
            {
                throw new InvalidOperationException($"Certificate does not have a private key - Subject:{certificate.Subject} Thumbprint:{certificate.Thumbprint}.");
            }

            var contentInfo = new ContentInfo(content);
            var signedCms   = new SignedCms(contentInfo, true);

            var signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate)
            {
                IncludeOption = X509IncludeOption.EndCertOnly
            };

            try
            {
                signedCms.ComputeSignature(signer);
            }
            catch (Exception e)
            {
                //NB. Cannot catch the internal exception type (cross-platform design of .NET Core)
                if (e.GetType().Name == "WindowsCryptographicException" && e.Message == "Keyset does not exist" && !WindowsIdentityQueries.CurrentUserIsAdministrator())
                {
                    throw new InvalidOperationException("Failed to sign with certificate when current user does not have UAC elevated permissions.", e);
                }

                throw;
            }

            return(signedCms.Encode());
        }
Beispiel #11
0
        private static byte[] CreateSignedDataPkcs7(byte[] encryptedMessageData, X509Certificate2 localPrivateKey)
        {
            // Create the outer envelope, signed with the local private key
            var signer = new CmsSigner(localPrivateKey)
            {
                DigestAlgorithm = Oids.Pkcs.MD5
            };

            // Message Type (messageType): https://tools.ietf.org/html/draft-nourse-scep-23#section-3.1.1.2
            // PKCS#10 request = PKCSReq (19)
            var messageType = new AsnEncodedData(Oids.Scep.MessageType, DerEncoding.EncodePrintableString("19"));

            signer.SignedAttributes.Add(messageType);

            // Tranaction ID (transId): https://tools.ietf.org/html/draft-nourse-scep-23#section-3.1.1.1
            var sha             = new SHA512Managed();
            var hashedKey       = sha.ComputeHash(localPrivateKey.GetPublicKey());
            var hashedKeyString = Convert.ToBase64String(hashedKey);
            var transactionId   = new Pkcs9AttributeObject(Oids.Scep.TransactionId, DerEncoding.EncodePrintableString(hashedKeyString));

            signer.SignedAttributes.Add(transactionId);

            // Sender Nonce (senderNonce): https://tools.ietf.org/html/draft-nourse-scep-23#section-3.1.1.5
            lastSenderNonce = new byte[16];
            RNGCryptoServiceProvider.Create().GetBytes(lastSenderNonce);
            var nonce = new Pkcs9AttributeObject(Oids.Scep.SenderNonce, DerEncoding.EncodeOctet(lastSenderNonce));

            signer.SignedAttributes.Add(nonce);

            // Seems that the oid is not needed for this envelope
            var signedContent = new ContentInfo(encryptedMessageData); //new Oid("1.2.840.113549.1.7.1", "data"), encryptedMessageData);
            var signedMessage = new SignedCms(signedContent);

            signedMessage.ComputeSignature(signer);

            var encodedMessage = signedMessage.Encode();

            return(encodedMessage);
        }
        /// <summary>
        /// Creates <see cref="SignedCms"/> for raw content and a collection of signing certificate
        /// </summary>
        /// <param name="content">The <c>byte</c> array to sign</param>
        /// <param name="signingCertificates">The certificates with which to sign.</param>
        /// <returns>An instance of <see cref="SignedCms"/> holdling the signatures</returns>
        public SignedCms CreateSignature(byte[] content, X509Certificate2Collection signingCertificates)
        {
            if (content == null)
            {
                throw new SignatureException(SignatureError.NullContent);
            }

            if (signingCertificates == null)
            {
                throw new SignatureException(SignatureError.NoCertificates);
            }

            SignedCms signature = new SignedCms(CreateDataContainer(content), true); // true: Detached Signature

            for (int i = 0, count = signingCertificates.Count; i < count; ++i)
            {
                CmsSigner signer = CreateSigner(signingCertificates[i]);
                signature.ComputeSignature(signer, true);  // true: don't prompt the user
            }

            return(signature);
        }
Beispiel #13
0
        /// <summary>
        /// Crea la firma CMS/PKCS #7
        /// </summary>
        private static byte[] SignMsg(byte[] Message, SysX509.X509Certificate2 SignerCertificate, bool Detached)
        {
            //Creamos el contenedor
            ContentInfo contentInfo = new ContentInfo(Message);

            //Instanciamos el objeto SignedCms con el contenedor
            SignedCms objSignedCms = new SignedCms(contentInfo, Detached);

            //Creamos el "firmante"
            CmsSigner objCmsSigner = new CmsSigner(SignerCertificate);

            // Include the following line if the top certificate in the
            // smartcard is not in the trusted list.
            objCmsSigner.IncludeOption = SysX509.X509IncludeOption.EndCertOnly;

            //  Sign the CMS/PKCS #7 message. The second argument is
            //  needed to ask for the pin.
            objSignedCms.ComputeSignature(objCmsSigner, false);

            //Encodeamos el mensaje CMS/PKCS #7
            return(objSignedCms.Encode());
        }
        public static byte[] SignFile(X509Certificate2 cert, byte[] data)
        {
            try
            {
                ContentInfo content   = new ContentInfo(data);
                SignedCms   signedCms = new SignedCms(content, false);
                if (VerifySign(data))
                {
                    signedCms.Decode(data);
                }

                CmsSigner signer = new CmsSigner(cert);
                signer.IncludeOption = X509IncludeOption.WholeChain;
                signedCms.ComputeSignature(signer);

                return(signedCms.Encode());
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao assinar arquivo. A mensagem retornada foi: " + ex.Message);
            }
        }
        // This generates a package with a basic signed CMS.
        // The signature MUST NOT have any signed or unsigned attributes.
        public static async Task <FileInfo> SignPackageFileWithBasicSignedCmsAsync(
            TestDirectory directory,
            FileInfo packageFile,
            X509Certificate2 certificate)
        {
            SignatureContent signatureContent;

            using (var stream = packageFile.OpenRead())
                using (var hashAlgorithm = HashAlgorithmName.SHA256.GetHashProvider())
                {
                    var hash = hashAlgorithm.ComputeHash(stream, leaveStreamOpen: false);
                    signatureContent = new SignatureContent(SigningSpecifications.V1, HashAlgorithmName.SHA256, Convert.ToBase64String(hash));
                }

            var signedPackageFile = new FileInfo(Path.Combine(directory, Guid.NewGuid().ToString()));
            var cmsSigner         = new CmsSigner(certificate)
            {
                DigestAlgorithm = HashAlgorithmName.SHA256.ConvertToOid(),
                IncludeOption   = X509IncludeOption.WholeChain
            };

            var contentInfo = new ContentInfo(signatureContent.GetBytes());
            var signature   = new SignedCms(contentInfo);

            signature.ComputeSignature(cmsSigner);

            Assert.Empty(signature.SignerInfos[0].SignedAttributes);
            Assert.Empty(signature.SignerInfos[0].UnsignedAttributes);

            using (var packageReadStream = packageFile.OpenRead())
                using (var packageWriteStream = signedPackageFile.OpenWrite())
                    using (var package = new SignedPackageArchive(packageReadStream, packageWriteStream))
                        using (var signatureStream = new MemoryStream(signature.Encode()))
                        {
                            await package.AddSignatureAsync(signatureStream, CancellationToken.None);
                        }

            return(signedPackageFile);
        }
Beispiel #16
0
        public static void SignWithImplicitSubjectKeyIdentifier()
        {
            byte[]      contentBytes = { 9, 8, 7, 6, 5 };
            ContentInfo contentInfo  = new ContentInfo(contentBytes);
            SignedCms   cms          = new SignedCms(contentInfo, false);

            using (X509Certificate2 signerCert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
            {
                // This cert has no Subject Key Identifier extension.
                Assert.Null(signerCert.Extensions[Oids.SubjectKeyIdentifier]);

                CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, signerCert);
                cms.ComputeSignature(signer);
            }

            Assert.Equal(
                "6B4A6B92FDED07EE0119F3674A96D1A70D2A588D",
                (string)cms.SignerInfos[0].SignerIdentifier.Value);

            // Assert.NoThrow
            cms.CheckSignature(true);
        }
Beispiel #17
0
        /// <summary>
        /// Encodes the specified ar message. THIS IS FOR THE TEST CHANNEL
        /// </summary>
        /// <param name="arMessage">The ar message.</param>
        /// <param name="signerCert">The signer cert.</param>
        /// <param name="signerPassword">The signer password.</param>
        /// <returns></returns>
        internal static byte[] EncodeMDN(byte[] arMessage, string signerCert, string signerPassword)
        {
            byte[] signature = null;
            try
            {
                X509Certificate2 cert = new X509Certificate2(signerCert, signerPassword);

                ContentInfo contentInfo = new ContentInfo(arMessage);

                SignedCms signedCms = new SignedCms(contentInfo, true);
                CmsSigner cmsSigner = new CmsSigner(cert);

                signedCms.ComputeSignature(cmsSigner);
                signature = signedCms.Encode();
            }
            catch (Exception ex)
            {
                Log.Error($"Encoding Exception occured : {ex.Message}");
            }

            return(signature);
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            var data = Encoding.ASCII.GetBytes("Hi!");

            var hash        = HashAlgorithm.Create("SHA256").ComputeHash(data);
            var certificate = new X509Certificate2(Convert.FromBase64String(cert), pwd);
            // So since I've no idea how you got p7s, i improvised here:
            var cms    = new SignedCms(new ContentInfo(hash), true); // true -> Detached
            var signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, certificate);

            cms.ComputeSignature(signer);
            var data2 = cms.Encode();
            // assuming this was in p7s file
            var xx = Convert.ToBase64String(data2);
            // this passes, this is the .Net validation from OP
            var cms2 = new SignedCms(new ContentInfo(hash), true);

            cms2.Decode(Convert.FromBase64String(xx));
            cms2.CheckSignature(true);
            // Same in bouncy castle:
            BCUtil.Validate(certificate, hash, xx);
        }
Beispiel #19
0
        /// <summary>
        /// Firma mensaje
        /// </summary>
        /// <param name="argBytesMsg">Bytes del mensaje</param>
        /// <param name="argCertFirmante">Certificado usado para firmar</param>
        /// <returns>Bytes del mensaje firmado</returns>
        /// <remarks></remarks>
        public static byte[] FirmaBytesMensaje(byte[] argBytesMsg, X509Certificate2 argCertFirmante)
        {
            const string ID_FNC = "[FirmaBytesMensaje]";

            try
            {
                // Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms)
                var infoContenido = new ContentInfo(argBytesMsg);
                var cmsFirmado    = new SignedCms(infoContenido);

                // Creo objeto CmsSigner que tiene las caracteristicas del firmante
                var cmsFirmante = new CmsSigner(argCertFirmante)
                {
                    IncludeOption = X509IncludeOption.EndCertOnly
                };


                if (VerboseMode)
                {
                    Console.WriteLine($@"{ID_FNC}***Firmando bytes del mensaje...");
                }

                // Firmo el mensaje PKCS #7
                cmsFirmado.ComputeSignature(cmsFirmante);

                if (VerboseMode)
                {
                    Console.WriteLine($@"{ID_FNC}***OK mensaje firmado");
                }

                // Encodeo el mensaje PKCS #7.
                return(cmsFirmado.Encode());
            }
            catch (Exception excepcionAlFirmar)
            {
                throw new Exception($"{ID_FNC}***Error al firmar: {excepcionAlFirmar.Message}");
            }
        }
Beispiel #20
0
        private static void VerifyWithExplicitPrivateKey(X509Certificate2 cert, AsymmetricAlgorithm key)
        {
            using (var pubCert = new X509Certificate2(cert.RawData))
            {
                Assert.False(pubCert.HasPrivateKey);

                byte[]      content     = { 9, 8, 7, 6, 5 };
                ContentInfo contentInfo = new ContentInfo(content);

                SignedCms cms    = new SignedCms(contentInfo);
                CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, pubCert, key)
                {
                    IncludeOption   = X509IncludeOption.EndCertOnly,
                    DigestAlgorithm = new Oid(Oids.Sha1, Oids.Sha1)
                };

                cms.ComputeSignature(signer);
                cms.CheckSignature(true);

                Assert.Equal(1, cms.SignerInfos.Count);
                Assert.Equal(pubCert, cms.SignerInfos[0].Certificate);
            }
        }
        public async Task <byte[]> Handle(Stream file)
        {
            var data = await ReadFully(file);

            var envelopedCms = new EnvelopedCms(new ContentInfo(data));

            envelopedCms.Encrypt(new CmsRecipient(cert));

            var encryptedMessage = envelopedCms.Encode();

            var signedCms = new SignedCms(new ContentInfo(encryptedMessage));

            var signer = new CmsSigner(cert)
            {
                IncludeOption = X509IncludeOption.EndCertOnly
            };

            signedCms.ComputeSignature(signer);

            var result = signedCms.Encode();

            return(result);
        }
Beispiel #22
0
 public byte[] signMessage(byte[] data, X509Certificate2 privateCert)
 {
     byte[] numArray;
     try
     {
         if (data == null)
         {
             throw new ArgumentNullException("data");
         }
         if (privateCert == null)
         {
             throw new ArgumentNullException("privateCertificate");
         }
         SignedCms signedCm = new SignedCms(new ContentInfo(data));
         signedCm.ComputeSignature(new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, privateCert));
         numArray = signedCm.Encode();
     }
     catch (Exception exception)
     {
         numArray = null;
     }
     return(numArray);
 }
Beispiel #23
0
        public static void CreateSignature_RsaPadding_DefaultToPkcs1()
        {
            ContentInfo content = new ContentInfo(new byte[] { 1, 2, 3 });
            SignedCms   cms     = new SignedCms(content);

            byte[] cmsBytes;

            using (X509Certificate2 cert = Certificates.RSA2048SignatureOnly.TryGetCertificateWithPrivateKey())
            {
                CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert, null, null);
                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.Rsa, signerInfo.SignatureAlgorithm.Value);
        }
Beispiel #24
0
        /// <summary>
        /// Generates a cryptographic signature for a given message
        /// </summary>
        /// <param name="message">The message to sign</param>
        /// <param name="signingCertificate">The certificate to sign the message with</param>
        /// <param name="encryptionCertificate">An optional encryption certificate to include along with the signature</param>
        /// <returns>The signature for the specified message</returns>
        internal static byte[] GetSignature(string message, X509Certificate2 signingCertificate, X509Certificate2 encryptionCertificate)
        {
            byte[] messageBytes = Encoding.ASCII.GetBytes(message);

            SignedCms signedCms = new SignedCms(new ContentInfo(messageBytes), true);

            CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate);

            cmsSigner.IncludeOption = X509IncludeOption.WholeChain;

            if (encryptionCertificate != null)
            {
                cmsSigner.Certificates.Add(encryptionCertificate);
            }

            Pkcs9SigningTime signingTime = new Pkcs9SigningTime();

            cmsSigner.SignedAttributes.Add(signingTime);

            signedCms.ComputeSignature(cmsSigner, false);

            return(signedCms.Encode());
        }
Beispiel #25
0
        public AsnElt Encode()
        {
            SignedCms signed = new SignedCms(
                new ContentInfo(
                    IdPkInitAuthData,
                    AuthPack.Encode().Encode()
                    )
                );

            var signer = new CmsSigner(PKCert);

            if (!VerifyCerts)
            {
                signer.IncludeOption = X509IncludeOption.EndCertOnly; // only the end certificate is included in the X.509 chain information.
            }
            signed.ComputeSignature(signer, silent: false);

            return(AsnElt.Make(AsnElt.SEQUENCE, new AsnElt[] {
                AsnElt.Make(AsnElt.CONTEXT, 0, new AsnElt[] {
                    AsnElt.MakeBlob(signed.Encode())
                })
            }));
        }
        public static void TryDecode_Fails_MalformedToken()
        {
            ContentInfo contentInfo = new ContentInfo(
                new Oid(Oids.TstInfo, Oids.TstInfo),
                new byte[] { 1 });

            SignedCms cms = new SignedCms(contentInfo);

            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
            {
                cms.ComputeSignature(new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert));
            }

            Assert.False(
                Rfc3161TimestampToken.TryDecode(
                    cms.Encode(),
                    out Rfc3161TimestampToken token,
                    out int bytesRead),
                "Rfc3161TimestampToken.TryDecode");

            Assert.Equal(0, bytesRead);
            Assert.Null(token);
        }
Beispiel #27
0
        //http://stackoverflow.com/questions/11526572/openssl-smime-in-c-sharp
        public static void Sign(string basePath)
        {
            var cert = new X509Certificate2(yourCertFile, yourCertFilePassword);

            var buffer = File.ReadAllBytes(Path.Combine(basePath, "manifest.json"));

            ContentInfo cont   = new ContentInfo(buffer);
            var         cms    = new SignedCms(cont, true);
            var         signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, cert);

            signer.IncludeOption = X509IncludeOption.ExcludeRoot;

            // TODO: You MUST visit this URL and download/install Apple's certificates
            // http://www.apple.com/certificateauthority/
            // Apple Inc. Root Certificate
            // Apple Computer, Inc. Root Certificate
            // Worldwide Developer Relations
            cms.ComputeSignature(signer);

            var myCmsMessage = cms.Encode();

            File.WriteAllBytes(Path.Combine(basePath, "signature"), myCmsMessage);
        }
Beispiel #28
0
        private byte[] Sign(byte[] data, X509Certificate2 signingCert)
        {
            // create ContentInfo
            ContentInfo content = new ContentInfo(data);

            // SignedCms represents signed data
            SignedCms signedMessage = new SignedCms(content);



            // create a signer
            CmsSigner signer = new CmsSigner(signingCert);

            // sign the data
            //Orig:signedMessage.ComputeSignature(signer);
            signedMessage.ComputeSignature(signer, false);

            // create PKCS #7 byte array
            byte[] signedBytes = signedMessage.Encode();

            // return signed data
            return(signedBytes);
        }
        public byte[] Sign(string certificateThumbprint, byte[] data, bool detached)
        {
            var store = new X509Store(StoreLocation.CurrentUser);

            store.Open(OpenFlags.ReadOnly);

            var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);

            if (certificates.Count == 0)
            {
                throw new Exception("Сертификат с отпечатком " + certificateThumbprint + " не найден в хранилище " + store.Location + ". Пользователь " + Environment.UserName);
            }

            var contentInfo = new ContentInfo(data);
            var signedCms   = new SignedCms(contentInfo, detached);
            var cmsSigner   = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificates[0]);

            cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.Now));

            signedCms.ComputeSignature(cmsSigner, true);

            return(signedCms.Encode());
        }
        /// <summary>
        /// Firma mensaje
        /// </summary>
        /// <param name="messageBytes">Bytes del mensaje</param>
        /// <param name="signerCertificate">Certificado usado para firmar</param>
        /// <returns>Bytes del mensaje firmado</returns>
        /// <remarks></remarks>
        public static byte[] SignMessageBytes(byte[] messageBytes, X509Certificate2 signerCertificate)
        {
            const string ID_FNC = "[FirmaBytesMensaje]";

            try
            {
                // Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms)
                var contentInfo = new ContentInfo(messageBytes);
                var signedCms   = new SignedCms(contentInfo);

                // Creo objeto CmsSigner que tiene las caracteristicas del firmante
                var cmsSigner = new CmsSigner(signerCertificate)
                {
                    IncludeOption = X509IncludeOption.EndCertOnly
                };

                if (VerboseMode)
                {
                    Console.WriteLine(ID_FNC + "***Firmando bytes del mensaje...");
                }

                // Firmo el mensaje PKCS #7
                signedCms.ComputeSignature(cmsSigner);

                if (VerboseMode)
                {
                    Console.WriteLine(ID_FNC + "***OK mensaje firmado");
                }

                // Encodeo el mensaje PKCS #7.
                return(signedCms.Encode());
            }
            catch (Exception ex)
            {
                throw new Exception(ID_FNC + "***Error al firmar: " + ex.Message);
            }
        }
Beispiel #31
0
        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;
        }
Beispiel #32
0
        /// <summary> 
        /// Construye un Login Ticket obtenido del WSAA 
        /// </summary> 
        /// <param name="argServicio">Servicio al que se desea acceder</param> 
        /// <param name="argUrlWsaa">URL del WSAA</param> 
        /// <param name="argRutaCertX509Firmante">Ruta del certificado X509 (con clave privada) usado para firmar</param> 
        /// <param name="argVerbose">Nivel detallado de descripcion? true/false</param> 
        /// <remarks></remarks> 
        public void Obtener(string argServicio, string argUrlWsaa, string argRutaCertX509Firmante, bool argVerbose)
        {
            RutaDelCertificadoFirmante = argRutaCertX509Firmante;

            string cmsFirmadoBase64;
            string respuesta;

            XmlNode xmlNodoUniqueId;
            XmlNode xmlNodoGenerationTime;
            XmlNode xmlNodoExpirationTime;
            XmlNode xmlNodoService;

            // PASO 1: Genero el Login Ticket Request
            try {
                solicitudXML = new XmlDocument ();
                solicitudXML.LoadXml (solicitudPlantillaXML);

                xmlNodoUniqueId = solicitudXML.SelectSingleNode ("//uniqueId");
                xmlNodoGenerationTime = solicitudXML.SelectSingleNode ("//generationTime");
                xmlNodoExpirationTime = solicitudXML.SelectSingleNode ("//expirationTime");
                xmlNodoService = solicitudXML.SelectSingleNode ("//service");

                var now = DateTime.Now;

                xmlNodoGenerationTime.InnerText = now.ToString ("s");
                xmlNodoExpirationTime.InnerText = now.AddHours (12).ToString ("s");
                xmlNodoUniqueId.InnerText = Convert.ToString (_globalUniqueID);
                xmlNodoService.InnerText = Servicio;

                _globalUniqueID += 1;

            } catch (Exception ex) {
                throw new Exception ("Error GENERANDO el Ticket de acceso : " + ex.Message);
            }

            // PASO 2: Firmo el Login Ticket Request
            try {
                // Convierto el login ticket request a bytes, para firmar
                Encoding EncodedMsg = Encoding.UTF8;
                byte[] msgBytes = EncodedMsg.GetBytes (solicitudXML.OuterXml);
                byte[] encodedSignedCms;
                // Firmo el msg y paso a Base64
                try {
                    var certList = new ArrayList ();
                    CMSTypedData msg = new CMSProcessableByteArray ("Hello world!".getBytes ());

                    certList.add (signCert);

                    Store certs = new JcaCertStore (certList);

                    var gen = new  CMSSignedDataGenerator ();
                    ContentSigner sha1Signer = new JcaContentSignerBuilder ("SHA1withRSA").setProvider ("BC").build (signKP.getPrivate ());

                    gen.addSignerInfoGenerator (
                        new JcaSignerInfoGeneratorBuilder (
                            new JcaDigestCalculatorProviderBuilder ().setProvider ("BC").build ())
                        .build (sha1Signer, signCert));

                    gen.addCertificates (certs);

                    CMSSignedData sigData = gen.generate (msg, false);

                    cmsFirmadoBase64 = Convert.ToBase64String (encodedSignedCms);
                    // Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms)
                    var infoContenido = new System.Security.Cryptography.Pkcs.ContentInfo (msgBytes);
                    var cmsFirmado = new SignedCms (infoContenido);

                    // Creo objeto CmsSigner que tiene las caracteristicas del firmante
                    var cmsFirmante = new CmsSigner (certificadoFirmante);
                    cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly;

                    // Firmo el mensaje PKCS #7
                    cmsFirmado.ComputeSignature (cmsFirmante);
                    // Encodeo el mensaje PKCS #7.
                    encodedSignedCms = cmsFirmado.Encode ();
                } catch (Exception excepcionAlFirmar) {
                    throw new Exception ("***Error al firmar: " + excepcionAlFirmar.Message);
                }
            } catch (Exception excepcionAlFirmar) {
                throw new Exception ("***Error FIRMANDO el LoginTicketRequest : " + excepcionAlFirmar.Message);
            }

            // PASO 3: Invoco al WSAA para obtener el Login Ticket Response
            try {
                var wsaa = new  WSAA.LoginCMSService ();
                respuesta = wsaa.loginCms (cmsFirmadoBase64);
            } catch (Exception ex) {
                throw new Exception ("Error INVOCANDO al servicio WSAA : " + ex.Message);
            }

            // PASO 4: Analizo el Login Ticket Response recibido del WSAA
            try {
                respuestaXML = new XmlDocument ();
                respuestaXML.LoadXml (respuesta);

                id = UInt32.Parse (respuestaXML.SelectSingleNode ("//uniqueId").InnerText);
                generacion = DateTime.Parse (respuestaXML.SelectSingleNode ("//generationTime").InnerText);
                expiracion = DateTime.Parse (respuestaXML.SelectSingleNode ("//expirationTime").InnerText);
                firma = respuestaXML.SelectSingleNode ("//sign").InnerText;
                token = respuestaXML.SelectSingleNode ("//token").InnerText;
            } catch (Exception ex) {
                throw new Exception ("Error ANALIZANDO el LoginTicketResponse : " + ex.Message);
            }
        }