Example #1
0
        private ITestResult EnvelopedTest()
        {
            try
            {
                // Key trans
                ContentInfo info = ContentInfo.GetInstance(
                    Asn1Object.FromByteArray(envDataKeyTrns));
                EnvelopedData envData = EnvelopedData.GetInstance(info.Content);
                Asn1Set       s       = envData.RecipientInfos;

                if (s.Count != 1)
                {
                    return(new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong number of recipients"));
                }

                RecipientInfo recip = RecipientInfo.GetInstance(s[0]);

                if (recip.Info is KeyTransRecipientInfo)
                {
                    KeyTransRecipientInfo inf = KeyTransRecipientInfo.GetInstance(recip.Info);

                    inf = new KeyTransRecipientInfo(inf.RecipientIdentifier, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);

                    s = new DerSet(new RecipientInfo(inf));
                }
                else
                {
                    return(new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong recipient type"));
                }

                envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
                info    = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);

                if (!Arrays.AreEqual(info.GetEncoded(), envDataKeyTrns))
                {
                    return(new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped failed to re-encode"));
                }


                // KEK
                info = ContentInfo.GetInstance(
                    Asn1Object.FromByteArray(envDataKEK));
                envData = EnvelopedData.GetInstance(info.Content);
                s       = envData.RecipientInfos;

                if (s.Count != 1)
                {
                    return(new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong number of recipients"));
                }

                recip = RecipientInfo.GetInstance(s[0]);

                if (recip.Info is KekRecipientInfo)
                {
                    KekRecipientInfo inf = KekRecipientInfo.GetInstance(recip.Info);

                    inf = new KekRecipientInfo(inf.KekID, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);

                    s = new DerSet(new RecipientInfo(inf));
                }
                else
                {
                    return(new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong recipient type"));
                }

                envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
                info    = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);

                if (!Arrays.AreEqual(info.GetEncoded(), envDataKEK))
                {
                    return(new SimpleTestResult(false, Name + ": CMS KEK enveloped failed to re-encode"));
                }

                // Nested NDEF problem
                Asn1StreamParser    asn1In = new Asn1StreamParser(new MemoryStream(envDataNestedNDEF, false));
                ContentInfoParser   ci     = new ContentInfoParser((Asn1SequenceParser)asn1In.ReadObject());
                EnvelopedDataParser ed     = new EnvelopedDataParser((Asn1SequenceParser)ci
                                                                     .GetContent(Asn1Tags.Sequence));
                Touch(ed.Version);
                ed.GetOriginatorInfo();
                ed.GetRecipientInfos().ToAsn1Object();
                EncryptedContentInfoParser eci = ed.GetEncryptedContentInfo();
                Touch(eci.ContentType);
                Touch(eci.ContentEncryptionAlgorithm);

                Stream dataIn = ((Asn1OctetStringParser)eci.GetEncryptedContent(Asn1Tags.OctetString))
                                .GetOctetStream();
                Streams.Drain(dataIn);
                dataIn.Close();

                // Test data doesn't have unprotected attrs, bug was being thrown by this call
                Asn1SetParser upa = ed.GetUnprotectedAttrs();
                if (upa != null)
                {
                    upa.ToAsn1Object();
                }

                return(new SimpleTestResult(true, Name + ": Okay"));
            }
            catch (Exception e)
            {
                return(new SimpleTestResult(false, Name + ": CMS enveloped failed - " + e.ToString(), e));
            }
        }
Example #2
0
        /**
         * generate a signed object that for a CMS Signed Data
         * object - if encapsulate is true a copy
         * of the message will be included in the signature. The content type
         * is set according to the OID represented by the string signedContentType.
         */
        public Stream Open(
            Stream outStream,
            string signedContentType,
            bool encapsulate)
        {
            //
            // ContentInfo
            //
            BerSequenceGenerator sGen = new BerSequenceGenerator(outStream);

            sGen.AddObject(CmsObjectIdentifiers.SignedData);

            //
            // Signed Data
            //
            BerSequenceGenerator sigGen = new BerSequenceGenerator(
                sGen.GetRawOutputStream(), 0, true);

            sigGen.AddObject(CalculateVersion(signedContentType));

            Asn1EncodableVector digestAlgs = new Asn1EncodableVector();

            //
            // add the precalculated SignerInfo digest algorithms.
            //
            foreach (SignerInformation signer in _signers)
            {
                digestAlgs.Add(FixAlgID(signer.DigestAlgorithmID));
            }

            //
            // add the new digests
            //
            foreach (SignerInf signer in _signerInfs)
            {
                digestAlgs.Add(FixAlgID(signer.DigestAlgorithmID));
            }

            {
                byte[] tmp = new DerSet(digestAlgs).GetEncoded();
                sigGen.GetRawOutputStream().Write(tmp, 0, tmp.Length);
            }

            BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream());

            eiGen.AddObject(new DerObjectIdentifier(signedContentType));

            Stream digStream;

            if (encapsulate)
            {
                BerOctetStringGenerator octGen = new BerOctetStringGenerator(
                    eiGen.GetRawOutputStream(), 0, true);

                if (_bufferSize != 0)
                {
                    digStream = octGen.GetOctetOutputStream(new byte[_bufferSize]);
                }
                else
                {
                    digStream = octGen.GetOctetOutputStream();
                }
            }
            else
            {
                digStream = new NullOutputStream();
            }

            foreach (IDigest d in _messageDigests)
            {
                digStream = new DigestStream(digStream, null, d);
            }

            return(new CmsSignedDataOutputStream(this, digStream, signedContentType, sGen, sigGen, eiGen));
        }
Example #3
0
        /// <summary>
        /// Формирование сигнатуры для серверной подписи
        /// </summary>
        /// <param name="alg"></param>
        /// <param name="data"></param>
        /// <param name="detached"></param>
        /// <returns></returns>
        public static byte[] ComputeSignature(Gost3410 alg, byte[] data, bool detached = true)
        {
            var certBytes = alg.ContainerCertificateRaw;

            var _x509CertificateParser = new BCX509.X509CertificateParser();
            var bcCert = _x509CertificateParser.ReadCertificate(certBytes);

            ICollection <BCX509.X509Certificate> certPath = new List <BCX509.X509Certificate>();

            certPath.Add(bcCert);

            IDigest digest;
            string  hashOid;
            string  signOid;

            if (GostCryptoConfig.ProviderType == ProviderTypes.CryptoPro256)
            {
                digest  = new GOST3411_2012_256Digest();
                signOid = Constants.OID_GR3410_12_256;
                hashOid = Constants.OID_GR3411_12_256;
            }
            else if (GostCryptoConfig.ProviderType == ProviderTypes.CryptoPro512)
            {
                digest  = new GOST3411_2012_512Digest();
                signOid = Constants.OID_GR3410_12_512;
                hashOid = Constants.OID_GR3411_12_512;
            }
            else
            {
                digest  = new Gost3411Digest();
                signOid = Constants.OID_GR3410_2001;
                hashOid = Constants.OID_GR3411_2001;
            }

            byte[] dataHash = ComputeDigest(digest, data);

            // Construct SignerInfo.signedAttrs
            Asn1EncodableVector signedAttributesVector = new Asn1EncodableVector();

            // Add PKCS#9 contentType signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(Constants.szOID_RSA_contentType),
                    new DerSet(new DerObjectIdentifier(Constants.szOID_RSA_data))));

            // Add PKCS#9 messageDigest signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(Constants.szOID_RSA_messageDigest),
                    new DerSet(new DerOctetString(dataHash))));

            // Add PKCS#9 signingTime signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(Constants.szOID_RSA_signingTime),
                    new DerSet(new Org.BouncyCastle.Asn1.Cms.Time(new DerUtcTime(DateTime.UtcNow)))));

            DerSet signedAttributes = new DerSet(signedAttributesVector);

            byte[] pkcs1Digest = ComputeDigest(digest, signedAttributes.GetDerEncoded());
            //byte[] pkcs1DigestInfo = CreateDigestInfo(pkcs1Digest, hashOid);

            var formatter = new GostSignatureFormatter(alg);
            var signature = formatter.CreateSignature(pkcs1Digest);

            // Construct SignerInfo
            SignerInfo signerInfo = new SignerInfo(
                new SignerIdentifier(new IssuerAndSerialNumber(bcCert.IssuerDN, bcCert.SerialNumber)),
                new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null),
                signedAttributes,
                new AlgorithmIdentifier(new DerObjectIdentifier(signOid), null),
                new DerOctetString(signature),
                null);

            // Construct SignedData.digestAlgorithms
            Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();

            digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null));

            // Construct SignedData.encapContentInfo
            ContentInfo encapContentInfo = new ContentInfo(
                new DerObjectIdentifier(Constants.szOID_RSA_data),
                (detached) ? null : new DerOctetString(data));

            // Construct SignedData.certificates
            Asn1EncodableVector certificatesVector = new Asn1EncodableVector();

            foreach (BCX509.X509Certificate cert in certPath)
            {
                certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
            }

            // Construct SignedData.signerInfos
            Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();

            signerInfosVector.Add(signerInfo.ToAsn1Object());

            // Construct SignedData
            SignedData signedData = new SignedData(
                new DerSet(digestAlgorithmsVector),
                encapContentInfo,
                new BerSet(certificatesVector),
                null,
                new DerSet(signerInfosVector));

            // Construct top level ContentInfo
            ContentInfo contentInfo = new ContentInfo(
                new DerObjectIdentifier(Constants.szOID_RSA_signedData),
                signedData);

            return(contentInfo.GetDerEncoded());
        }
