コード例 #1
0
ファイル: SignApk.cs プロジェクト: peterdocter/signapk-1
        /** Write a .RSA file with a digital signature. */
        private static void writeSignatureBlock(
            MemoryStream signature, X509Certificate2 certificate, Stream out_)
        {
            string      OID_DATA  = "1.2.840.113549.1.7.1";
            ContentInfo content   = new ContentInfo(new Oid(OID_DATA), signature.ToArray());
            SignedCms   signedCms = new SignedCms(content, true);
            CmsSigner   signer    = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);

            signedCms.ComputeSignature(signer);
            var encodedPkcs7 = signedCms.Encode();

            out_.Write(encodedPkcs7, 0, encodedPkcs7.Length);
        }
コード例 #2
0
        public static void AddAttributeToIndefiniteLengthContent()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.IndefiniteLengthContentDocument);
            cms.SignerInfos[0].AddUnsignedAttribute(new Pkcs9DocumentDescription("Indefinite length test"));
            byte[] encoded = cms.Encode();

            cms = new SignedCms();
            cms.Decode(encoded);
            // It should sort first, because it's smaller.
            Assert.Equal(Oids.DocumentDescription, cms.SignerInfos[0].UnsignedAttributes[0].Oid.Value);
        }
コード例 #3
0
        public void AddTimestamp(SignedCms timestamp)
        {
            var bytes = timestamp.Encode();

            var unsignedAttribute = new AsnEncodedData(Oids.SignatureTimeStampTokenAttribute, bytes);

            if (_signedCms.SignerInfos.Count != 1)
            {
                throw new SignatureException(NuGetLogCode.NU3009, Strings.Error_NotOnePrimarySignature);
            }

            _signedCms.SignerInfos[0].AddUnsignedAttribute(unsignedAttribute);
        }
コード例 #4
0
        public static byte[] Encode(byte[] arMessage, object signerCert, string signerPassword)
        {
            X509Certificate2 cert        = signerCert is X509Certificate2 ? (X509Certificate2)signerCert : new X509Certificate2((string)signerCert, signerPassword);
            ContentInfo      contentInfo = new ContentInfo(arMessage);

            SignedCms signedCms = new SignedCms(contentInfo, true); // <- true detaches the signature
            CmsSigner cmsSigner = new CmsSigner(cert);

            signedCms.ComputeSignature(cmsSigner);
            byte[] signature = signedCms.Encode();

            return(signature);
        }
コード例 #5
0
        internal byte[] SignProject(ExcelVbaProject proj)
        {
            if (!Certificate.HasPrivateKey)
            {
                //throw (new InvalidOperationException("The certificate doesn't have a private key"));
                Certificate = null;
                return(null);
            }
            var hash = GetContentHash(proj);

            BinaryWriter bw = new BinaryWriter(new MemoryStream());

            bw.Write((byte)0x30);                                                                //Constructed Type
            bw.Write((byte)0x32);                                                                //Total length
            bw.Write((byte)0x30);                                                                //Constructed Type
            bw.Write((byte)0x0E);                                                                //Length SpcIndirectDataContent
            bw.Write((byte)0x06);                                                                //Oid Tag Indentifier
            bw.Write((byte)0x0A);                                                                //Lenght OId
            bw.Write(new byte[] { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x1D }); //Encoded Oid 1.3.6.1.4.1.311.2.1.29
            bw.Write((byte)0x04);                                                                //Octet String Tag Identifier
            bw.Write((byte)0x00);                                                                //Zero length

            bw.Write((byte)0x30);                                                                //Constructed Type (DigestInfo)
            bw.Write((byte)0x20);                                                                //Length DigestInfo
            bw.Write((byte)0x30);                                                                //Constructed Type (Algorithm)
            bw.Write((byte)0x0C);                                                                //length AlgorithmIdentifier
            bw.Write((byte)0x06);                                                                //Oid Tag Indentifier
            bw.Write((byte)0x08);                                                                //Lenght OId
            bw.Write(new byte[] { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05 });             //Encoded Oid for 1.2.840.113549.2.5 (AlgorithmIdentifier MD5)
            bw.Write((byte)0x05);                                                                //Null type identifier
            bw.Write((byte)0x00);                                                                //Null length
            bw.Write((byte)0x04);                                                                //Octet String Identifier
            bw.Write((byte)hash.Length);                                                         //Hash length
            bw.Write(hash);                                                                      //Content hash

            ContentInfo contentInfo = new ContentInfo(((MemoryStream)bw.BaseStream).ToArray());

            contentInfo.ContentType.Value = "1.3.6.1.4.1.311.2.1.4";
#if (Core)
            Verifier = new EnvelopedCms(contentInfo);
            var r = new CmsRecipient(Certificate);
            Verifier.Encrypt(r);
            return(Verifier.Encode());
#else
            Verifier = new SignedCms(contentInfo);
            var signer = new CmsSigner(Certificate);
            Verifier.ComputeSignature(signer, false);
            return(Verifier.Encode());
#endif
        }