Example #4
0
        static void PKCS7()
        {
            GostCryptoConfig.ProviderType = ProviderTypes.VipNet;
            Config.InitCommon();

            BCX509.X509Certificate bcCert = null;
            using (var g = GostCryptoConfig.CreateGost3410AsymmetricAlgorithm())
            {
                bool   detached = false;
                byte[] data     = File.ReadAllBytes("test.xml");

                var certBytes = g.ContainerCertificateRaw;

                BCX509.X509CertificateParser _x509CertificateParser = new BCX509.X509CertificateParser();
                bcCert = _x509CertificateParser.ReadCertificate(certBytes);

                ICollection <BCX509.X509Certificate> certPath = new List <BCX509.X509Certificate>();
                certPath.Add(bcCert);

                IDigest digest  = new Gost3411Digest();
                string  hashOid = GostCryptoConfig.DefaultHashOid;

                byte[] dataHash = ComputeDigest(digest, data);

                // Construct SignerInfo.signedAttrs
                Asn1EncodableVector signedAttributesVector = new Asn1EncodableVector();

                // Add PKCS#9 contentType signed attribute
                signedAttributesVector.Add(
                    new Org.BouncyCastle.Asn1.Cms.Attribute(
                        new DerObjectIdentifier("1.2.840.113549.1.9.3"),
                        new DerSet(new DerObjectIdentifier("1.2.840.113549.1.7.1"))));

                // Add PKCS#9 messageDigest signed attribute
                signedAttributesVector.Add(
                    new Org.BouncyCastle.Asn1.Cms.Attribute(
                        new DerObjectIdentifier("1.2.840.113549.1.9.4"),
                        new DerSet(new DerOctetString(dataHash))));

                // Add PKCS#9 signingTime signed attribute
                signedAttributesVector.Add(
                    new Org.BouncyCastle.Asn1.Cms.Attribute(
                        new DerObjectIdentifier("1.2.840.113549.1.9.5"),
                        new DerSet(new Org.BouncyCastle.Asn1.Cms.Time(new DerUtcTime(DateTime.UtcNow)))));

                DerSet signedAttributes = new DerSet(signedAttributesVector);
                byte[] pkcs1Digest      = ComputeDigest(digest, signedAttributes.GetDerEncoded());
                byte[] pkcs1DigestInfo  = CreateDigestInfo(pkcs1Digest, hashOid);

                // hash


                //var signature = g.CreateSignature(hash);
                var formatter = new GostSignatureFormatter(g);
                var signature = formatter.CreateSignature(pkcs1Digest);

                // Construct SignerInfo
                SignerInfo signerInfo = new SignerInfo(
                    new SignerIdentifier(new IssuerAndSerialNumber(bcCert.IssuerDN, bcCert.SerialNumber)),
                    new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null),
                    signedAttributes,
                    new AlgorithmIdentifier(new DerObjectIdentifier(GostCryptoConfig.DefaultSignOid), null),
                    new DerOctetString(signature),
                    null);

                // Construct SignedData.digestAlgorithms
                Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();
                digestAlgorithmsVector.Add(new AlgorithmIdentifier(new DerObjectIdentifier(hashOid), null));

                // Construct SignedData.encapContentInfo
                ContentInfo encapContentInfo = new ContentInfo(
                    new DerObjectIdentifier("1.2.840.113549.1.7.1"),
                    (detached) ? null : new DerOctetString(data));

                // Construct SignedData.certificates
                Asn1EncodableVector certificatesVector = new Asn1EncodableVector();
                foreach (BCX509.X509Certificate cert in certPath)
                {
                    certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
                }

                // Construct SignedData.signerInfos
                Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();
                signerInfosVector.Add(signerInfo.ToAsn1Object());

                // Construct SignedData
                SignedData signedData = new SignedData(
                    new DerSet(digestAlgorithmsVector),
                    encapContentInfo,
                    new BerSet(certificatesVector),
                    null,
                    new DerSet(signerInfosVector));

                // Construct top level ContentInfo
                ContentInfo contentInfo = new ContentInfo(
                    new DerObjectIdentifier("1.2.840.113549.1.7.2"),
                    signedData);

                var res = contentInfo.GetDerEncoded();
                File.WriteAllBytes("test.p7", res);


                CmsSignedData cms = new CmsSignedData(res);

                var certStore = cms.GetCertificates("Collection");


                SignerInformationStore signers = cms.GetSignerInfos();
                var it = signers.GetSigners().GetEnumerator();
                it.MoveNext();
                var signer = it.Current as SignerInformation;

                var b = signer.Verify(bcCert);
            }
        }
Example #5
0
        public override void PerformTest()
        {
            Asn1EncodableVector v = new Asn1EncodableVector();

            byte[] data = new byte[10];

            v.Add(new DerOctetString(data));
            v.Add(new DerBitString(data));
            v.Add(new DerInteger(100));
            v.Add(DerBoolean.True);

            checkSortedSet(0, new DerSet(v));

            v = new Asn1EncodableVector();
            v.Add(new DerInteger(100));
            v.Add(DerBoolean.True);
            v.Add(new DerOctetString(data));
            v.Add(new DerBitString(data));

            checkSortedSet(1, new DerSet(v));

            v = new Asn1EncodableVector();
            v.Add(DerBoolean.True);
            v.Add(new DerOctetString(data));
            v.Add(new DerBitString(data));
            v.Add(new DerInteger(100));


            checkSortedSet(2, new DerSet(v));

            v = new Asn1EncodableVector();
            v.Add(new DerBitString(data));
            v.Add(new DerOctetString(data));
            v.Add(new DerInteger(100));
            v.Add(DerBoolean.True);

            checkSortedSet(3, new DerSet(v));

            v = new Asn1EncodableVector();
            v.Add(new DerOctetString(data));
            v.Add(new DerBitString(data));
            v.Add(new DerInteger(100));
            v.Add(DerBoolean.True);

            Asn1Set s = new BerSet(v);

            if (!(s[0] is DerOctetString))
            {
                Fail("BER set sort order changed.");
            }

            // create an implicitly tagged "set" without sorting
            Asn1TaggedObject tag = new DerTaggedObject(false, 1, new DerSequence(v));

            s = Asn1Set.GetInstance(tag, false);

            if (s[0] is DerBoolean)
            {
                Fail("sorted when shouldn't be.");
            }

            // equality test
            v = new Asn1EncodableVector();

            v.Add(DerBoolean.True);
            v.Add(DerBoolean.True);
            v.Add(DerBoolean.True);

            s = new DerSet(v);
        }
        /**
         * generate a signed object that for a CMS Signed Data
         * object using the given provider - if encapsulate is true a copy
         * of the message will be included in the signature. The content type
         * is set according to the OID represented by the string signedContentType.
         * @param out stream the CMS object is to be written to.
         * @param signedContentType OID for data to be signed.
         * @param encapsulate true if data should be encapsulated.
         * @param dataOutputStream output stream to copy the data being signed to.
         */
        public Stream Open(
            Stream outStream,
            string signedContentType,
            bool encapsulate,
            Stream dataOutputStream)
        {
            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }
            if (!outStream.CanWrite)
            {
                throw new ArgumentException("Expected writeable stream", "outStream");
            }
            if (dataOutputStream != null && !dataOutputStream.CanWrite)
            {
                throw new ArgumentException("Expected writeable stream", "dataOutputStream");
            }

            _messageDigestsLocked = true;

            //
            // ContentInfo
            //
            BerSequenceGenerator sGen = new BerSequenceGenerator(outStream);

            sGen.AddObject(CmsObjectIdentifiers.SignedData);

            //
            // Signed Data
            //
            BerSequenceGenerator sigGen = new BerSequenceGenerator(
                sGen.GetRawOutputStream(), 0, true);

            sigGen.AddObject(CalculateVersion(signedContentType));

            Asn1EncodableVector digestAlgs = new Asn1EncodableVector();

            foreach (string digestOid in _messageDigestOids)
            {
                digestAlgs.Add(
                    new AlgorithmIdentifier(new DerObjectIdentifier(digestOid), DerNull.Instance));
            }

            {
                byte[] tmp = new DerSet(digestAlgs).GetEncoded();
                sigGen.GetRawOutputStream().Write(tmp, 0, tmp.Length);
            }

            BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream());

            eiGen.AddObject(new DerObjectIdentifier(signedContentType));

            Stream digStream;

            if (encapsulate)
            {
                BerOctetStringGenerator octGen = new BerOctetStringGenerator(
                    eiGen.GetRawOutputStream(), 0, true);

                digStream = octGen.GetOctetOutputStream(_bufferSize);

                if (dataOutputStream != null)
                {
                    digStream = new TeeOutputStream(dataOutputStream, digStream);
                }
            }
            else
            {
                if (dataOutputStream != null)
                {
                    digStream = dataOutputStream;
                }
                else
                {
                    digStream = new NullOutputStream();
                }
            }

            foreach (IDigest d in _messageDigests.Values)
            {
                digStream = new DigestStream(digStream, null, d);
            }

            return(new CmsSignedDataOutputStream(this, digStream, signedContentType, sGen, sigGen, eiGen));
        }
        /// <summary>
        /// Creates a certificate signing request from an
        /// existing certificate with a private key.
        /// </summary>
        public static byte[] CreateSigningRequest(
            X509Certificate2 certificate,
            IList <String> domainNames = null
            )
        {
            if (certificate == null)
            {
                throw new ArgumentNullException(nameof(certificate));
            }
            using (var cfrg = new CertificateFactoryRandomGenerator())
            {
                SecureRandom random = new SecureRandom(cfrg);

                // try to get signing/private key from certificate passed in
                AsymmetricKeyParameter signingKey = X509Utils.GetPrivateKeyParameter(certificate);
                RsaKeyParameters       publicKey  = X509Utils.GetPublicKeyParameter(certificate);

                ISignatureFactory signatureFactory =
                    new Asn1SignatureFactory(X509Utils.GetRSAHashAlgorithm(X509Defaults.HashAlgorithmName), signingKey, random);

                Asn1Set attributes = null;
                var     san        = X509Extensions.FindExtension <X509SubjectAltNameExtension>(certificate);
                X509SubjectAltNameExtension alternateName = new X509SubjectAltNameExtension(san, san.Critical);

                string applicationUri = null;
                domainNames = domainNames ?? new List <String>();
                if (alternateName != null)
                {
                    if (alternateName.Uris.Count > 0)
                    {
                        applicationUri = alternateName.Uris[0];
                    }
                    foreach (var name in alternateName.DomainNames)
                    {
                        if (!domainNames.Any(s => s.Equals(name, StringComparison.OrdinalIgnoreCase)))
                        {
                            domainNames.Add(name);
                        }
                    }
                    foreach (var ipAddress in alternateName.IPAddresses)
                    {
                        if (!domainNames.Any(s => s.Equals(ipAddress, StringComparison.OrdinalIgnoreCase)))
                        {
                            domainNames.Add(ipAddress);
                        }
                    }
                }

                // build CSR extensions
                var generalNames = new List <GeneralName>();

                if (applicationUri != null)
                {
                    generalNames.Add(new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri));
                }

                if (domainNames.Count > 0)
                {
                    generalNames.AddRange(BouncyCastle.X509Extensions.CreateSubjectAlternateNameDomains(domainNames));
                }

                if (generalNames.Count > 0)
                {
                    IList oids   = new ArrayList();
                    IList values = new ArrayList();
                    oids.Add(Org.BouncyCastle.Asn1.X509.X509Extensions.SubjectAlternativeName);
                    values.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false,
                                                                            new DerOctetString(new GeneralNames(generalNames.ToArray()).GetDerEncoded())));
                    var attribute = new Org.BouncyCastle.Asn1.Pkcs.AttributePkcs(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                                                                 new DerSet(new Org.BouncyCastle.Asn1.X509.X509Extensions(oids, values)));
                    attributes = new DerSet(attribute);
                }

                var pkcs10CertificationRequest = new Pkcs10CertificationRequest(
                    signatureFactory,
                    new CertificateFactoryX509Name(true, certificate.Subject),
                    publicKey,
                    attributes);

                return(pkcs10CertificationRequest.GetEncoded());
            }
        }
        private bool saveAs(bool Signed)
        {
            //SaveFileDialog dialog;

            mSubjectItemsOIDs.Add(X509Name.C);
            mSubjectItemsOIDs.Add(X509Name.OU);
            mSubjectItemsOIDs.Add(X509Name.CN);
            mSubjectItemsOIDs.Add(X509Name.TelephoneNumber);

            mSubjectItems.Add(CountryCodeTB.Text.Trim());
            mSubjectItems.Add(OrganizationalUnitTB.Text.Trim());
            mSubjectItems.Add(CommonNameTB.Text.Trim());
            mSubjectItems.Add(PhoneNumberTB.Text.Trim());

            mExtItemsOIDs.Add(X509Extensions.SubjectAlternativeName);
            mExtItems.Add(new X509Extension(false,
                                            new DerOctetString(new GeneralNames(new GeneralName(GeneralName.Rfc822Name, EmailTB.Text)))));


            string mKeyUsageDescription = "digitalSignature, nonRepudiation";

            int key_usage_bit_map = 0;

            key_usage_bit_map |= KeyUsage.DigitalSignature;
            key_usage_bit_map |= KeyUsage.NonRepudiation;

            KeyUsage mKeyUsage = new KeyUsage(key_usage_bit_map);

            mExtItemsOIDs.Add(X509Extensions.KeyUsage);
            mExtItems.Add(new X509Extension(true, new DerOctetString(mKeyUsage)));

            try
            {
                /* dialog = new SaveFileDialog();
                *  dialog.Filter = "CSR files (*.pem)|*.pem|All files (*.*)|*.*";
                *  dialog.RestoreDirectory = true;*/

                //if (dialog.ShowDialog() == DialogResult.OK)
                //{
                X509Name subject            = new X509Name(mSubjectItemsOIDs, mSubjectItems);
                string   signatureAlgorithm = "SHA256withECDSA";

                DerSet attributes = new DerSet();
                if (mExtItemsOIDs.Count > 0)
                {
                    attributes.AddObject(new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(
                                                               new X509Extensions(mExtItemsOIDs, mExtItems)))); // mExtItemsOIDs.Zip(mExtItems, (k, v) => new { Key = k, Value = v })
                                                                                                                //              .ToDictionary(x => x.Key, x => x.Value)
                }

                AsymmetricKeyParameter local_pub_key;

                if (Signed)
                {
                    local_pub_key = mPublicKey;
                }
                else
                {
                    local_pub_key = new RsaKeyParameters(false, BigInteger.One, BigInteger.One); // DUMMY RSA public key - for templates
                }
                Pkcs10CertificationRequestDelaySigned csr_ds =
                    new Pkcs10CertificationRequestDelaySigned(signatureAlgorithm, subject, local_pub_key, attributes);

                byte[] dataToSign = csr_ds.GetDataToSign();
                byte[] toSave;
                string header_footer;

                if (Signed)
                {
                    byte[] SignedData = uFRSigner(dataToSign);
                    // Rest of the input parameters needed (here accessible directly from UI):
                    //      - digest_alg, signature_cipher, card_key_index
                    csr_ds.SignRequest(SignedData);

                    toSave        = csr_ds.GetDerEncoded();
                    header_footer = "CERTIFICATE REQUEST";
                }
                else
                {
                    toSave        = dataToSign;
                    header_footer = "TBS CERTIFICATE REQUEST";
                }

                var file_extension = Path.GetExtension("CSR.pem");
                if (file_extension.Equals(".pem"))
                {
                    //var textWriter = new StreamWriter(dialog.FileName);
                    var textWriter = new StreamWriter("CSR.pem");

                    textWriter.Write(der2pem(toSave, header_footer));
                    textWriter.Flush();
                    textWriter.Close();
                }

                /* else
                 * {
                 *   using (var fs = new FileStream(dialog.FileName, FileMode.Create, FileAccess.Write))
                 *   {
                 *       fs.Write(toSave, 0, toSave.Length);
                 *       fs.Flush();
                 *       fs.Close();
                 *   }
                 * }*/
                // }
                //else
                //return false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            return(true);
        }