コード例 #6
0
        private byte[] GetSignature(byte[] range)
        {
            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);
        }
コード例 #7
0
        public static byte[] SignDetached(byte[] data, X509Certificate2 signingCert)
        {
            var content = new ContentInfo(data);

            var signedMessage = new SignedCms(content, true);

            var signer = new CmsSigner(signingCert);

            signedMessage.ComputeSignature(signer);

            var signedBytes = signedMessage.Encode();

            return(signedBytes);
        }
コード例 #8
0
        public byte[] Sign(byte[] docByteArray)
        {
            Log.Info("Start Sign[]");
            //if (!CheckLicense())
            //    throw new Exception("Нет лицензии на использование данного метода.");

            var contentInfo = new ContentInfo(docByteArray);
            var signedCms   = new SignedCms(contentInfo, true);
            var cmsSigner   = new CmsSigner(CurrentCert);

            signedCms.ComputeSignature(cmsSigner, false);
            Log.Info("End Sign[]");
            return(signedCms.Encode());
        }
コード例 #9
0
        public static void AddFirstCounterSigner_NoSignature()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);

            SignerInfo firstSigner = cms.SignerInfos[0];

            // A certificate shouldn't really be required here, but on .NET Framework
            // it will prompt for the counter-signer's certificate if it's null,
            // even if the signature type is NoSignature.
            using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.TryGetCertificateWithPrivateKey())
            {
                firstSigner.ComputeCounterSignature(
                    new CmsSigner(
                        SubjectIdentifierType.NoSignature,
                        cert)
                {
                    IncludeOption = X509IncludeOption.None,
                });
            }

            Assert.ThrowsAny <CryptographicException>(() => cms.CheckSignature(true));
            cms.CheckHash();

            byte[] encoded = cms.Encode();
            cms = new SignedCms();
            cms.Decode(encoded);
            Assert.ThrowsAny <CryptographicException>(() => cms.CheckSignature(true));
            cms.CheckHash();

            firstSigner = cms.SignerInfos[0];
            firstSigner.CheckSignature(verifySignatureOnly: true);
            Assert.ThrowsAny <CryptographicException>(() => firstSigner.CheckHash());

            SignerInfo firstCounterSigner = firstSigner.CounterSignerInfos[0];

            Assert.ThrowsAny <CryptographicException>(() => firstCounterSigner.CheckSignature(true));

            if (PlatformDetection.IsFullFramework)
            {
                // NetFX's CheckHash only looks at top-level SignerInfos to find the
                // crypt32 CMS signer ID, so it fails on any check from a countersigner.
                Assert.ThrowsAny <CryptographicException>(() => firstCounterSigner.CheckHash());
            }
            else
            {
                firstCounterSigner.CheckHash();
            }
        }
コード例 #10
0
        private void SignManifestFile(PassGeneratorRequest request)
        {
            Trace.TraceInformation("Signing the manifest file...");

            X509Certificate2 card = GetCertificate(request);

            if (card == null)
            {
                throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct.");
            }

            X509Certificate2 appleCA = GetAppleCertificate(request);

            if (appleCA == null)
            {
                throw new FileNotFoundException("Apple Certificate could not be found. Please download it from http://www.apple.com/certificateauthority/ and install it into your LOCAL MACHINE certificate store.");
            }

            try
            {
                ContentInfo contentInfo = new ContentInfo(manifestFile);

                SignedCms signing = new SignedCms(contentInfo, true);

                CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, card)
                {
                    IncludeOption = X509IncludeOption.None
                };

                Trace.TraceInformation("Fetching Apple Certificate for signing..");
                Trace.TraceInformation("Constructing the certificate chain..");
                signer.Certificates.Add(appleCA);
                signer.Certificates.Add(card);

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

                Trace.TraceInformation("Processing the signature..");
                signing.ComputeSignature(signer);

                signatureFile = signing.Encode();

                Trace.TraceInformation("The file has been successfully signed!");
            }
            catch (Exception exp)
            {
                Trace.TraceError("Failed to sign the manifest file: [{0}]", exp.Message);
                throw new ManifestSigningException("Failed to sign manifest", exp);
            }
        }
コード例 #11
0
    protected void btnSendStatusUpdate_Click(object sender, EventArgs e)
    {
        UTF8Encoding utf8 = new UTF8Encoding();
        string       xml  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

        xml += "<current-status>It's really working .</current-status>";

        _oauth.Token       = ConfigHelper.GetConfigValue("LiApiKey");
        _oauth.TokenSecret = ConfigHelper.GetConfigValue("LiSecretKey");
        _oauth.Verifier    = txtoAuth_verifier.Text;

        string           thumbprint = ConfigHelper.GetConfigValue("SigningCert");
        X509Certificate2 localCert  = LoadCertificateFromStoreByThumb(thumbprint);

        if (localCert == null)
        {
            txtApiResponse.Text = "<b>Requested certificate not found.  Sending plain text request.</b>";
        }
        else
        {
            txtApiResponse.Text = "<b>Requested certificate found.  Sending signed request.</b>";
        }
        byte[]      msgBytes    = utf8.GetBytes(xml);
        ContentInfo contentInfo = new ContentInfo(msgBytes);

        //  Instantiate SignedCms object with the ContentInfo above.
        SignedCms signedCms = new SignedCms(contentInfo);

        // Create a signer object with the certificate we have loaded from the local store by thumbnail.
        CmsSigner cmsSigner = new CmsSigner(localCert);

        // sign the message
        signedCms.ComputeSignature(cmsSigner);

        // create serialized representation
        byte[] signedBytes = signedCms.Encode();

        var signedData = Convert.ToBase64String(signedBytes);



        string response = _oauth.APIWebRequest("GET", "https://api.xero.com/api.xro/2.0/Invoices", null);

        if (response == "")
        {
            txtApiResponse.Text = "Your new status updated";
        }
        btnSendStatusUpdate.Focus();
    }
コード例 #12
0
        private void ButtonSignatureWithoutData_Click(object sender, EventArgs e)
        {
            byte[]           data = Encoding.UTF8.GetBytes(textBoxInfo.Text);
            X509Certificate2 cert = new X509Certificate2(fileCertPFX, pwdfileCertPFX);

            ContentInfo contentInfo = new ContentInfo(data);
            CmsSigner   cmsSigner   = new CmsSigner(cert);
            SignedCms   signedCms   = new SignedCms(contentInfo, true); // true = detached

            signedCms.ComputeSignature(cmsSigner);

            this.tempDigitalSignature = signedCms.Encode(); // msg no formato PCKS7 só com a assinatura pq está dettached

            //textBoxInfo.Text += Environment.NewLine + Convert.ToBase64String(tempDigitalSignature) + Environment.NewLine;
        }
コード例 #13
0
        private async Task <ReadOnlyMemory <byte> > SignDHResponseAsync(KrbKdcDHKeyInfo keyInfo)
        {
            var signed = new SignedCms(
                new ContentInfo(
                    IdPkInitDHKeyData,
                    keyInfo.Encode().ToArray()
                    )
                );

            var Certificate = await Service.Principals.RetrieveKdcCertificate();

            signed.ComputeSignature(new CmsSigner(Certificate));

            return(signed.Encode());
        }