Example #9
0
		private ITestResult EnvelopedTest()
		{
			try
			{
				// Key trans
				ContentInfo info = ContentInfo.GetInstance(
					Asn1Object.FromByteArray(envDataKeyTrns));
				EnvelopedData envData = EnvelopedData.GetInstance(info.Content);
				Asn1Set s = envData.RecipientInfos;

				if (s.Count != 1)
				{
					return new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong number of recipients");
				}

				RecipientInfo recip = RecipientInfo.GetInstance(s[0]);

				if (recip.Info is KeyTransRecipientInfo)
				{
					KeyTransRecipientInfo inf = KeyTransRecipientInfo.GetInstance(recip.Info);

					inf = new KeyTransRecipientInfo(inf.RecipientIdentifier, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);

					s = new DerSet(new RecipientInfo(inf));
				}
				else
				{
					return new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped, wrong recipient type");
				}

				envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
				info = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);

				if (!Arrays.AreEqual(info.GetEncoded(), envDataKeyTrns))
				{
					return new SimpleTestResult(false, Name + ": CMS KeyTrans enveloped failed to re-encode");
				}


				// KEK
				info = ContentInfo.GetInstance(
					Asn1Object.FromByteArray(envDataKEK));
				envData = EnvelopedData.GetInstance(info.Content);
				s = envData.RecipientInfos;

				if (s.Count != 1)
				{
					return new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong number of recipients");
				}

				recip = RecipientInfo.GetInstance(s[0]);

				if (recip.Info is KekRecipientInfo)
				{
					KekRecipientInfo inf = KekRecipientInfo.GetInstance(recip.Info);

					inf = new KekRecipientInfo(inf.KekID, inf.KeyEncryptionAlgorithm, inf.EncryptedKey);

					s = new DerSet(new RecipientInfo(inf));
				}
				else
				{
					return new SimpleTestResult(false, Name + ": CMS KEK enveloped, wrong recipient type");
				}

				envData = new EnvelopedData(envData.OriginatorInfo, s, envData.EncryptedContentInfo, envData.UnprotectedAttrs);
				info = new ContentInfo(CmsObjectIdentifiers.EnvelopedData, envData);

				if (!Arrays.AreEqual(info.GetEncoded(), envDataKEK))
				{
					return new SimpleTestResult(false, Name + ": CMS KEK enveloped failed to re-encode");
				}

				// Nested NDEF problem
				Asn1StreamParser asn1In = new Asn1StreamParser(new MemoryStream(envDataNestedNDEF, false));
				ContentInfoParser ci = new ContentInfoParser((Asn1SequenceParser)asn1In.ReadObject());
				EnvelopedDataParser ed = new EnvelopedDataParser((Asn1SequenceParser)ci
					.GetContent(Asn1Tags.Sequence));
				Touch(ed.Version);
				ed.GetOriginatorInfo();
				ed.GetRecipientInfos().ToAsn1Object();
				EncryptedContentInfoParser eci = ed.GetEncryptedContentInfo();
				Touch(eci.ContentType);
				Touch(eci.ContentEncryptionAlgorithm);

				Stream dataIn = ((Asn1OctetStringParser)eci.GetEncryptedContent(Asn1Tags.OctetString))
					.GetOctetStream();
				Streams.Drain(dataIn);
				dataIn.Close();

				// Test data doesn't have unprotected attrs, bug was being thrown by this call
				Asn1SetParser upa = ed.GetUnprotectedAttrs();
				if (upa != null)
				{
					upa.ToAsn1Object();
				}

				return new SimpleTestResult(true, Name + ": Okay");
			}
			catch (Exception e)
			{
				return new SimpleTestResult(false, Name + ": CMS enveloped failed - " + e.ToString(), e);
			}
		}
        /// <summary>
        /// Create a CSR and submit it to the Acme server for signing. Returns the certificate chain.
        /// </summary>
        /// <param name="domains">The list of domains that this certificate will be for. The first domain listed will be the CommonName.</param>
        /// <param name="keyPair">The RSA key pair for signing the certificate request, this is the key that will be used in conjunction with the certificate.</param>
        /// <returns>A tuple whose first value is the private key data and whose second value is a list of certificates. Everything is encoded in DER format, the first certificate is the signed certificate.</returns>
        public Tuple <byte[], List <byte[]> > GetCertificate(ICollection <string> domains)
        {
            //
            // Generate a new key for the certificate.
            //
            var generator = new RsaKeyPairGenerator();

            generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            var keyPair = generator.GenerateKeyPair();
            var sig     = new Asn1SignatureFactory("SHA256WITHRSA", keyPair.Private);

            var commonName = new X509Name(new DerObjectIdentifier[] { X509Name.CN }, new string[] { domains.First() });

            //
            // Generate the list of subject alternative names.
            //
            List <GeneralName> names = new List <GeneralName>();

            foreach (var domain in domains)
            {
                names.Add(new GeneralName(GeneralName.DnsName, domain));
            }
            var sanOctect    = new DerOctetString(new GeneralNames(names.ToArray()));
            var sanSequence  = new DerSequence(X509Extensions.SubjectAlternativeName, sanOctect);
            var extensionSet = new DerSet(new DerSequence(sanSequence));
            var attributes   = new DerSet(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, extensionSet));

            //
            // Generate the CSR from all the data.
            //
            var csr = new Pkcs10CertificationRequest(sig, commonName, keyPair.Public, attributes, keyPair.Private);

            var payload = new
            {
                resource = "new-cert",
                csr      = UrlBase64Encode(csr.GetDerEncoded())
            };

            var certificates = new List <X509Certificate>();
            var certParser   = new X509CertificateParser();

            byte[] certData;

            //
            // Send the request and fetch the certificate data.
            //
            certData = SendMessage <byte[]>(Directory.NewCert, payload, GetNonce(), out WebHeaderCollection headers);
            certificates.Add(certParser.ReadCertificate(certData));

            //
            // Fetch all the certificates in the chain.
            //
            foreach (var link in headers.GetValues("Link"))
            {
                var match = System.Text.RegularExpressions.Regex.Match(link, "\\<(.*)\\>;rel=\"(.*)\"");
                if (match.Success && match.Groups[2].Value == "up")
                {
                    certData = GetRequest <byte[]>(match.Groups[1].Value);
                    certificates.Add(certParser.ReadCertificate(certData));
                }
            }

            var privateKeyData  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private).ToAsn1Object().GetDerEncoded();
            var certificateData = certificates.Select(c => c.GetEncoded()).ToList();

            return(new Tuple <byte[], List <byte[]> >(privateKeyData, certificateData));
        }
Example #11
0
        protected Stream Open(
            Stream outStream,
            string encryptionOid,
            KeyParameter encKey,
            Asn1Encodable asn1Params,
            Asn1EncodableVector recipientInfos)
        {
            Asn1Object        asn1Object;
            ICipherParameters cipherParameters;

            if (asn1Params != null)
            {
                asn1Object       = asn1Params.ToAsn1Object();
                cipherParameters = ParameterUtilities.GetCipherParameters(
                    encryptionOid, encKey, asn1Object);
            }
            else
            {
                asn1Object       = DerNull.Instance;
                cipherParameters = encKey;
            }


            try
            {
                AlgorithmIdentifier encAlgId = new AlgorithmIdentifier(
                    new DerObjectIdentifier(encryptionOid),
                    asn1Object);

                //
                // ContentInfo
                //
                BerSequenceGenerator cGen = new BerSequenceGenerator(outStream);

                cGen.AddObject(CmsObjectIdentifiers.EnvelopedData);

                //
                // Encrypted Data
                //
                BerSequenceGenerator envGen = new BerSequenceGenerator(
                    cGen.GetRawOutputStream(), 0, true);

                envGen.AddObject(this.Version);

                DerSet derSet = _berEncodeRecipientSet
                                        ?       new BerSet(recipientInfos)
                                        :       new DerSet(recipientInfos);

                byte[] derSetEncoding = derSet.GetEncoded();

                envGen.GetRawOutputStream().Write(derSetEncoding, 0, derSetEncoding.Length);

                IBufferedCipher cipher = CipherUtilities.GetCipher(encryptionOid);

                cipher.Init(true, cipherParameters);

                BerSequenceGenerator eiGen = new BerSequenceGenerator(
                    envGen.GetRawOutputStream());

                eiGen.AddObject(PkcsObjectIdentifiers.Data);

                byte[] tmp = encAlgId.GetEncoded();
                eiGen.GetRawOutputStream().Write(tmp, 0, tmp.Length);

                BerOctetStringGenerator octGen = new BerOctetStringGenerator(
                    eiGen.GetRawOutputStream(), 0, false);

                Stream octetOutputStream = _bufferSize != 0
                                        ?       octGen.GetOctetOutputStream(new byte[_bufferSize])
                                        :       octGen.GetOctetOutputStream();

                CipherStream cOut = new CipherStream(octetOutputStream, null, cipher);

                return(new CmsEnvelopedDataOutputStream(cOut, cGen, envGen, eiGen));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (IOException e)
            {
                throw new CmsException("exception decoding algorithm parameters.", e);
            }
        }
Example #12
0
        protected override void CompleteWizard()
        {
            // Generate the CSR
            X509Name subjectName;

            try
            {
                subjectName = new X509Name(string.Format("C={0},ST={1},L={2},O={3},OU={4},CN={5}",
                                                         _wizardData.Country,
                                                         _wizardData.State,
                                                         _wizardData.City,
                                                         _wizardData.Organization,
                                                         _wizardData.Unit,
                                                         _wizardData.CommonName));
            }
            catch (ArgumentException ex)
            {
                ShowError(ex, Text, false);
                return;
            }

            // Generate the private/public keypair
            RsaKeyPairGenerator      kpgen           = new RsaKeyPairGenerator();
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();

            kpgen.Init(new KeyGenerationParameters(new SecureRandom(randomGenerator), _wizardData.Length));
            AsymmetricCipherKeyPair keyPair = kpgen.GenerateKeyPair();
            // Generate the CSR

            Asn1Set attributes = new DerSet(
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.3"),
                    new DerSet(new DerIA5String(Environment.OSVersion.Version.ToString()))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.21.20"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(5),
                            new DerUtf8String(Environment.MachineName),
                            new DerUtf8String(Environment.UserName),
                            new DerUtf8String("JexusManager.exe")))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.2"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(1),
                            new DerBmpString("Microsoft RSA SChannel Cryptographic Provider"),
                            new DerBitString(new byte[0])))),
                new DerSequence(
                    new DerObjectIdentifier("1.2.840.113549.1.9.14"),
                    new DerSet(
                        new DerSequence(
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.15"),
                                new DerBoolean(new byte[] { 0x01 }),
                                new DerOctetString(new byte[] { 0x03, 0x02, 0x04, 0xF0 })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.37"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x0a, 0x06, 0x08,
                0x2b, 0x06, 0x01, 0x05,
                0x05, 0x07, 0x03, 0x01
            })),
                            new DerSequence(
                                new DerObjectIdentifier("1.2.840.113549.1.9.15"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x69, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x02, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x04, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0b,
                0x06, 0x09, 0x60, 0x86,
                0x48, 0x01, 0x65, 0x03,
                0x04, 0x01, 0x2a, 0x30,
                0x0b, 0x06, 0x09, 0x60,
                0x86, 0x48, 0x01, 0x65,
                0x03, 0x04, 0x01, 0x2d,
                0x30, 0x0b, 0x06, 0x09,
                0x60, 0x86, 0x48, 0x01,
                0x65, 0x03, 0x04, 0x01,
                0x02, 0x30, 0x0b, 0x06,
                0x09, 0x60, 0x86, 0x48,
                0x01, 0x65, 0x03, 0x04,
                0x01, 0x05, 0x30, 0x07,
                0x06, 0x05, 0x2b, 0x0e,
                0x03, 0x02, 0x07, 0x30,
                0x0a, 0x06, 0x08, 0x2a,
                0x86, 0x48, 0x86, 0xf7,
                0x0d, 0x03, 0x07
            })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.14"),
                                new DerOctetString(new byte[]
            {
                0x04, 0x14, 0xaa, 0x25,
                0xd9, 0xa2, 0x39, 0x7e,
                0x49, 0xd2, 0x94, 0x85,
                0x7e, 0x82, 0xa8, 0x8f,
                0x3b, 0x20, 0xf1, 0x4e, 0x65, 0xe5
            }))))));

            var signing = new Asn1SignatureFactory("SHA256withRSA", keyPair.Private);
            Pkcs10CertificationRequest kpGen = new Pkcs10CertificationRequest(signing, subjectName, keyPair.Public, attributes);

            using (var stream = new StreamWriter(_wizardData.FileName))
            {
                stream.WriteLine(_wizardData.UseIisStyle ? "-----BEGIN NEW CERTIFICATE REQUEST-----" : "-----BEGIN CERTIFICATE REQUEST-----");
                stream.WriteLine(Convert.ToBase64String(kpGen.GetDerEncoded(), Base64FormattingOptions.InsertLineBreaks));
                stream.WriteLine(_wizardData.UseIisStyle ? "-----END NEW CERTIFICATE REQUEST-----" : "-----END CERTIFICATE REQUEST-----");
            }

            var        key = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
            PrivateKey pvk = new PrivateKey();

            pvk.RSA = new RSACryptoServiceProvider();
            pvk.RSA.ImportParameters(key);

            var file   = DialogHelper.GetPrivateKeyFile(subjectName.ToString());
            var folder = Path.GetDirectoryName(file);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            pvk.Save(file);
        }
Example #13
0
        public override Csr GenerateCsr(CsrParams csrParams, PrivateKey pk, Crt.MessageDigest md)
        {
            // Useful examples:
            //    http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation
            //    https://gist.github.com/Venomed/5337717aadfb61b09e58
            //    http://codereview.stackexchange.com/questions/84752/net-bouncycastle-csr-and-private-key-generation

            var csrDetails = csrParams.Details;
            var mdVal      = Enum.GetName(typeof(Crt.MessageDigest), md);

            var attrs = new Dictionary <DerObjectIdentifier, string>();

            if (!string.IsNullOrEmpty(csrDetails.CommonName /**/))
            {
                attrs.Add(X509Name.CN, csrDetails.CommonName);                                                                  // CN;
            }
            if (!string.IsNullOrEmpty(csrDetails.Country /**/))
            {
                attrs.Add(X509Name.C, csrDetails.Country);                                                                      // C;
            }
            if (!string.IsNullOrEmpty(csrDetails.StateOrProvince /**/))
            {
                attrs.Add(X509Name.ST, csrDetails.StateOrProvince);                                                             // ST;
            }
            if (!string.IsNullOrEmpty(csrDetails.Locality /**/))
            {
                attrs.Add(X509Name.L, csrDetails.Locality);                                                                     // L;
            }
            if (!string.IsNullOrEmpty(csrDetails.Organization /**/))
            {
                attrs.Add(X509Name.O, csrDetails.Organization);                                                                 // O;
            }
            if (!string.IsNullOrEmpty(csrDetails.OrganizationUnit /**/))
            {
                attrs.Add(X509Name.OU, csrDetails.OrganizationUnit);                                                            // OU;
            }
            if (!string.IsNullOrEmpty(csrDetails.Surname /**/))
            {
                attrs.Add(X509Name.Surname, csrDetails.Surname);                                                                // S;
            }
            if (!string.IsNullOrEmpty(csrDetails.GivenName /**/))
            {
                attrs.Add(X509Name.GivenName, csrDetails.GivenName);                                                            // G;
            }
            if (!string.IsNullOrEmpty(csrDetails.Initials /**/))
            {
                attrs.Add(X509Name.Initials, csrDetails.Initials);                                                              // I;
            }
            if (!string.IsNullOrEmpty(csrDetails.Title /**/))
            {
                attrs.Add(X509Name.T, csrDetails.Title);                                                                                      // T;
            }
            if (!string.IsNullOrEmpty(csrDetails.SerialNumber /**/))
            {
                attrs.Add(X509Name.SerialNumber, csrDetails.SerialNumber);                                                                    // SN;
            }
            if (!string.IsNullOrEmpty(csrDetails.UniqueIdentifier /**/))
            {
                attrs.Add(X509Name.UniqueIdentifier, csrDetails.UniqueIdentifier);                                                            // UID;
            }
            var subj = new X509Name(attrs.Keys.ToList(), attrs.Values.ToList());

            var rsaPk = pk as RsaPrivateKey;

            if (rsaPk != null)
            {
                using (var tr = new StringReader(rsaPk.Pem))
                {
                    var pr   = new PemReader(tr);
                    var pem  = pr.ReadObject();
                    var ackp = pem as AsymmetricCipherKeyPair;

                    if (ackp != null)
                    {
                        var    sigAlg   = $"{mdVal}withRSA";
                        DerSet csrAttrs = null;

                        if (csrDetails.AlternativeNames != null)
                        {
                            var gnames = new List <GeneralName>();

                            // Start off with the common name as the first alternative name
                            gnames.Add(new GeneralName(GeneralName.DnsName, csrDetails.CommonName));
                            // Combine with all subsequent alt names
                            foreach (var n in csrDetails.AlternativeNames)
                            {
                                gnames.Add(new GeneralName(GeneralName.DnsName, n));
                            }

                            var altNames = new GeneralNames(gnames.ToArray());
#pragma warning disable CS0612 // Type or member is obsolete
                            var x509Ext = new X509Extensions(new Hashtable
                            {
                                [X509Extensions.SubjectAlternativeName] = new X509Extension(false, new DerOctetString(altNames))
                            });
#pragma warning restore CS0612 // Type or member is obsolete

                            csrAttrs = new DerSet(new Org.BouncyCastle.Asn1.Cms.Attribute(
                                                      PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                                      new DerSet(x509Ext)));
                        }

#pragma warning disable CS0618 // Type or member is obsolete
                        var csr = new Pkcs10CertificationRequest(sigAlg,
                                                                 subj, ackp.Public, csrAttrs, ackp.Private);
#pragma warning restore CS0618 // Type or member is obsolete

                        var csrPem = ToCsrPem(csr);
                        return(new Csr(csrPem));
                    }
                }
            }

            throw new NotSupportedException("unsupported private key type");
        }