コード例 #14
0
ファイル: Signature.cs プロジェクト: supercoeus/SignApk
        public static byte[] GetRSAData(ZipFile zip, byte[] sfData, string rsaName, string keyFile)
        {
            if (!File.Exists(keyFile))
            {
                throw new NoKeyException();
            }

            X509Certificate2 certificate = new X509Certificate2(keyFile);
            ContentInfo      content     = new ContentInfo(sfData);
            SignedCms        signedCms   = new SignedCms(content, true);
            CmsSigner        signer      = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);

            signedCms.ComputeSignature(signer);
            return(signedCms.Encode());
        }
コード例 #15
0
        private static string SignDetached(byte[] data, X509Certificate2 signingCert)
        {
            ContentInfo content = new ContentInfo(data);

            SignedCms signedMessage = new SignedCms(content, true);

            CmsSigner signer = new CmsSigner(signingCert);


            signedMessage.ComputeSignature(signer);
            byte[] signedBytes = signedMessage.Encode();


            return(Convert.ToBase64String(signedBytes));
        }
コード例 #16
0
 /// <summary>
 /// Создать подпись
 /// </summary>
 /// <param name="message">
 /// </param>
 /// <param name="certificate">
 /// The certificate.
 /// </param>
 /// <returns>
 /// Возвращает цифровую подпись
 /// </returns>
 public byte[] Sign(byte[] message, X509Certificate2 certificate)
 {
     try
     {
         var contentInfo = new ContentInfo(message);
         var signedCms   = new SignedCms(contentInfo, true); // образом сообщение не будет включено в SignedCms.
         var cmsSigner   = new CmsSigner(certificate);       // Определяем подписывающего, объектом CmsSigner.
         signedCms.ComputeSignature(cmsSigner, false);       // Подписываем CMS/PKCS #7 сообение.
         return(signedCms.Encode());
     }
     catch (Exception e)
     {
         this.InfoListBox.Items.Add(e.Message);
         return(null);
     }
 }
コード例 #17
0
ファイル: CmsCryptography.cs プロジェクト: khangnv111/1400.vn
 private byte[] ComputeSignature(byte[] messageBytes)
 {
     try
     {
         ContentInfo cont   = new ContentInfo(messageBytes);
         SignedCms   signed = new SignedCms(cont, true);
         CmsSigner   signer = new CmsSigner(_SignerCert);
         signer.IncludeOption = X509IncludeOption.None;
         signed.ComputeSignature(signer);
         return(signed.Encode());
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #18
0
        private static byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert)
        {
            ContentInfo contentInfo = new ContentInfo(msg);

            // true = dessatachado e false = atachado
            SignedCms signedCms = new SignedCms(contentInfo, false);

            CmsSigner cmsSigner = new CmsSigner(signerCert);

            //  Sign the PKCS #7 message.
            //MessageBox.Show("Computing signature with signer subject name:... " + signerCert.SubjectName.Name);
            signedCms.ComputeSignature(cmsSigner, false);

            //  Encode the PKCS #7 message.
            return(signedCms.Encode());
        }
コード例 #19
0
        /// <summary>
        /// Signs a data hash and returns the signature
        /// </summary>
        /// <param name="x">Certificate used to sign the data</param>
        /// <param name="hashedData">Data digest to be signed</param>
        /// <returns>Returns a string containing a PKCS#7 signature</returns>
        protected String EncodeCMS(X509Certificate2 x, byte[] hashedData)
        {
            //we are creating a CMS/PKCS#7 message
            Oid         digestOid   = new Oid("1.2.840.113549.1.7.2");
            ContentInfo contentInfo = new ContentInfo(digestOid, hashedData);

            //true: signature is detached and will be added to the file
            SignedCms signedCms = new SignedCms(contentInfo, true);

            CmsSigner cmsSigner = new CmsSigner(x);

            // false will prompt the user to enter the pin if a PIV is used
            signedCms.ComputeSignature(cmsSigner, false);
            byte[] encode = signedCms.Encode();
            return(Convert.ToBase64String(encode));
        }
コード例 #20
0
        private byte[] Protect(byte[] data, X509Certificate2 encryptionCertificate)
        {
            // first we sign the message
            SignedCms signedCms = new SignedCms(new ContentInfo(data));

            signedCms.ComputeSignature(new CmsSigner(SigningCertificate));
            byte[] signedData = signedCms.Encode();

            // then we encrypt it
            CmsRecipient cmsRecipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, encryptionCertificate);
            EnvelopedCms envelopedCms = new EnvelopedCms(new ContentInfo(signedData));

            envelopedCms.Encrypt(cmsRecipient);

            return(envelopedCms.Encode());
        }
コード例 #21
0
        /// <summary>
        /// Signs a payload, using CMS, with the provided certificate
        /// </summary>
        /// <param name="payload">The bytes to sign</param>
        /// <param name="signingCertificate">The certificate to sign with</param>
        /// <returns>The signature</returns>
        private static byte[] SignBytes(byte[] payload, X509Certificate2 signingCertificate)
        {
            CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate)
            {
                IncludeOption   = X509IncludeOption.WholeChain,
                DigestAlgorithm = Oid.FromFriendlyName(RdpSignatureDigestAlgorithmName, OidGroup.All)
            };

            ContentInfo content = new ContentInfo(payload);

            SignedCms cmsPayload = new SignedCms(content, true);

            cmsPayload.ComputeSignature(signer);

            return(cmsPayload.Encode());
        }
コード例 #22
0
        public static void VerifyUnsortedAttributeSignature_ImportExportImport()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.DigiCertTimeStampToken);

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

            byte[] exported = cms.Encode();
            cms = new SignedCms();
            cms.Decode(exported);

            // Assert.NoThrows
            cms.CheckSignature(true);
        }
コード例 #23
0
		/// <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));
		}
コード例 #24
0
        Stream Sign(RealCmsSigner signer, Stream content, bool detach)
        {
            var contentInfo = new ContentInfo(ReadAllBytes(content));
            var signed      = new SignedCms(contentInfo, detach);

            try {
                signed.ComputeSignature(signer);
            } catch (CryptographicException) {
                signer.IncludeOption = X509IncludeOption.EndCertOnly;
                signed.ComputeSignature(signer);
            }

            var signedData = signed.Encode();

            return(new MemoryStream(signedData, false));
        }
コード例 #25
0
        internal static byte[] GetSignature(this string message, X509Certificate2 signingCertificate,
                                            X509Certificate2?encryptionCertificate = null)
        {
            var messageBytes = Encoding.ASCII.GetBytes(message);
            var signedCms    = new SignedCms(new ContentInfo(messageBytes), true);
            var cmsSigner    = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate);

            cmsSigner.IncludeOption = X509IncludeOption.WholeChain;
            if (encryptionCertificate != null)
            {
                cmsSigner.Certificates.Add(encryptionCertificate);
            }
            cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime());
            signedCms.ComputeSignature(cmsSigner, false);
            return(signedCms.Encode());
        }
コード例 #26
0
        public override void TransformKdcReq(KrbKdcReq req)
        {
            var padata = req.PaData.ToList();

            KrbAuthPack authPack;

            if (SupportsEllipticCurveDiffieHellman)
            {
                authPack = CreateEllipticCurveDiffieHellmanAuthPack(req.Body);
            }
            else if (SupportsDiffieHellman)
            {
                authPack = CreateDiffieHellmanAuthPack(req.Body);
            }
            else
            {
                throw OnlyKeyAgreementSupportedException();
            }

            KerberosConstants.Now(out authPack.PKAuthenticator.CTime, out authPack.PKAuthenticator.CuSec);

            SignedCms signed = new SignedCms(
                new ContentInfo(
                    IdPkInitAuthData,
                    authPack.Encode().ToArray()
                    )
                );

            var signer = new CmsSigner(Certificate)
            {
                IncludeOption = IncludeOption
            };

            signed.ComputeSignature(signer, silent: true);

            var pk = new KrbPaPkAsReq {
                SignedAuthPack = signed.Encode()
            };

            padata.Add(new KrbPaData
            {
                Type  = PaDataType.PA_PK_AS_REQ,
                Value = pk.Encode()
            });

            req.PaData = padata.ToArray();
        }