Example #14
0
        private async Task ProcessCsrGeneration(ThingToGenerate toGenerate)
        {
            SetStatusAndProgress("Generating...");
            var(keyGenerator, signerFactoryFactory) = await CsrGetKeyGeneratorAsync();

            var lines = txtCsrDomains.Text
                        .Split('\r')
                        .Select(x => x.Trim())
                        .Where(x => !string.IsNullOrEmpty(x))
                        .Select(x => x.Split(';', ',').Select(y => y.Trim()).Where(y => !string.IsNullOrEmpty(y)).ToArray())
                        .Where(x => x.Length >= 1)
                        .ToArray();

            string dnO     = txtCsrSubjO.Text.Trim();
            string dnOU    = txtCsrSubjOU.Text.Trim();
            string dnC     = txtCsrSubjC.Text.Trim();
            string dnST    = txtCsrSubjST.Text.Trim();
            string dnL     = txtCsrSubjL.Text.Trim();
            string dnEmail = txtCsrSubjEmail.Text.Trim();

            var dnOrdering = new List <DerObjectIdentifier>();
            var dnValues   = new List <string>();

            dnOrdering.Add(X509Name.CN);
            dnValues.Add("<placeholder>");
            if (!string.IsNullOrEmpty(dnO))
            {
                dnOrdering.Add(X509Name.O); dnValues.Add(dnO);
            }
            if (!string.IsNullOrEmpty(dnOU))
            {
                dnOrdering.Add(X509Name.OU); dnValues.Add(dnOU);
            }
            if (!string.IsNullOrEmpty(dnC))
            {
                dnOrdering.Add(X509Name.C); dnValues.Add(dnC);
            }
            if (!string.IsNullOrEmpty(dnST))
            {
                dnOrdering.Add(X509Name.ST); dnValues.Add(dnST);
            }
            if (!string.IsNullOrEmpty(dnL))
            {
                dnOrdering.Add(X509Name.L); dnValues.Add(dnL);
            }
            if (!string.IsNullOrEmpty(dnEmail))
            {
                dnOrdering.Add(X509Name.EmailAddress); dnValues.Add(dnEmail);
            }

            int cnt = 0;

            foreach (var line in lines)
            {
                SetStatusAndProgress("Generating...", (double)cnt++ / lines.Length);

                string   cn       = line[0];
                string[] altnames = line;

                var dnValuesThese = dnValues.ToArray();
                dnValuesThese[0] = cn;

                var keyPath = Path.Combine(CurrentWorkingDirectory, FixFilename($"{cn}.key"));
                AsymmetricCipherKeyPair key = null;
                if (rdCsrUseExistingKey.Checked && File.Exists(keyPath))
                {
                    try
                    {
                        PemReader pr = new PemReader(File.OpenText(keyPath));
                        key = pr.ReadObject() as AsymmetricCipherKeyPair;
                    }
                    catch { key = null; }
                }

                if (key == null)
                {
                    key = await Task.Factory.StartNew(() => keyGenerator.GenerateKeyPair());

                    WriteToPemFile(keyPath, key);
                }

                X509Name subject = new X509Name(dnOrdering, dnValuesThese);


                if ((toGenerate | ThingToGenerate.Csr) == ThingToGenerate.Csr)
                {
                    X509ExtensionsGenerator extGenerator = GetExtensionsGenerator(altnames);

                    var     exts  = extGenerator.Generate();
                    Asn1Set attrs = new DerSet(new DerSequence(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(exts)));

                    var req = new Pkcs10CertificationRequest(
                        signerFactoryFactory(key.Private),
                        subject,
                        key.Public,
                        attrs,
                        key.Private);

                    if (!req.Verify())
                    {
                        throw new InvalidOperationException("Generated an invalid CSR.");
                    }
                    WriteToPemFile(Path.Combine(CurrentWorkingDirectory, FixFilename($"{cn}.csr")), req);
                }
                if ((toGenerate | ThingToGenerate.SelfSignedCert) == ThingToGenerate.SelfSignedCert)
                {
                    SecureRandom sr = new SecureRandom();
                    X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();

                    certgen.SetSerialNumber(new BigInteger(128, sr));
                    certgen.SetIssuerDN(subject);
                    certgen.SetSubjectDN(subject);
                    certgen.SetNotBefore(DateTime.Today.Subtract(new TimeSpan(1, 0, 0, 0)));
                    certgen.SetNotAfter(DateTime.Today.AddYears(30));
                    certgen.SetPublicKey(key.Public);

                    foreach (var ext in GetExtensions(altnames))
                    {
                        certgen.AddExtension(ext.oid, ext.isCritical, ext.section);
                    }

                    ISignatureFactory signer;
                    if (key.Private is ECPrivateKeyParameters)
                    {
                        signer = new Asn1SignatureFactory("SHA256WITHECDSA", key.Private, sr);
                    }
                    else
                    {
                        signer = new Asn1SignatureFactory("SHA256WITHRSA", key.Private, sr);
                    }

                    var cert = certgen.Generate(signer);
                    cert.CheckValidity();
                    cert.Verify(key.Public);
                    WriteToPemFile(Path.Combine(CurrentWorkingDirectory, FixFilename($"{cn}.cer")), cert);
                }
            }

            SetStatusAndProgress("Generating CSRs", 1);
        }