コード例 #27
0
        public ActionResult SignAndEncrypt(SignedAsymmetricModel model)
        {
            if (model.Action == "encrypt")
            {
                var plainTextAsBytes     = Encoding.Unicode.GetBytes(model.PlainText);
                var recipientCertificate = LoadCertificate(model.RecipientThumbprint);
                var signingCertificate   = LoadCertificate(model.SenderThumbprint);

                // Sign message
                var signatureContentInfo = new ContentInfo(plainTextAsBytes);
                var signedCms            = new SignedCms(signatureContentInfo);
                var cmsSigner            = new CmsSigner(signingCertificate);
                signedCms.ComputeSignature(cmsSigner);
                var signedMessageAsBytes = signedCms.Encode();

                // Encrypt
                var encryptedContentInfo = new ContentInfo(signedMessageAsBytes);
                var envelopedCms         = new EnvelopedCms(encryptedContentInfo);
                var cmsRecipient         = new CmsRecipient(recipientCertificate);
                envelopedCms.Encrypt(cmsRecipient);
                var envelopeAsBytes = envelopedCms.Encode();

                model.Envelope  = Convert.ToBase64String(envelopeAsBytes);
                model.PlainText = string.Empty;
            }
            else if (model.Action == "decrypt")
            {
                // Decrypt
                var cipherTextAsBytes = Convert.FromBase64String(model.Envelope);
                var envelopedCms      = new EnvelopedCms();
                envelopedCms.Decode(cipherTextAsBytes);
                envelopedCms.Decrypt();
                var encodedSignedCMS = envelopedCms.Encode();
                var signedCms        = new SignedCms();
                signedCms.Decode(encodedSignedCMS);
                signedCms.CheckSignature(true);

                var plainTextAsBytes = signedCms.ContentInfo.Content;
                model.PlainText     = UnicodeEncoding.Unicode.GetString(plainTextAsBytes);
                model.SenderSubject = signedCms.SignerInfos[0].Certificate.Subject;
                model.Envelope      = string.Empty;
            }
            model.RecipientThumbprint = RecipientThumbprint;
            model.SenderThumbprint    = SenderThumbprint;
            ModelState.Clear();
            return(View(model));
        }
コード例 #28
0
    public static byte[] Sign(byte[] data, X509Certificate2 certificate)
    {
        if (data == null)
        {
            throw new ArgumentNullException("data");
        }
        if (certificate == null)
        {
            throw new ArgumentNullException("certificate");
        }
        ContentInfo content   = new ContentInfo(data);
        SignedCms   signedCms = new SignedCms(content, false);
        CmsSigner   signer    = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);

        signedCms.ComputeSignature(signer);
        return(signedCms.Encode());
    }
コード例 #29
0
        public async Task Load_WithPrimarySignatureWithNoCertificates_ThrowsAsync()
        {
            var packageContext = new SimpleTestPackageContext();

            using (var directory = TestDirectory.Create())
                using (var certificate = new X509Certificate2(_trustedTestCert.Source.Cert))
                {
                    var packageFilePath = await SignedArchiveTestUtility.AuthorSignPackageAsync(
                        certificate,
                        packageContext,
                        directory);

                    var signatureFileBytes = ReadSignatureFile(packageFilePath);
                    var signedCms          = new SignedCms();

                    signedCms.Decode(signatureFileBytes);

                    var certificateStore = X509StoreFactory.Create(
                        "Certificate/Collection",
                        new X509CollectionStoreParameters(Array.Empty <Org.BouncyCastle.X509.X509Certificate>()));
                    var crlStore = X509StoreFactory.Create(
                        "CRL/Collection",
                        new X509CollectionStoreParameters(Array.Empty <Org.BouncyCastle.X509.X509Crl>()));

                    using (var readStream = new MemoryStream(signedCms.Encode()))
                        using (var writeStream = new MemoryStream())
                        {
                            CmsSignedDataParser.ReplaceCertificatesAndCrls(
                                readStream,
                                certificateStore,
                                crlStore,
                                certificateStore,
                                writeStream);

                            signedCms.Decode(writeStream.ToArray());
                        }

                    Assert.Empty(signedCms.Certificates);

                    var exception = Assert.Throws <SignatureException>(
                        () => PrimarySignature.Load(signedCms));

                    Assert.Equal(NuGetLogCode.NU3010, exception.Code);
                    Assert.Contains("The primary signature does not have a signing certificate.", exception.Message);
                }
        }
コード例 #30
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);
        }
コード例 #31
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);
            }
        }
コード例 #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;
        }