Example #15
0
        public void Get_ContainerNames()
        {
            uint          pcbData = 0;
            uint          dwFlags = CRYPT_FIRST;
            IntPtr        hProv   = IntPtr.Zero;
            bool          gotcsp  = CryptAcquireContext(ref hProv, null, "Crypto-Pro GOST R 34.10-2001 Cryptographic Service Provider", PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CSPKEYTYPE);
            StringBuilder sb      = null;

            CryptGetProvParam(hProv, PP_ENUMCONTAINERS, sb, ref pcbData, dwFlags);
            sb      = new StringBuilder((int)(2 * pcbData));
            dwFlags = CRYPT_FIRST;

            DateTime dt      = DateTime.Now;
            string   curDate = dt.ToShortDateString();

            X509Certificate2 CurrentCert;

            String[] CertStorage;

            while (CryptGetProvParam(hProv, PP_ENUMCONTAINERS, sb, ref pcbData, dwFlags))
            {
                dwFlags = 0;
                cspParameters.KeyContainerName = sb.ToString();
                cspParameters.Flags            = CspProviderFlags.NoPrompt;

                try
                {
                    CryptoServiceProvider2001 = new Gost3410CryptoServiceProvider(cspParameters);
                    CurrentCert = CryptoServiceProvider2001.ContainerCertificate;
                    CertStorage = CryptoServiceProvider2001.CspKeyContainerInfo.UniqueKeyContainerName.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                }
                catch (Exception Ex)
                {
                    if (Environment.OSVersion.Version.Major < 6)
                    {
                        return;
                    }

                    if (Convert.ToInt32(CSPVersion()[0].ToString()) < 4)
                    {
                        return;
                    }

                    CryptoServiceProvider2012 = new Gost3410_2012_256CryptoServiceProvider(cspParameters);
                    CurrentCert = CryptoServiceProvider2012.ContainerCertificate;
                    CertStorage = CryptoServiceProvider2012.CspKeyContainerInfo.UniqueKeyContainerName.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                }

                try
                {
                    if (CurrentCert != null)
                    {
                        Invoke(new Action(() => label1.Text = "Поиск в контейнере: " + CertStorage[1]));

                        if (CurrentCert.NotAfter < DateTime.Now)
                        {
                            Invoke(new Action(() => label1.Text = "Истек срок действия: " + CurrentCert.SerialNumber + " (" + CurrentCert.NotAfter + ")"));
                        }
                        else
                        {
                            string GetNameInfo = CurrentCert.GetNameInfo(X509NameType.SimpleName, true);

                            if (GetNameInfo.Contains("Link-Service") || GetNameInfo.Contains("Линк-сервис") || CertStorage[0].Contains("LINK"))
                            {
                                X509Store CertificationStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                                CertificationStore.Open(OpenFlags.ReadWrite);

                                X509CertificateParser parser = new X509CertificateParser();

                                byte[] rawdata = CurrentCert.RawData;

                                Org.BouncyCastle.X509.X509Certificate cert = parser.ReadCertificate(rawdata);
                                DerSequence subject = cert.SubjectDN.ToAsn1Object() as DerSequence;

                                foreach (Asn1Encodable setItem in subject)
                                {
                                    DerSet subSet = setItem as DerSet;
                                    if (subSet == null)
                                    {
                                        continue;
                                    }
                                    DerSequence subSeq = subSet[0] as DerSequence;

                                    foreach (Asn1Encodable subSeqItem in subSeq)
                                    {
                                        DerObjectIdentifier oid = subSeqItem as DerObjectIdentifier;
                                        if (oid == null)
                                        {
                                            continue;
                                        }
                                        string value = subSeq[1].ToString();
                                        if (oid.Id.Equals("2.5.4.3"))
                                        {
                                            CN = value;
                                        }
                                    }
                                }

                                if (!CertStorage[0].Contains("ePass")) // ePass break; Equals
                                {
                                    if (CertStorage[0] != "REGISTRY")
                                    {
                                        InstallCertificate(CurrentCert);
                                    }
                                    else
                                    {
                                        InstallCertificate(CurrentCert);
                                    }
                                }

                                CertificationStore.Close();


                                // CryptoServiceProvider.Clear();
                            }
                            else
                            {
                                Invoke(new Action(() => label1.Text = "Сертификат: " + CurrentCert.SerialNumber + " (недоступен)"));
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //LogWrite(ex);
                }
            }

            if (hProv != IntPtr.Zero)
            {
                CryptReleaseContext(hProv, 0);
            }
        }
Example #16
0
		public override void PerformTest()
		{
			Asn1EncodableVector v = new Asn1EncodableVector();
			byte[] data = new byte[10];

			v.Add(new DerOctetString(data));
			v.Add(new DerBitString(data));
			v.Add(new DerInteger(100));
			v.Add(DerBoolean.True);

			checkSortedSet(0, new DerSet(v));

			v = new Asn1EncodableVector();
			v.Add(new DerInteger(100));
			v.Add(DerBoolean.True);
			v.Add(new DerOctetString(data));
			v.Add(new DerBitString(data));

			checkSortedSet(1, new DerSet(v));

			v = new Asn1EncodableVector();
			v.Add(DerBoolean.True);
			v.Add(new DerOctetString(data));
			v.Add(new DerBitString(data));
			v.Add(new DerInteger(100));


			checkSortedSet(2, new DerSet(v));

			v = new Asn1EncodableVector();
			v.Add(new DerBitString(data));
			v.Add(new DerOctetString(data));
			v.Add(new DerInteger(100));
			v.Add(DerBoolean.True);

			checkSortedSet(3, new DerSet(v));

			v = new Asn1EncodableVector();
			v.Add(new DerOctetString(data));
			v.Add(new DerBitString(data));
			v.Add(new DerInteger(100));
			v.Add(DerBoolean.True);

			Asn1Set s = new BerSet(v);

			if (!(s[0] is DerOctetString))
			{
				Fail("BER set sort order changed.");
			}

			// create an implicitly tagged "set" without sorting
			Asn1TaggedObject tag = new DerTaggedObject(false, 1, new DerSequence(v));
			s = Asn1Set.GetInstance(tag, false);

			if (s[0] is DerBoolean)
			{
				Fail("sorted when shouldn't be.");
			}

			// equality test
			v = new Asn1EncodableVector();

			v.Add(DerBoolean.True);
			v.Add(DerBoolean.True);
			v.Add(DerBoolean.True);

			s = new DerSet(v);
		}
        protected override void CompleteWizard()
        {
            X509Name subjectName = new X509Name(_existing.Subject);

            // Generate the private/public keypair
            var keyPair = DotNetUtilities.GetKeyPair(_existing.PrivateKey);

            // Generate the CSR
            Asn1Set attributes = new DerSet(
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.3"),
                    new DerSet(new DerIA5String(Environment.OSVersion.Version.ToString()))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.21.20"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(5),
                            new DerUtf8String(Environment.MachineName),
                            new DerUtf8String(Environment.UserName),
                            new DerUtf8String("JexusManager.exe")))),
                new DerSequence(
                    new DerObjectIdentifier("1.3.6.1.4.1.311.13.2.2"),
                    new DerSet(
                        new DerSequence(
                            new DerInteger(1),
                            new DerBmpString("Microsoft RSA SChannel Cryptographic Provider"),
                            new DerBitString(new byte[0])))),
                new DerSequence(
                    new DerObjectIdentifier("1.2.840.113549.1.9.14"),
                    new DerSet(
                        new DerSequence(
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.15"),
                                new DerBoolean(new byte[] { 0x01 }),
                                new DerOctetString(new byte[] { 0x03, 0x02, 0x04, 0xF0 })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.37"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x0a, 0x06, 0x08,
                0x2b, 0x06, 0x01, 0x05,
                0x05, 0x07, 0x03, 0x01
            })),
                            new DerSequence(
                                new DerObjectIdentifier("1.2.840.113549.1.9.15"),
                                new DerOctetString(new byte[]
            {
                0x30, 0x69, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x02, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0e,
                0x06, 0x08, 0x2a, 0x86,
                0x48, 0x86, 0xf7, 0x0d,
                0x03, 0x04, 0x02, 0x02,
                0x00, 0x80, 0x30, 0x0b,
                0x06, 0x09, 0x60, 0x86,
                0x48, 0x01, 0x65, 0x03,
                0x04, 0x01, 0x2a, 0x30,
                0x0b, 0x06, 0x09, 0x60,
                0x86, 0x48, 0x01, 0x65,
                0x03, 0x04, 0x01, 0x2d,
                0x30, 0x0b, 0x06, 0x09,
                0x60, 0x86, 0x48, 0x01,
                0x65, 0x03, 0x04, 0x01,
                0x02, 0x30, 0x0b, 0x06,
                0x09, 0x60, 0x86, 0x48,
                0x01, 0x65, 0x03, 0x04,
                0x01, 0x05, 0x30, 0x07,
                0x06, 0x05, 0x2b, 0x0e,
                0x03, 0x02, 0x07, 0x30,
                0x0a, 0x06, 0x08, 0x2a,
                0x86, 0x48, 0x86, 0xf7,
                0x0d, 0x03, 0x07
            })),
                            new DerSequence(
                                new DerObjectIdentifier("2.5.29.14"),
                                new DerOctetString(new byte[]
            {
                0x04, 0x14, 0xaa, 0x25,
                0xd9, 0xa2, 0x39, 0x7e,
                0x49, 0xd2, 0x94, 0x85,
                0x7e, 0x82, 0xa8, 0x8f,
                0x3b, 0x20, 0xf1, 0x4e, 0x65, 0xe5
            }))))));

            var signing = new Asn1SignatureFactory("SHA256withRSA", keyPair.Private);
            Pkcs10CertificationRequest kpGen = new Pkcs10CertificationRequest(signing, subjectName, keyPair.Public, attributes, keyPair.Private);

            using (var stream = new StreamWriter(_wizardData.FileName))
            {
                stream.WriteLine(_wizardData.UseIisStyle ? "-----BEGIN NEW CERTIFICATE REQUEST-----" : "-----BEGIN CERTIFICATE REQUEST-----");
                stream.WriteLine(Convert.ToBase64String(kpGen.GetDerEncoded(), Base64FormattingOptions.InsertLineBreaks));
                stream.WriteLine(_wizardData.UseIisStyle ? "-----END NEW CERTIFICATE REQUEST-----" : "-----END CERTIFICATE REQUEST-----");
            }

            var        key = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
            PrivateKey pvk = new PrivateKey();

            pvk.RSA = new RSACryptoServiceProvider();
            pvk.RSA.ImportParameters(key);

            var file   = DialogHelper.GetPrivateKeyFile(_existing.Subject);
            var folder = Path.GetDirectoryName(file);

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            pvk.Save(file);
        }
        private CmsSignedData GenerateTimestamp(
            TimeStampRequest request,
            BigInteger serialNumber,
            DateTime generalizedTime)
        {
            var messageImprint = new MessageImprint(
                new AlgorithmIdentifier(
                    new DerObjectIdentifier(request.MessageImprintAlgOid)), request.GetMessageImprintDigest());
            DerInteger nonce = request.Nonce == null ? null : new DerInteger(request.Nonce);

            var tstInfo = new TstInfo(
                new DerObjectIdentifier(_options.Policy.Value),
                messageImprint,
                new DerInteger(serialNumber),
                new DerGeneralizedTime(generalizedTime),
                _options.Accuracy,
                DerBoolean.False,
                nonce,
                tsa: null,
                extensions: null);

            var content          = new CmsProcessableByteArray(tstInfo.GetEncoded());
            var signedAttributes = new Asn1EncodableVector();
            var certificateBytes = new Lazy <byte[]>(() => Certificate.GetEncoded());

            if (_options.SigningCertificateUsage.HasFlag(SigningCertificateUsage.V1))
            {
                byte[] hash = _options.SigningCertificateV1Hash ?? DigestUtilities.CalculateDigest("SHA-1", certificateBytes.Value);
                var    signingCertificate = new SigningCertificate(new EssCertID(hash));
                var    attributeValue     = new DerSet(signingCertificate);
                var    attribute          = new BcAttribute(PkcsObjectIdentifiers.IdAASigningCertificate, attributeValue);

                signedAttributes.Add(attribute);
            }

            if (_options.SigningCertificateUsage.HasFlag(SigningCertificateUsage.V2))
            {
                byte[] hash = DigestUtilities.CalculateDigest("SHA-256", certificateBytes.Value);
                var    signingCertificateV2 = new SigningCertificateV2(new EssCertIDv2(hash));
                var    attributeValue       = new DerSet(signingCertificateV2);
                var    attribute            = new BcAttribute(PkcsObjectIdentifiers.IdAASigningCertificateV2, attributeValue);

                signedAttributes.Add(attribute);
            }

            var generator = new CmsSignedDataGenerator();

            if (_options.ReturnSigningCertificate)
            {
                var certificates = X509StoreFactory.Create(
                    "Certificate/Collection",
                    new X509CollectionStoreParameters(new[] { Certificate }));

                generator.AddCertificates(certificates);
            }

            generator.AddSigner(
                _keyPair.Private,
                Certificate,
                _options.SignatureHashAlgorithm.Value,
                new BcAttributeTable(signedAttributes),
                new BcAttributeTable(DerSet.Empty));

            CmsSignedData signedCms = generator.Generate(
                PkcsObjectIdentifiers.IdCTTstInfo.Id,
                content,
                encapsulate: true);

            return(signedCms);
        }
Example #19
0
        public static void AddCertInDir(string dir)
        {
            X509CertificateParser parser;
            x509Cert        certificate;
            X509Certificate cert;

            System.Security.Cryptography.X509Certificates.X509Certificate2 x509_2;

            foreach (string str in Directory.GetFiles(@dir, "*.cer", SearchOption.AllDirectories))
            {
                parser      = new X509CertificateParser();
                cert        = parser.ReadCertificate(File.ReadAllBytes(str));
                certificate = new x509Cert();
                x509_2      = new System.Security.Cryptography.X509Certificates.X509Certificate2();

                byte[] rawData = File.ReadAllBytes(str);
                x509_2.Import(rawData);

                // Разбор поля subject = SEQ of SET of SEQ of {OID/value}
                DerSequence subject = cert.SubjectDN.ToAsn1Object() as DerSequence;
                foreach (Asn1Encodable setItem in subject)
                {
                    DerSet subSet = setItem as DerSet;
                    if (subSet == null)
                    {
                        continue;
                    }

                    // Первый элемент множества SET - искомая последовательность SEQ of {OID/value}
                    DerSequence subSeq = subSet[0] as DerSequence;
                    foreach (Asn1Encodable subSeqItem in subSeq)
                    {
                        DerObjectIdentifier oid = subSeqItem as DerObjectIdentifier;

                        if (oid == null)
                        {
                            continue;
                        }

                        string value = subSeq[1].ToString();

                        if (oid.Id.Equals("2.5.4.3"))
                        {
                            certificate.certCn = value;
                        }
                        if (oid.Id.Equals("1.2.643.3.131.1.1"))
                        {
                            certificate.certInn = value;
                        }
                        if (oid.Id.Equals("2.5.4.4"))
                        {
                            certificate.certF = value;
                        }
                        if (oid.Id.Equals("2.5.4.42"))
                        {
                            certificate.certIo = value;
                        }
                        if (oid.Id.Equals("1.2.643.100.5"))
                        {
                            certificate.certOgrnIp = value;
                        }
                        if (oid.Id.Equals("1.2.643.100.1"))
                        {
                            certificate.certOgrn = value;
                        }
                        if (oid.Id.Equals("1.2.643.100.3"))
                        {
                            certificate.certSnils = value;
                        }

                        certificate.certThumb     = x509_2.Thumbprint;
                        certificate.certSerial    = x509_2.SerialNumber.ToUpper();
                        certificate.certNotBefore = cert.NotBefore.ToString("dd.MM.yyyy");
                        certificate.certNotAfter  = cert.NotAfter.ToString("dd.MM.yyyy");

                        //value.Distinct();
                        value = string.Empty;
                    }
                }

                AddToList(certificate);
            }
        }
Example #20
0
        /// <summary>
        /// Generates PKCS#7 signature of specified data
        /// </summary>
        /// <param name="data">Data to be signed</param>
        /// <param name="detached">Flag indicating whether detached signature should be produced</param>
        /// <param name="signingCertificate">Signing certificate</param>
        /// <param name="certPath">Certification path for signing certificate</param>
        /// <returns>DER encoded PKCS#7 signature of specified data</returns>
        public byte[] GenerateSignature(byte[] data, bool detached, BCX509.X509Certificate signingCertificate, ICollection <BCX509.X509Certificate> certPath)
        {
            if (this._disposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            string  hashOid       = HashAlgorithmUtils.GetHashOid(_hashAlgorihtm);
            IDigest hashGenerator = HashAlgorithmUtils.GetHashGenerator(_hashAlgorihtm);

            // Compute hash of input data
            byte[] dataHash = ComputeDigest(hashGenerator, data);

            // Construct SignerInfo.signedAttrs
            Asn1EncodableVector signedAttributesVector = new Asn1EncodableVector();

            // Add PKCS#9 contentType signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    attrType: new DerObjectIdentifier(OID.PKCS9AtContentType),
                    attrValues: new DerSet(new DerObjectIdentifier(OID.PKCS7IdData))));

            // Add PKCS#9 messageDigest signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    attrType: new DerObjectIdentifier(OID.PKCS9AtMessageDigest),
                    attrValues: new DerSet(new DerOctetString(dataHash))));

            // Add PKCS#9 signingTime signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    attrType: new DerObjectIdentifier(OID.PKCS9AtSigningTime),
                    attrValues: new DerSet(new Org.BouncyCastle.Asn1.Cms.Time(new DerUtcTime(DateTime.UtcNow)))));

            // Compute digest of SignerInfo.signedAttrs
            DerSet signedAttributes = new DerSet(signedAttributesVector);

            byte[] signedAttributesDigest = ComputeDigest(hashGenerator, signedAttributes.GetDerEncoded());

            // Sign digest of SignerInfo.signedAttrs with private key stored on PKCS#11 compatible device
            Asn1OctetString     digestSignature          = null;
            AlgorithmIdentifier digestSignatureAlgorithm = null;

            if (_signatureScheme == SignatureScheme.RSASSA_PKCS1_v1_5)
            {
                // Construct DigestInfo
                byte[] digestInfo = CreateDigestInfo(signedAttributesDigest, hashOid);

                // Sign DigestInfo with CKM_RSA_PKCS mechanism
                byte[] signature = null;

                using (Session session = _slot.OpenSession(SessionType.ReadOnly))
                    using (Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS))
                        signature = session.Sign(mechanism, _privateKeyHandle, digestInfo);

                // Construct SignerInfo.signature
                digestSignature = new DerOctetString(signature);

                // Construct SignerInfo.signatureAlgorithm
                digestSignatureAlgorithm = new AlgorithmIdentifier(
                    algorithm: new DerObjectIdentifier(OID.PKCS1RsaEncryption),
                    parameters: DerNull.Instance
                    );
            }
            else if (_signatureScheme == SignatureScheme.RSASSA_PSS)
            {
                // Construct parameters for CKM_RSA_PKCS_PSS mechanism
                CkRsaPkcsPssParams pssMechanismParams = CreateCkRsaPkcsPssParams(_hashAlgorihtm);

                // Sign digest with CKM_RSA_PKCS_PSS mechanism
                byte[] signature = null;

                using (Session session = _slot.OpenSession(SessionType.ReadOnly))
                    using (Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS_PSS, pssMechanismParams))
                        signature = session.Sign(mechanism, _privateKeyHandle, signedAttributesDigest);

                // Construct SignerInfo.signature
                digestSignature = new DerOctetString(signature);

                // Construct SignerInfo.signatureAlgorithm
                digestSignatureAlgorithm = new AlgorithmIdentifier(
                    algorithm: new DerObjectIdentifier(OID.PKCS1RsassaPss),
                    parameters: new Org.BouncyCastle.Asn1.Pkcs.RsassaPssParameters(
                        hashAlgorithm: new AlgorithmIdentifier(
                            algorithm: new DerObjectIdentifier(hashOid),
                            parameters: DerNull.Instance
                            ),
                        maskGenAlgorithm: new AlgorithmIdentifier(
                            algorithm: new DerObjectIdentifier(OID.PKCS1Mgf1),
                            parameters: new AlgorithmIdentifier(
                                algorithm: new DerObjectIdentifier(hashOid),
                                parameters: DerNull.Instance
                                )
                            ),
                        saltLength: new DerInteger(hashGenerator.GetDigestSize()),
                        trailerField: new DerInteger(1)
                        )
                    );
            }
            else
            {
                throw new NotSupportedException("Unsupported signature scheme");
            }

            // Construct SignerInfo
            SignerInfo signerInfo = new SignerInfo(
                sid: new SignerIdentifier(new IssuerAndSerialNumber(signingCertificate.IssuerDN, signingCertificate.SerialNumber)),
                digAlgorithm: new AlgorithmIdentifier(
                    algorithm: new DerObjectIdentifier(hashOid),
                    parameters: DerNull.Instance
                    ),
                authenticatedAttributes: signedAttributes,
                digEncryptionAlgorithm: digestSignatureAlgorithm,
                encryptedDigest: digestSignature,
                unauthenticatedAttributes: null
                );

            // Construct SignedData.digestAlgorithms
            Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();

            digestAlgorithmsVector.Add(
                new AlgorithmIdentifier(
                    algorithm: new DerObjectIdentifier(hashOid),
                    parameters: DerNull.Instance));

            // Construct SignedData.encapContentInfo
            ContentInfo encapContentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(OID.PKCS7IdData),
                content: (detached) ? null : new DerOctetString(data));

            // Construct SignedData.certificates
            Asn1EncodableVector certificatesVector = new Asn1EncodableVector();

            foreach (BCX509.X509Certificate cert in certPath)
            {
                certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
            }

            // Construct SignedData.signerInfos
            Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();

            signerInfosVector.Add(signerInfo.ToAsn1Object());

            // Construct SignedData
            SignedData signedData = new SignedData(
                digestAlgorithms: new DerSet(digestAlgorithmsVector),
                contentInfo: encapContentInfo,
                certificates: new BerSet(certificatesVector),
                crls: null,
                signerInfos: new DerSet(signerInfosVector));

            // Construct top level ContentInfo
            ContentInfo contentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(OID.PKCS7IdSignedData),
                content: signedData);

            return(contentInfo.GetDerEncoded());
        }
 internal virtual DerSet CreateDerSet(DefiniteLengthInputStream dIn)
 {
     return(DerSet.FromVector(BuildDerEncodableVector(dIn), needsSorting: false));
 }
Example #22
0
        public byte[] GenerateP7s(byte[] data, X509Certificate signingCertificate, IEnumerable <X509Certificate> certPath)
        {
            if (data == null)
            {
                throw new ArgumentNullException(nameof(data));
            }

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

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

            byte[] dataHashSha256 = this.ComputeHash(data);
            Asn1EncodableVector signedAttributesVector = this.CreateSignatureAttribute(dataHashSha256, signingCertificate);

            DerSet signedAttributes = new DerSet(signedAttributesVector);

            byte[] signedAttributesDigest = this.ComputeHash(signedAttributes.GetDerEncoded());

            byte[]              signature                = this.cadesExternalSignature.SignSha256(signedAttributesDigest);
            DerOctetString      digestSignature          = new DerOctetString(signature);
            AlgorithmIdentifier digestSignatureAlgorithm = this.CreateSignatureInfo();

            SignerInfo signerInfo = new SignerInfo(
                sid: new SignerIdentifier(new IssuerAndSerialNumber(signingCertificate.IssuerDN, signingCertificate.SerialNumber)),
                digAlgorithm: new AlgorithmIdentifier(
                    algorithm: new DerObjectIdentifier(Oid.SHA256),
                    parameters: DerNull.Instance
                    ),
                authenticatedAttributes: signedAttributes,
                digEncryptionAlgorithm: digestSignatureAlgorithm,
                encryptedDigest: digestSignature,
                unauthenticatedAttributes: null
                );

            // Construct SignedData.digestAlgorithms
            Asn1EncodableVector digestAlgorithmsVector = new Asn1EncodableVector();

            digestAlgorithmsVector.Add(
                new AlgorithmIdentifier(
                    algorithm: new DerObjectIdentifier(Oid.SHA256),
                    parameters: DerNull.Instance));

            // Construct SignedData.encapContentInfo
            ContentInfo encapContentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(Oid.PKCS7IdData),
                content: null);

            // Construct SignedData.certificates
            Asn1EncodableVector certificatesVector = new Asn1EncodableVector();

            foreach (X509Certificate cert in certPath)
            {
                certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(cert.GetEncoded())));
            }

            // Construct SignedData.signerInfos
            Asn1EncodableVector signerInfosVector = new Asn1EncodableVector();

            signerInfosVector.Add(signerInfo.ToAsn1Object());

            // Construct SignedData
            SignedData signedData = new SignedData(
                digestAlgorithms: new DerSet(digestAlgorithmsVector),
                contentInfo: encapContentInfo,
                certificates: new BerSet(certificatesVector),
                crls: null,
                signerInfos: new DerSet(signerInfosVector));

            // Construct top level ContentInfo
            ContentInfo contentInfo = new ContentInfo(
                contentType: new DerObjectIdentifier(Oid.PKCS7IdSignedData),
                content: signedData);

            return(contentInfo.GetDerEncoded());
        }
    /// <summary>
    /// Creates a certificate signing request from an existing certificate.
    /// </summary>
    public static byte[] CreateSigningRequest(
        X509Certificate2 certificate,
        IList <String> domainNames = null
        )
    {
        using (var cfrg = new CertificateFactoryRandomGenerator())
        {
            SecureRandom random = new SecureRandom(cfrg);

            // try to get signing/private key from certificate passed in
            AsymmetricKeyParameter signingKey = GetPrivateKeyParameter(certificate);
            RsaKeyParameters       publicKey  = GetPublicKeyParameter(certificate);

            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory(GetRSAHashAlgorithm(defaultHashSize), signingKey, random);

            Asn1Set attributes = null;
            X509SubjectAltNameExtension alternateName = null;
            foreach (System.Security.Cryptography.X509Certificates.X509Extension extension in certificate.Extensions)
            {
                if (extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltNameOid || extension.Oid.Value == X509SubjectAltNameExtension.SubjectAltName2Oid)
                {
                    alternateName = new X509SubjectAltNameExtension(extension, extension.Critical);
                    break;
                }
            }

            domainNames = domainNames ?? new List <String>();
            if (alternateName != null)
            {
                foreach (var name in alternateName.DomainNames)
                {
                    if (!domainNames.Any(s => s.Equals(name, StringComparison.OrdinalIgnoreCase)))
                    {
                        domainNames.Add(name);
                    }
                }
                foreach (var ipAddress in alternateName.IPAddresses)
                {
                    if (!domainNames.Any(s => s.Equals(ipAddress, StringComparison.OrdinalIgnoreCase)))
                    {
                        domainNames.Add(ipAddress);
                    }
                }
            }

            if (domainNames.Count > 0)
            {
                List <GeneralName> generalNames = CreateSubjectAlternateNameDomains(domainNames);
                if (generalNames.Count > 0)
                {
                    IList oids   = new ArrayList();
                    IList values = new ArrayList();
                    oids.Add(X509Extensions.SubjectAlternativeName);
                    values.Add(new Org.BouncyCastle.Asn1.X509.X509Extension(false,
                                                                            new DerOctetString(new GeneralNames(generalNames.ToArray()).GetDerEncoded())));

                    AttributePkcs attribute = new AttributePkcs(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
                                                                new DerSet(new X509Extensions(oids, values)));

                    attributes = new DerSet(attribute);
                }
            }

            Pkcs10CertificationRequest pkcs10CertificationRequest = new Pkcs10CertificationRequest(
                signatureFactory,
                new CertificateFactoryX509Name(false, certificate.Subject),
                publicKey,
                attributes,
                signingKey);

            return(pkcs10CertificationRequest.GetEncoded());
        }
    }
Example #24
0
        /**
         * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
         * in the signerInfo can also be set, OR a time-stamp-authority client
         * may be provided.
         * @param secondDigest the digest in the authenticatedAttributes
         * @param signingTime the signing time in the authenticatedAttributes
         * @param tsaClient TSAClient - null or an optional time stamp authority client
         * @return byte[] the bytes for the PKCS7SignedData object
         * @since   2.1.6
         */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp, ICollection <byte[]> crlBytes, CryptoStandard sigtype)
        {
            if (externalDigest != null)
            {
                digest = externalDigest;
                if (RSAdata != null)
                {
                    RSAdata = externalRSAdata;
                }
            }
            else if (externalRSAdata != null && RSAdata != null)
            {
                RSAdata = externalRSAdata;
                sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                digest = sig.GenerateSignature();
            }
            else
            {
                if (RSAdata != null)
                {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }

            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();

            foreach (string dal in digestalgos.Keys)
            {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }

            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();

            v.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA));
            if (RSAdata != null)
            {
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            }
            DerSequence contentinfo = new DerSequence(v);

            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs)
            {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }

            DerSet dercertificates = new DerSet(v);

            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();

            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));

            v = new Asn1EncodableVector();
            v.Add(CertificateInfo.GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));

            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // add the authenticated attribute if present
            if (secondDigest != null /*&& signingTime != null*/)
            {
                signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype)));
            }
            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // Add the digest
            signerinfo.Add(new DerOctetString(digest));

            // When requested, go get and add the timestamp. May throw an exception.
            // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
            // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
            if (tsaClient != null)
            {
                byte[] tsImprint = DigestAlgorithms.Digest(tsaClient.GetMessageDigest(), digest);
                byte[] tsToken   = tsaClient.GetTimeStampToken(tsImprint);
                if (tsToken != null)
                {
                    Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken);
                    if (unauthAttributes != null)
                    {
                        signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes)));
                    }
                }
            }

            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();

            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));

            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));

            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();

            whole.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));

            MemoryStream bOut = new MemoryStream();

            Asn1OutputStream dout = new Asn1OutputStream(bOut);

            dout.WriteObject(new DerSequence(whole));
            dout.Close();

            return(bOut.ToArray());
        }
        /**
         * generate a signed object that for a CMS Signed Data
         * object using the given provider - if encapsulate is true a copy
         * of the message will be included in the signature. The content type
         * is set according to the OID represented by the string signedContentType.
         * @param out stream the CMS object is to be written to.
         * @param signedContentType OID for data to be signed.
         * @param encapsulate true if data should be encapsulated.
         * @param dataOutputStream output stream to copy the data being signed to.
         */
        public Stream Open(
            Stream outStream,
            string signedContentType,
            bool encapsulate,
            Stream dataOutputStream)
        {
            if (outStream == null)
            {
                throw new ArgumentNullException("outStream");
            }
            if (!outStream.CanWrite)
            {
                throw new ArgumentException("Expected writeable stream", "outStream");
            }
            if (dataOutputStream != null && !dataOutputStream.CanWrite)
            {
                throw new ArgumentException("Expected writeable stream", "dataOutputStream");
            }

            _messageDigestsLocked = true;

            //
            // ContentInfo
            //
            BerSequenceGenerator sGen = new BerSequenceGenerator(outStream);

            sGen.AddObject(CmsObjectIdentifiers.SignedData);

            //
            // Signed Data
            //
            BerSequenceGenerator sigGen = new BerSequenceGenerator(
                sGen.GetRawOutputStream(), 0, true);

            bool isCounterSignature = (signedContentType == null);

            DerObjectIdentifier contentTypeOid = isCounterSignature
                ? null
                : new DerObjectIdentifier(signedContentType);

            sigGen.AddObject(CalculateVersion(contentTypeOid));

            Asn1EncodableVector digestAlgs = new Asn1EncodableVector();

            foreach (string digestOid in _messageDigestOids)
            {
                digestAlgs.Add(
                    new AlgorithmIdentifier(new DerObjectIdentifier(digestOid), DerNull.Instance));
            }

            {
                byte[] tmp = new DerSet(digestAlgs).GetEncoded();
                sigGen.GetRawOutputStream().Write(tmp, 0, tmp.Length);
            }

            BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream());

            eiGen.AddObject(contentTypeOid);

            // If encapsulating, add the data as an octet string in the sequence
            Stream encapStream = encapsulate
                                ?       CmsUtilities.CreateBerOctetOutputStream(eiGen.GetRawOutputStream(), 0, true, _bufferSize)
                                :       null;

            // Also send the data to 'dataOutputStream' if necessary
            Stream teeStream = GetSafeTeeOutputStream(dataOutputStream, encapStream);

            // Let all the digests see the data as it is written
            Stream digStream = AttachDigestsToOutputStream(_messageDigests.Values, teeStream);

            return(new CmsSignedDataOutputStream(this, digStream, signedContentType, sGen, sigGen, eiGen));
        }
Example #26
0
        //var bcCert = CertificateUtilities.BuildBouncyCastleCollection(signingCertificates);
        //ICollection<Org.BouncyCastle.X509.X509Certificate>

        private SignedData CreateSignature(
            Session session,
            byte[] content,
            X509Certificate2Collection signingCertificates)
        {
            var digestOid     = ToDigestAlgorithmOid(DigestAlgorithm).Value;
            var hashGenerator = GetHashGenerator(DigestAlgorithm);
            var dataHash      = ComputeDigest(hashGenerator, content);

            // Construct SignerInfo.signedAttrs
            var signedAttributesVector = new Asn1EncodableVector();

            // Add PKCS#9 contentType signed attribute as Data
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(PkcsObjectIdentifiers.Pkcs9AtContentType.Id),
                    new DerSet(new DerObjectIdentifier(PkcsObjectIdentifiers.Data.Id))));

            // Add PKCS#9 messageDigest signed attribute with hash der string encoded
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(PkcsObjectIdentifiers.Pkcs9AtMessageDigest.Id),
                    new DerSet(new DerOctetString(dataHash))));

            // Add PKCS#9 signingTime signed attribute
            signedAttributesVector.Add(
                new Org.BouncyCastle.Asn1.Cms.Attribute(
                    new DerObjectIdentifier(PkcsObjectIdentifiers.Pkcs9AtSigningTime.Id),
                    new DerSet(new Time(new DerUtcTime(DateTime.UtcNow)))));

            var signedAttributes = new DerSet(signedAttributesVector);



            // Sign SignerInfo.signedAttrs with PKCS#1 v1.5 RSA signature using private key stored on PKCS#11 compatible device
            byte[] pkcs1Digest     = ComputeDigest(hashGenerator, signedAttributes.GetDerEncoded());
            byte[] pkcs1DigestInfo = CreateDigestInfo(pkcs1Digest, digestOid);

            // Construct SignedData.digestAlgorithms
            var digestAlgorithmsVector = new Asn1EncodableVector();
            // Construct SignedData.certificates
            var certificatesVector = new Asn1EncodableVector();
            // Construct SignedData.signerInfos
            var signerInfosVector = new Asn1EncodableVector();

            // Construct SignedData.encapContentInfo
            var encapContentInfo = new Org.BouncyCastle.Asn1.Cms.ContentInfo(
                new DerObjectIdentifier(PkcsObjectIdentifiers.Data.Id),
                null); //Always a detached signature.


            foreach (var signingCertificate in signingCertificates)
            {
                var bcSigningCertificate = CertificateUtilities.ToBouncyCastleObject(signingCertificate.RawData);
                // Get public key from certificate
                var pubKeyParams = bcSigningCertificate.GetPublicKey(); //AsymmetricKeyParameter
                if (!(pubKeyParams is RsaKeyParameters))
                {
                    throw new NotSupportedException("Unsupported keys.  Currently supporting RSA keys only.");
                }

                var rsaPubKeyParams = (RsaKeyParameters)pubKeyParams;

                byte[] pkcs1Signature;

                if (signingCertificate.HasPrivateKey)
                {
                    pkcs1Signature = GeneratePkcs1Signature(signingCertificate, pkcs1DigestInfo);
                }
                else
                {
                    pkcs1Signature = GeneratePkcs1Signature(session, rsaPubKeyParams, bcSigningCertificate, pkcs1DigestInfo);
                }

                // Construct SignerInfo
                var signerInfo = new Org.BouncyCastle.Asn1.Cms.SignerInfo(
                    new SignerIdentifier(new IssuerAndSerialNumber(bcSigningCertificate.IssuerDN, bcSigningCertificate.SerialNumber)),
                    new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier(digestOid), null),
                    signedAttributes,
                    new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier(PkcsObjectIdentifiers.RsaEncryption.Id), null),
                    new DerOctetString(pkcs1Signature),
                    null);

                digestAlgorithmsVector.Add(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier(new DerObjectIdentifier(digestOid), null));
                certificatesVector.Add(X509CertificateStructure.GetInstance(Asn1Object.FromByteArray(bcSigningCertificate.GetEncoded())));
                signerInfosVector.Add(signerInfo.ToAsn1Object());
            }

            // Construct SignedData
            var signedData = new SignedData(
                new DerSet(digestAlgorithmsVector),
                encapContentInfo,
                new BerSet(certificatesVector),
                null,
                new DerSet(signerInfosVector));

            return(signedData);
        }