Beispiel #1
0
        private byte[] GetPublicKey(X509Certificate2 certificate)
        {
            var rootBCCert = new X509CertificateParser().ReadCertificate(certificate.RawData);

            return(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootBCCert.GetPublicKey()).GetDerEncoded());
        }
        private X509Certificate MakeCertificate(AsymmetricCipherKeyPair subjectKeyPair, X509Name certificateSubject, AsymmetricCipherKeyPair rootKeyPair, X509Name rootSubject, bool isRootCertificate, bool addAuthorityKeyIdentifier)
        {
            X509Certificate x509Certificate;

            try
            {
                AsymmetricKeyParameter     @public  = subjectKeyPair.Public;
                AsymmetricKeyParameter     @private = rootKeyPair.Private;
                AsymmetricKeyParameter     asymmetricKeyParameter     = rootKeyPair.Public;
                X509V3CertificateGenerator x509V3CertificateGenerator = new X509V3CertificateGenerator();
                x509V3CertificateGenerator.Reset();
                if (this.SerialNumber != -9223372036854775808L)
                {
                    x509V3CertificateGenerator.SetSerialNumber(new BigInteger(this.SerialNumber.ToString()));
                }
                else
                {
                    DateTime now = DateTime.Now;
                    x509V3CertificateGenerator.SetSerialNumber(new BigInteger(128, new Random(now.Millisecond + Environment.TickCount)));
                }
                x509V3CertificateGenerator.SetIssuerDN(rootSubject);
                x509V3CertificateGenerator.SetNotBefore(this.ValidFrom.ToUniversalTime());
                x509V3CertificateGenerator.SetNotAfter(this.ValidTo.ToUniversalTime());
                x509V3CertificateGenerator.SetSubjectDN(certificateSubject);
                x509V3CertificateGenerator.SetPublicKey(@public);
                x509V3CertificateGenerator.SetSignatureAlgorithm(string.Concat(this.SignatureAlgorithm.ToString(), "Encryption"));
                int extensionType = 0;
                Asn1EncodableVector asn1EncodableVectors = new Asn1EncodableVector(new Asn1Encodable[0]);
                foreach (ExtensionInfo extension in this.Extensions.extensionInfo)
                {
                    if (!extension.ExtendedKeyUsage)
                    {
                        extensionType |= (int)extension.ExtensionType;
                    }
                    if (!extension.ExtendedKeyUsage)
                    {
                        continue;
                    }
                    asn1EncodableVectors.Add(new Asn1Encodable[] { (Asn1Encodable)extension.ExtensionType });
                }
                bool keyUsageIsCritical = this.Extensions.KeyUsageIsCritical;
                if (isRootCertificate)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
                    extensionType     |= 6;
                    keyUsageIsCritical = true;
                }
                if (extensionType != 0)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.KeyUsage, keyUsageIsCritical, new KeyUsage(extensionType));
                }
                if (asn1EncodableVectors.Count > 0)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, this.Extensions.EnhancedKeyUsageIsCritical, ExtendedKeyUsage.GetInstance(new DerSequence(asn1EncodableVectors)));
                }
                x509V3CertificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(@public)));
                if (addAuthorityKeyIdentifier)
                {
                    x509V3CertificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricKeyParameter)));
                }
                X509Certificate x509Certificate1 = x509V3CertificateGenerator.Generate(@private, this.GetSecureRandom());
                x509Certificate1.Verify(asymmetricKeyParameter);
                x509Certificate = x509Certificate1;
            }
            catch
            {
                throw;
            }
            return(x509Certificate);
        }
Beispiel #3
0
        public async Task <bool> RequestMinecraftChain(AuthResponse <XuiDisplayClaims <XstsXui> > token, AsymmetricCipherKeyPair key)
        {
            var b = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(MinecraftKeyPair.Public).GetEncoded().EncodeBase64();

            var body = new MCChainPostData()
            {
                IdentityPublicKey = b
            };

            var client = GetClient();

            //using (var client = new HttpClient())
            {
                using (var r = new HttpRequestMessage(HttpMethod.Post,
                                                      MinecraftAuthUrl))
                {
                    //r.Headers.Add("x-xbl-contract-version", "1");

                    r.Content = SetHttpContent(body, out var jsonData);
                    r.Headers.Add("Authorization", $"XBL3.0 x={token.DisplayClaims.Xui[0].Uhs};{token.Token}");
                    r.Headers.Add("User-Agent", "MCPE/UWP");
                    r.Headers.Add("Client-Version", McpeProtocolInfo.ProtocolVersion.ToString());
                    //Sign(r, jsonData);
                    try
                    {
                        using (var response = await client
                                              .SendAsync(r, HttpCompletionOption.ResponseContentRead)
                                              .ConfigureAwait(false))
                        {
                            response.EnsureSuccessStatusCode();

                            var rawResponse = await response.Content.ReadAsStringAsync();

                            DecodedChain = new ChainData();
                            dynamic a     = JObject.Parse(rawResponse);
                            var     chain = ((JArray)a.chain).Values <string>().ToArray();
                            DecodedChain.Chain = new CertificateData[chain.Length];
                            for (int i = 0; i < chain.Length; i++)
                            {
                                var element = chain[i];
                                try
                                {
                                    DecodedChain.Chain[i] = JWT.Payload <CertificateData>(element);
                                }
                                catch (Exception ex)
                                {
                                    Log.Error($"Could not parse chain element: {ex.ToString()}");
                                }
                            }

                            //DecodedChain = JsonConvert.DeserializeObject<ChainData>(rawResponse);
                            MinecraftChain = Encoding.UTF8.GetBytes(rawResponse);
                            Log.Debug($"Chain: {rawResponse}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Warn($"AHHH: {ex.ToString()}");
                        return(false);
                    }
                }
            }

            Log.Debug($"Xbox login processed!");
            return(true);
        }
        private static PemObject CreatePemObject(object obj)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }

            if (obj is AsymmetricCipherKeyPair)
            {
                return(CreatePemObject(((AsymmetricCipherKeyPair)obj).Private));
            }

            string type;

            byte[] encoding;

            if (obj is PemObject)
            {
                return((PemObject)obj);
            }

            if (obj is PemObjectGenerator)
            {
                return(((PemObjectGenerator)obj).Generate());
            }

            if (obj is X509Certificate)
            {
                // TODO Should we prefer "X509 CERTIFICATE" here?
                type = "CERTIFICATE";
                try
                {
                    encoding = ((X509Certificate)obj).GetEncoded();
                }
                catch (CertificateEncodingException e)
                {
                    throw new IOException("Cannot Encode object: " + e.ToString());
                }
            }
            else if (obj is X509Crl)
            {
                type = "X509 CRL";
                try
                {
                    encoding = ((X509Crl)obj).GetEncoded();
                }
                catch (CrlException e)
                {
                    throw new IOException("Cannot Encode object: " + e.ToString());
                }
            }
            else if (obj is AsymmetricKeyParameter)
            {
                AsymmetricKeyParameter akp = (AsymmetricKeyParameter)obj;
                if (akp.IsPrivate)
                {
                    string keyType;
                    encoding = EncodePrivateKey(akp, out keyType);

                    type = keyType + " PRIVATE KEY";
                }
                else
                {
                    type = "PUBLIC KEY";

                    encoding = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(akp).GetDerEncoded();
                }
            }
            else if (obj is IX509AttributeCertificate)
            {
                type     = "ATTRIBUTE CERTIFICATE";
                encoding = ((X509V2AttributeCertificate)obj).GetEncoded();
            }
            else if (obj is Pkcs10CertificationRequest)
            {
                type     = "CERTIFICATE REQUEST";
                encoding = ((Pkcs10CertificationRequest)obj).GetEncoded();
            }
            else if (obj is Asn1.Cms.ContentInfo)
            {
                type     = "PKCS7";
                encoding = ((Asn1.Cms.ContentInfo)obj).GetEncoded();
            }
            else
            {
                throw new PemGenerationException("Object type not supported: " + Platform.GetTypeName(obj));
            }

            return(new PemObject(type, encoding));
        }
Beispiel #5
0
 private static SubjectKeyIdentifier CreateSubjectKeyID(
     AsymmetricKeyParameter pubKey)
 {
     return(new SubjectKeyIdentifier(
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey)));
 }
Beispiel #6
0
        private void doTestGP(
            string algName,
            int size,
            int privateValueSize,
            IBigInteger g,
            IBigInteger p)
        {
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            DHParameters            dhParams = new DHParameters(p, g, null, privateValueSize);
            KeyGenerationParameters kgp      = new DHKeyGenerationParameters(new SecureRandom(), dhParams);

            keyGen.Init(kgp);

            //
            // a side
            //
            IAsymmetricCipherKeyPair aKeyPair = keyGen.GenerateKeyPair();

            IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName);

            checkKeySize(privateValueSize, aKeyPair);

            aKeyAgreeBasic.Init(aKeyPair.Private);

            //
            // b side
            //
            IAsymmetricCipherKeyPair bKeyPair = keyGen.GenerateKeyPair();

            IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algName);

            checkKeySize(privateValueSize, bKeyPair);

            bKeyAgreeBasic.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgreeBasic.doPhase(bKeyPair.Public, true);
//			bKeyAgreeBasic.doPhase(aKeyPair.Public, true);
//
//			IBigInteger  k1 = new BigInteger(aKeyAgreeBasic.generateSecret());
//			IBigInteger  k2 = new BigInteger(bKeyAgreeBasic.generateSecret());
            IBigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public);
            IBigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public);

            if (!k1.Equals(k2))
            {
                Fail(size + " bit 2-way test failed");
            }

            //
            // public key encoding test
            //
//			byte[]              pubEnc = aKeyPair.Public.GetEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

//			KeyFactory          keyFac = KeyFactory.getInstance(algName);
//			X509EncodedKeySpec  pubX509 = new X509EncodedKeySpec(pubEnc);
//			DHPublicKey         pubKey = (DHPublicKey)keyFac.generatePublic(pubX509);
            DHPublicKeyParameters pubKey = (DHPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);
//			DHParameterSpec     spec = pubKey.Parameters;
            DHParameters spec = pubKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit public key encoding/decoding test failed on parameters");
            }

            if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y))
            {
                Fail(size + " bit public key encoding/decoding test failed on y value");
            }

            //
            // public key serialisation test
            //
            // TODO Put back in
//			MemoryStream bOut = new MemoryStream();
//			ObjectOutputStream oOut = new ObjectOutputStream(bOut);
//
//			oOut.WriteObject(aKeyPair.Public);
//
//			MemoryStream bIn = new MemoryStream(bOut.ToArray(), false);
//			ObjectInputStream oIn = new ObjectInputStream(bIn);
//
//			pubKey = (DHPublicKeyParameters)oIn.ReadObject();
            spec = pubKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit public key serialisation test failed on parameters");
            }

            if (!((DHPublicKeyParameters)aKeyPair.Public).Y.Equals(pubKey.Y))
            {
                Fail(size + " bit public key serialisation test failed on y value");
            }

            //
            // private key encoding test
            //
//			byte[] privEnc = aKeyPair.Private.GetEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();
//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			DHPrivateKeyParameters privKey = (DHPrivateKey)keyFac.generatePrivate(privPKCS8);
            DHPrivateKeyParameters privKey = (DHPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

            spec = privKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit private key encoding/decoding test failed on parameters");
            }

            if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X))
            {
                Fail(size + " bit private key encoding/decoding test failed on y value");
            }

            //
            // private key serialisation test
            //
            // TODO Put back in
//			bOut = new MemoryStream();
//			oOut = new ObjectOutputStream(bOut);
//
//			oOut.WriteObject(aKeyPair.Private);
//
//			bIn = new MemoryStream(bOut.ToArray(), false);
//			oIn = new ObjectInputStream(bIn);
//
//			privKey = (DHPrivateKeyParameters)oIn.ReadObject();
            spec = privKey.Parameters;

            if (!spec.G.Equals(dhParams.G) || !spec.P.Equals(dhParams.P))
            {
                Fail(size + " bit private key serialisation test failed on parameters");
            }

            if (!((DHPrivateKeyParameters)aKeyPair.Private).X.Equals(privKey.X))
            {
                Fail(size + " bit private key serialisation test failed on y value");
            }

            //
            // three party test
            //
            IAsymmetricCipherKeyPairGenerator aPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            aPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
            IAsymmetricCipherKeyPair aPair = aPairGen.GenerateKeyPair();

            IAsymmetricCipherKeyPairGenerator bPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            bPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
            IAsymmetricCipherKeyPair bPair = bPairGen.GenerateKeyPair();

            IAsymmetricCipherKeyPairGenerator cPairGen = GeneratorUtilities.GetKeyPairGenerator(algName);

            cPairGen.Init(new DHKeyGenerationParameters(new SecureRandom(), spec));
            IAsymmetricCipherKeyPair cPair = cPairGen.GenerateKeyPair();


            IBasicAgreement aKeyAgree = AgreementUtilities.GetBasicAgreement(algName);

            aKeyAgree.Init(aPair.Private);

            IBasicAgreement bKeyAgree = AgreementUtilities.GetBasicAgreement(algName);

            bKeyAgree.Init(bPair.Private);

            IBasicAgreement cKeyAgree = AgreementUtilities.GetBasicAgreement(algName);

            cKeyAgree.Init(cPair.Private);

//			Key ac = aKeyAgree.doPhase(cPair.Public, false);
//			Key ba = bKeyAgree.doPhase(aPair.Public, false);
//			Key cb = cKeyAgree.doPhase(bPair.Public, false);
//
//			aKeyAgree.doPhase(cb, true);
//			bKeyAgree.doPhase(ac, true);
//			cKeyAgree.doPhase(ba, true);
//
//			IBigInteger aShared = new BigInteger(aKeyAgree.generateSecret());
//			IBigInteger bShared = new BigInteger(bKeyAgree.generateSecret());
//			IBigInteger cShared = new BigInteger(cKeyAgree.generateSecret());

            DHPublicKeyParameters ac = new DHPublicKeyParameters(aKeyAgree.CalculateAgreement(cPair.Public), spec);
            DHPublicKeyParameters ba = new DHPublicKeyParameters(bKeyAgree.CalculateAgreement(aPair.Public), spec);
            DHPublicKeyParameters cb = new DHPublicKeyParameters(cKeyAgree.CalculateAgreement(bPair.Public), spec);

            IBigInteger aShared = aKeyAgree.CalculateAgreement(cb);
            IBigInteger bShared = bKeyAgree.CalculateAgreement(ac);
            IBigInteger cShared = cKeyAgree.CalculateAgreement(ba);

            if (!aShared.Equals(bShared))
            {
                Fail(size + " bit 3-way test failed (a and b differ)");
            }

            if (!cShared.Equals(bShared))
            {
                Fail(size + " bit 3-way test failed (c and b differ)");
            }
        }
Beispiel #7
0
        public static OneAsymmetricKeyInfo CreateOneAsymmetricKeyInfo(AsymmetricKeyParameter privateKey, AsymmetricKeyParameter publicKey)
        {
            if (publicKey.IsPrivate)
            {
                throw new ArgumentException("Private key passed - public key expected", "publicKey");
            }

            return(CreateOneAsymmetricKeyInfo(PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey), SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey)));
        }
 public static byte[] GetPublicKeyDerEncoded(AsymmetricCipherKeyPair AsymmetricKey)
 {
     return(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(AsymmetricKey.Public).GetDerEncoded());
 }
Beispiel #9
0
        private static void Certificate_Sample()
        {
            var algorithm = "RSA";
            var keySize   = 2048;

            //颁发者DN
            var issuer = new X509Name(new ArrayList
            {
                X509Name.C,
                X509Name.O,
                X509Name.OU,
                X509Name.L,
                X509Name.ST
            }, new Hashtable
            {
                [X509Name.C]  = "CN",
                [X509Name.O]  = "Fulu Newwork",
                [X509Name.OU] = "Fulu RSA CA 2020",
                [X509Name.L]  = "Wuhan",
                [X509Name.ST] = "Hubei",
            });
            //使用者DN
            var subject = new X509Name(new ArrayList
            {
                X509Name.C,
                X509Name.O,
                X509Name.CN
            }, new Hashtable
            {
                [X509Name.C]  = "CN",
                [X509Name.O]  = "ICH",
                [X509Name.CN] = "*.fulu.com"
            });

            CertificateGenerator.GenerateCertificate(new GenerateCertificateOptions {
                Path = "mypfx.pfx", Issuer = issuer, Subject = subject
            });

            var password           = "******";        //证书密码
            var signatureAlgorithm = "SHA256WITHRSA"; //签名算法

            //var keyP = RSAKeyGenerator.Pkcs1();

            //var pK = AsymmetricKeyUtilities.GetAsymmetricKeyParameterFormPrivateKey(keyP.PrivateKey);

            //CertificateGenerator.GenerateCertificate(new GenerateCertificateOptions{ Path = "mypfx.pfx", Issuer = issuer, Subject = subject });

            //生成证书
            // CertificateGenerator.X509V3(algorithm, keySize, password, signatureAlgorithm, DateTime.Now.AddDays(-1),DateTime.Now.AddDays(2), issuer, subject, "mycert.cert", "mypfx.pfx");

            var pfx = new X509Certificate2("mypfx.pfx", password, X509KeyStorageFlags.Exportable);



            var keyPair2 = DotNetUtilities.GetKeyPair(pfx.PrivateKey);

            var subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair2.Public);
            var privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair2.Private);

            var privateKey = Base64.ToBase64String(privateKeyInfo.ParsePrivateKey().GetEncoded());
            var publicKey  = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded());

            //var cert = new X509Certificate2("mycert.cert", string.Empty, X509KeyStorageFlags.Exportable);

            //var publicKey2 = Base64.ToBase64String(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.FromX509Certificate(cert).GetPublicKey()).GetEncoded());

            Console.ForegroundColor = ConsoleColor.DarkYellow;

            Console.WriteLine("Pfx证书私钥:");
            Console.WriteLine(privateKey);

            Console.WriteLine("Pfx证书公钥:");
            Console.WriteLine(publicKey);

            //Console.WriteLine("Cert证书公钥:");
            //Console.WriteLine(publicKey2);

            var data = "hello rsa";

            Console.WriteLine($"加密原文:{data}");

            var pkcs1data = RSA.EncryptToBase64(data, AsymmetricKeyUtilities.GetAsymmetricKeyParameterFormPublicKey(publicKey), Algorithms.RSA_ECB_PKCS1Padding);

            Console.WriteLine("加密结果:");
            Console.WriteLine(pkcs1data);

            //pkcs1data =
            //    "KGbgP3Ns6kFyjJ7tbepdZ3X8zssoHKWyVzVesghWg8fFP0ZMVumf+iXJ93LBu3xqKWE/5JTr1qFc5u0Cm3BUPnusMjBTgMrQk3zopVOELpChFbkeTR2YHsdDZdBzaJVN4SQQwHMkp2w8Pyb9x1NjsFoHHQEskBUNnOEuGkEFZdg=";

            Console.WriteLine("解密结果:");
            var datares = RSA.DecryptFromBase64(pkcs1data,
                                                AsymmetricKeyUtilities.GetAsymmetricKeyParameterFormPrivateKey(privateKey), Algorithms.RSA_ECB_PKCS1Padding);

            Console.WriteLine(datares);
        }
Beispiel #10
0
        private static byte[] SerializePublicKey(AsymmetricKeyParameter publicKey)
        {
            SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

            return(SerializeKey(publicKeyInfo));
        }
        /// <summary>
        /// Create the extensions.
        /// </summary>
        /// <param name="cg">The cert generator.</param>
        /// <param name="subjectPublicKey">The public key to use for the extensions.</param>
        private void CreateExtensions(X509V3CertificateGenerator cg, AsymmetricKeyParameter subjectPublicKey)
        {
            if (X509Extensions.FindExtension <X509SubjectKeyIdentifierExtension>(m_extensions) == null)
            {
                // Subject key identifier
                cg.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.SubjectKeyIdentifier.Id, false,
                                new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectPublicKey)));
            }

            // Basic constraints
            BasicConstraints basicConstraints = new BasicConstraints(m_isCA);

            if (m_isCA && m_pathLengthConstraint >= 0)
            {
                basicConstraints = new BasicConstraints(m_pathLengthConstraint);
            }
            else if (!m_isCA && IssuerCAKeyCert == null)
            {   // self-signed
                basicConstraints = new BasicConstraints(0);
            }

            if (X509Extensions.FindExtension <X509BasicConstraintsExtension>(m_extensions) == null)
            {
                cg.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.BasicConstraints.Id, true, basicConstraints);
            }

            // Authority Key identifier references the issuer cert or itself when self signed
            AsymmetricKeyParameter issuerPublicKey;
            BigInteger             issuerSerialNumber;

            if (IssuerCAKeyCert != null)
            {
                issuerPublicKey    = X509Utils.GetPublicKeyParameter(IssuerCAKeyCert);
                issuerSerialNumber = X509Utils.GetSerialNumber(IssuerCAKeyCert);
            }
            else
            {
                issuerPublicKey    = subjectPublicKey;
                issuerSerialNumber = new BigInteger(1, m_serialNumber.Reverse().ToArray());
            }

            // Authority Key Identifier
            if (X509Extensions.FindExtension <X509AuthorityKeyIdentifierExtension>(m_extensions) == null)
            {
                cg.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.AuthorityKeyIdentifier.Id, false,
                                new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerPublicKey),
                                                           new GeneralNames(new GeneralName(m_issuerIssuerAKI)), issuerSerialNumber));
            }

            if (!m_isCA)
            {
                // Key usage
                var keyUsage = KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                               KeyUsage.NonRepudiation | KeyUsage.KeyEncipherment;
                if (IssuerCAKeyCert == null)
                {   // only self signed certs need KeyCertSign flag.
                    keyUsage |= KeyUsage.KeyCertSign;
                }

                if (X509Extensions.FindExtension <X509KeyUsageExtension>(m_extensions) == null)
                {
                    cg.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.KeyUsage, true,
                                    new KeyUsage(keyUsage));
                }

                // Extended Key usage
                if (X509Extensions.FindExtension <X509EnhancedKeyUsageExtension>(m_extensions) == null)
                {
                    cg.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.ExtendedKeyUsage, true,
                                    new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                    {
                        new DerObjectIdentifier(Oids.ServerAuthentication), // server auth
                        new DerObjectIdentifier(Oids.ClientAuthentication), // client auth
                    }));
                }
            }
            else
            {
                if (X509Extensions.FindExtension <X509KeyUsageExtension>(m_extensions) == null)
                {
                    // Key usage CA
                    cg.AddExtension(Org.BouncyCastle.Asn1.X509.X509Extensions.KeyUsage, true,
                                    new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
                }
            }

            foreach (var extension in m_extensions)
            {
                cg.AddExtension(extension.Oid.Value, extension.Critical, Asn1Object.FromByteArray(extension.RawData));
            }
        }
Beispiel #12
0
        public SimpleTestResult EncodeDecodePublicLW(string oidStr, DerObjectIdentifier digest)
        {
            DerObjectIdentifier       oid        = ECGost3410NamedCurves.GetOid(oidStr);
            ECNamedDomainParameters   ecp        = new ECNamedDomainParameters(oid, ECGost3410NamedCurves.GetByOid(oid));
            ECGOST3410Parameters      gostParams = new ECGOST3410Parameters(ecp, oid, digest, null);
            ECKeyGenerationParameters parameters = new ECKeyGenerationParameters(gostParams, new SecureRandom());
            ECKeyPairGenerator        engine     = new ECKeyPairGenerator();

            engine.Init(parameters);
            AsymmetricCipherKeyPair pair = engine.GenerateKeyPair();
            ECPublicKeyParameters   generatedKeyParameters = (ECPublicKeyParameters)pair.Public;

            SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(generatedKeyParameters);

            ECPublicKeyParameters recoveredKeyParameters = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(info);

            { // Specifically cast and test gost parameters.
                ECGOST3410Parameters gParam = (ECGOST3410Parameters)generatedKeyParameters.Parameters;
                ECGOST3410Parameters rParam = (ECGOST3410Parameters)recoveredKeyParameters.Parameters;


                bool ok = SafeEquals(gParam.DigestParamSet, rParam.DigestParamSet) &&
                          SafeEquals(gParam.EncryptionParamSet, rParam.EncryptionParamSet) &&
                          SafeEquals(gParam.PublicKeyParamSet, rParam.PublicKeyParamSet);

                if (!ok)
                {
                    return(new SimpleTestResult(false, "GOST parameters does not match"));
                }
            }

            if (!((ECGOST3410Parameters)recoveredKeyParameters.Parameters).Name.Equals(
                    ((ECGOST3410Parameters)generatedKeyParameters.Parameters).Name))
            {
                return(new SimpleTestResult(false, "Name does not match"));
            }


            if (recoveredKeyParameters.IsPrivate != generatedKeyParameters.IsPrivate)
            {
                return(new SimpleTestResult(false, "isPrivate does not match"));
            }

            if (!Arrays.AreEqual(recoveredKeyParameters.Q.GetEncoded(true), generatedKeyParameters.Q.GetEncoded(true)))
            {
                return(new SimpleTestResult(false, "Q does not match"));
            }

            if (!recoveredKeyParameters.Parameters.Curve.Equals(generatedKeyParameters.Parameters.Curve))
            {
                return(new SimpleTestResult(false, "Curve does not match"));
            }

            if (!Arrays.AreEqual(
                    recoveredKeyParameters.Parameters.G.GetEncoded(true),
                    generatedKeyParameters.Parameters.G.GetEncoded(true)))
            {
                return(new SimpleTestResult(false, "G does not match"));
            }

            if (!recoveredKeyParameters.Parameters.H.Equals(generatedKeyParameters.Parameters.H))
            {
                return(new SimpleTestResult(false, "H does not match"));
            }

            if (!recoveredKeyParameters.Parameters.HInv.Equals(generatedKeyParameters.Parameters.HInv))
            {
                return(new SimpleTestResult(false, "Hinv does not match"));
            }

            if (!recoveredKeyParameters.Parameters.N.Equals(generatedKeyParameters.Parameters.N))
            {
                return(new SimpleTestResult(false, "N does not match"));
            }

            if (!Arrays.AreEqual(recoveredKeyParameters.Parameters.GetSeed(), generatedKeyParameters.Parameters.GetSeed()))
            {
                return(new SimpleTestResult(false, "Seed does not match"));
            }

            return(new SimpleTestResult(true, null));
        }
Beispiel #13
0
        public SimpleTestResult EncodeRecodePublicKey()
        {
            DerObjectIdentifier       oid          = ECGost3410NamedCurves.GetOid("Tc26-Gost-3410-12-512-paramSetA");
            ECNamedDomainParameters   ecp          = new ECNamedDomainParameters(oid, ECGost3410NamedCurves.GetByOid(oid));
            ECGOST3410Parameters      gostParams   = new ECGOST3410Parameters(ecp, oid, RosstandartObjectIdentifiers.id_tc26_gost_3411_12_512, null);
            ECKeyGenerationParameters paramameters = new ECKeyGenerationParameters(gostParams, new SecureRandom());
            ECKeyPairGenerator        engine       = new ECKeyPairGenerator();

            engine.Init(paramameters);
            AsymmetricCipherKeyPair pair = engine.GenerateKeyPair();

            ECPublicKeyParameters generatedKeyParameters = (ECPublicKeyParameters)pair.Public;
            ECPublicKeyParameters keyParameters          = generatedKeyParameters;


            //
            // Continuously encode/decode the key and check for loss of information.
            //
            for (int t = 0; t < 3; t++)
            {
                SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyParameters);
                keyParameters = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(info);

                {     // Specifically cast and test gost parameters.
                    ECGOST3410Parameters gParam = (ECGOST3410Parameters)generatedKeyParameters.Parameters;
                    ECGOST3410Parameters rParam = (ECGOST3410Parameters)keyParameters.Parameters;


                    bool ok = SafeEquals(gParam.DigestParamSet, rParam.DigestParamSet) &&
                              SafeEquals(gParam.EncryptionParamSet, rParam.EncryptionParamSet) &&
                              SafeEquals(gParam.PublicKeyParamSet, rParam.PublicKeyParamSet);

                    if (!ok)
                    {
                        return(new SimpleTestResult(false, "GOST parameters does not match"));
                    }
                }

                if (!((ECGOST3410Parameters)keyParameters.Parameters).Name.Equals(
                        ((ECGOST3410Parameters)generatedKeyParameters.Parameters).Name))
                {
                    return(new SimpleTestResult(false, "Name does not match"));
                }


                if (keyParameters.IsPrivate != generatedKeyParameters.IsPrivate)
                {
                    return(new SimpleTestResult(false, "isPrivate does not match"));
                }

                if (!Arrays.AreEqual(keyParameters.Q.GetEncoded(true), generatedKeyParameters.Q.GetEncoded(true)))
                {
                    return(new SimpleTestResult(false, "Q does not match"));
                }

                if (!keyParameters.Parameters.Curve.Equals(generatedKeyParameters.Parameters.Curve))
                {
                    return(new SimpleTestResult(false, "Curve does not match"));
                }

                if (!Arrays.AreEqual(
                        keyParameters.Parameters.G.GetEncoded(true),
                        generatedKeyParameters.Parameters.G.GetEncoded(true)))
                {
                    return(new SimpleTestResult(false, "G does not match"));
                }

                if (!keyParameters.Parameters.H.Equals(generatedKeyParameters.Parameters.H))
                {
                    return(new SimpleTestResult(false, "H does not match"));
                }

                if (!keyParameters.Parameters.HInv.Equals(generatedKeyParameters.Parameters.HInv))
                {
                    return(new SimpleTestResult(false, "Hinv does not match"));
                }

                if (!keyParameters.Parameters.N.Equals(generatedKeyParameters.Parameters.N))
                {
                    return(new SimpleTestResult(false, "N does not match"));
                }

                if (!Arrays.AreEqual(keyParameters.Parameters.GetSeed(), generatedKeyParameters.Parameters.GetSeed()))
                {
                    return(new SimpleTestResult(false, "Seed does not match"));
                }
            }
            return(new SimpleTestResult(true, null));
        }
Beispiel #14
0
    private static OriginatorPublicKey CreateOriginatorPublicKey(AsymmetricKeyParameter publicKey)
    {
        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);

        return(new OriginatorPublicKey(new AlgorithmIdentifier(subjectPublicKeyInfo.AlgorithmID.Algorithm, DerNull.Instance), subjectPublicKeyInfo.PublicKeyData.GetBytes()));
    }
 private static SubjectPublicKeyInfo GetSubjectPublicKey(
     X509Certificate c)
 {
     return(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(c.GetPublicKey()));
 }
Beispiel #16
0
        /// <summary>
        /// Create a self signed certificate with bouncy castle.
        /// </summary>
        public static X509Certificate2 GenerateCertificate(
            string subjectName,
            Action <X509V3CertificateGenerator> modifyGenerator,
            string signatureAlgorithm = "SHA256WITHRSA",
            int publicKeyLength       = 2048,
            ChainCertificateRequest chainCertificateRequest = null)
        {
            if (string.IsNullOrEmpty(subjectName))
            {
                subjectName = "NuGetTest";
            }

            var random  = new SecureRandom();
            var keyPair = GenerateKeyPair(publicKeyLength);

            // Create cert
            var subjectDN = $"CN={subjectName}";
            var certGen   = new X509V3CertificateGenerator();

            certGen.SetSubjectDN(new X509Name(subjectDN));

            // default to new key pair
            var issuerPrivateKey = keyPair.Private;
            var keyUsage         = KeyUsage.DigitalSignature;
            var issuerDN         = chainCertificateRequest?.IssuerDN ?? subjectDN;

            certGen.SetIssuerDN(new X509Name(issuerDN));

#if IS_DESKTOP
            if (chainCertificateRequest != null)
            {
                if (chainCertificateRequest.Issuer != null)
                {
                    // for a certificate with an issuer assign Authority Key Identifier
                    var issuer   = chainCertificateRequest?.Issuer;
                    var bcIssuer = DotNetUtilities.FromX509Certificate(issuer);
                    var authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(bcIssuer);
                    issuerPrivateKey = DotNetUtilities.GetKeyPair(issuer.PrivateKey).Private;
                    certGen.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false, authorityKeyIdentifier);
                }

                if (chainCertificateRequest.ConfigureCrl)
                {
                    // for a certificate in a chain create CRL distribution point extension
                    var crlServerUri  = $"{chainCertificateRequest.CrlServerBaseUri}{issuerDN}.crl";
                    var generalName   = new Org.BouncyCastle.Asn1.X509.GeneralName(Org.BouncyCastle.Asn1.X509.GeneralName.UniformResourceIdentifier, new DerIA5String(crlServerUri));
                    var distPointName = new DistributionPointName(new GeneralNames(generalName));
                    var distPoint     = new DistributionPoint(distPointName, null, null);

                    certGen.AddExtension(X509Extensions.CrlDistributionPoints, critical: false, extensionValue: new DerSequence(distPoint));
                }

                if (chainCertificateRequest.IsCA)
                {
                    // update key usage with CA cert sign and crl sign attributes
                    keyUsage |= KeyUsage.CrlSign | KeyUsage.KeyCertSign;
                }
            }
#endif
            certGen.SetNotAfter(DateTime.UtcNow.Add(TimeSpan.FromHours(1)));
            certGen.SetNotBefore(DateTime.UtcNow.Subtract(TimeSpan.FromHours(1)));
            certGen.SetPublicKey(keyPair.Public);

            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);
            certGen.SetSerialNumber(serialNumber);

            var subjectKeyIdentifier = new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public));
            certGen.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false, subjectKeyIdentifier);

            certGen.AddExtension(X509Extensions.KeyUsage.Id, false, new KeyUsage(keyUsage));
            certGen.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(chainCertificateRequest?.IsCA ?? false));

            // Allow changes
            modifyGenerator?.Invoke(certGen);

            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm, issuerPrivateKey, random);
            var certificate      = certGen.Generate(signatureFactory);
            var certResult       = new X509Certificate2(certificate.GetEncoded());

#if IS_DESKTOP
            certResult.PrivateKey = DotNetUtilities.ToRSA(keyPair.Private as RsaPrivateCrtKeyParameters);
#endif

            return(certResult);
        }
Beispiel #17
0
        private void doTestECDH(
            string algorithm)
        {
            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator(algorithm);

//			EllipticCurve curve = new EllipticCurve(
//				new ECFieldFp(new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839")), // q
//				new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a
//				new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b
            ECCurve curve = new FPCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"),         // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),                 // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16));                // b

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
//				ECPointUtil.DecodePoint(curve, Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                curve.DecodePoint(Hex.Decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G
                new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307"),      // n
                BigInteger.One);                                                                                 //1); // h

//			g.initialize(ecSpec, new SecureRandom());
            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            //
            // a side
            //
            IAsymmetricCipherKeyPair aKeyPair = g.GenerateKeyPair();

            IBasicAgreement aKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);

            aKeyAgreeBasic.Init(aKeyPair.Private);

            //
            // b side
            //
            IAsymmetricCipherKeyPair bKeyPair = g.GenerateKeyPair();

            IBasicAgreement bKeyAgreeBasic = AgreementUtilities.GetBasicAgreement(algorithm);

            bKeyAgreeBasic.Init(bKeyPair.Private);

            //
            // agreement
            //
//			aKeyAgreeBasic.doPhase(bKeyPair.Public, true);
//			bKeyAgreeBasic.doPhase(aKeyPair.Public, true);
//
//			IBigInteger k1 = new BigInteger(aKeyAgreeBasic.generateSecret());
//			IBigInteger k2 = new BigInteger(bKeyAgreeBasic.generateSecret());
            IBigInteger k1 = aKeyAgreeBasic.CalculateAgreement(bKeyPair.Public);
            IBigInteger k2 = bKeyAgreeBasic.CalculateAgreement(aKeyPair.Public);

            if (!k1.Equals(k2))
            {
                Fail(algorithm + " 2-way test failed");
            }

            //
            // public key encoding test
            //
//			byte[] pubEnc = aKeyPair.Public.GetEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(aKeyPair.Public).GetDerEncoded();

//			KeyFactory keyFac = KeyFactory.getInstance(algorithm);
//			X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
//			ECPublicKey pubKey = (ECPublicKey)keyFac.generatePublic(pubX509);
            ECPublicKeyParameters pubKey = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(pubEnc);

            ECDomainParameters ecDP = pubKey.Parameters;

//			if (!pubKey.getW().Equals(((ECPublicKeyParameters)aKeyPair.Public).getW()))
            if (!pubKey.Q.Equals(((ECPublicKeyParameters)aKeyPair.Public).Q))
            {
//				Console.WriteLine(" expected " + pubKey.getW().getAffineX() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineX());
//				Console.WriteLine(" expected " + pubKey.getW().getAffineY() + " got " + ((ECPublicKey)aKeyPair.Public).getW().getAffineY());
//				Fail(algorithm + " public key encoding (W test) failed");
                Console.WriteLine(" expected " + pubKey.Q.X.ToBigInteger()
                                  + " got " + ((ECPublicKeyParameters)aKeyPair.Public).Q.X.ToBigInteger());
                Console.WriteLine(" expected " + pubKey.Q.Y.ToBigInteger()
                                  + " got " + ((ECPublicKeyParameters)aKeyPair.Public).Q.Y.ToBigInteger());
                Fail(algorithm + " public key encoding (Q test) failed");
            }

//			if (!pubKey.Parameters.getGenerator().Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.getGenerator()))
            if (!pubKey.Parameters.G.Equals(((ECPublicKeyParameters)aKeyPair.Public).Parameters.G))
            {
                Fail(algorithm + " public key encoding (G test) failed");
            }

            //
            // private key encoding test
            //
//			byte[] privEnc = aKeyPair.Private.GetEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(aKeyPair.Private).GetDerEncoded();

//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			ECPrivateKey        privKey = (ECPrivateKey)keyFac.generatePrivate(privPKCS8);
            ECPrivateKeyParameters privKey = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privEnc);

//			if (!privKey.getS().Equals(((ECPrivateKey)aKeyPair.Private).getS()))
            if (!privKey.D.Equals(((ECPrivateKeyParameters)aKeyPair.Private).D))
            {
//				Fail(algorithm + " private key encoding (S test) failed");
                Fail(algorithm + " private key encoding (D test) failed");
            }

//			if (!privKey.Parameters.getGenerator().Equals(((ECPrivateKey)aKeyPair.Private).Parameters.getGenerator()))
            if (!privKey.Parameters.G.Equals(((ECPrivateKeyParameters)aKeyPair.Private).Parameters.G))
            {
                Fail(algorithm + " private key encoding (G test) failed");
            }
        }
Beispiel #18
0
        protected override TlsSignerCredentials GetECDsaSignerCredentials()
        {
            byte[] certTypes;

            if (mClientExtensions.Contains(ExtensionType.server_certificate_type))
            {
                certTypes = (byte[])mClientExtensions[ExtensionType.server_certificate_type];
            }
            else
            {
                certTypes = new byte[] { CertificateType.X509 };
            }

            foreach (byte b in certTypes)
            {
                if (b == CertificateType.X509)
                {
                    foreach (TlsKeyPair kp in _serverKeys)
                    {
                        if (b != kp.CertType)
                        {
                            continue;
                        }

                        OneKey k = kp.PrivateKey;
                        if (k.HasKeyType((int)GeneralValuesInt.KeyType_EC2) &&
                            k.HasAlgorithm(AlgorithmValues.ECDSA_256))
                        {
                            return(new DefaultTlsSignerCredentials(
                                       mContext,
                                       new Certificate(kp.X509Certificate),
                                       kp.PrivateKey.AsPrivateKey(),
                                       new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                        }
                    }
                }
#if SUPPORT_RPK
                if (b == CertificateType.RawPublicKey)
                {
                    foreach (TlsKeyPair kp in _serverKeys)
                    {
                        if (b != kp.CertType)
                        {
                            continue;
                        }

                        OneKey k = kp.PublicKey;
                        if (k.HasKeyType((int)GeneralValuesInt.KeyType_EC2) &&
                            k.HasAlgorithm(AlgorithmValues.ECDSA_256))
                        {
                            AsymmetricKeyParameter param = k.AsPublicKey();

                            SubjectPublicKeyInfo spi = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(param);

                            return(new DefaultTlsSignerCredentials(mContext, new RawPublicKey(spi), kp.PrivateKey.AsPrivateKey(),
                                                                   new SignatureAndHashAlgorithm(
                                                                       HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                        }
                    }
                }
#endif
#if SUPPORT_TLS_CWT
                if (b == CertificateType.CwtPublicKey)
                {
                    foreach (TlsKeyPair kp in _serverKeys)
                    {
                        if (b != kp.CertType)
                        {
                            continue;
                        }

                        OneKey k = kp.PrivateKey;
                        if (k.HasKeyType((int)GeneralValuesInt.KeyType_EC2) &&
                            k.HasAlgorithm(AlgorithmValues.ECDSA_256))
                        {
                            CwtPublicKey           cwtKey = new CwtPublicKey(kp.PublicCwt.EncodeToBytes());
                            AsymmetricKeyParameter pubKey = kp.PublicCwt.Cnf.CoseKey.AsPublicKey();
                            cwtKey.SetSubjectPublicKeyInfo(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey));

                            return(new DefaultTlsSignerCredentials(
                                       mContext, cwtKey, kp.PrivateKey.AsPrivateKey(),
                                       new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                        }
                    }
                }
#endif
            }

            // If we did not fine appropriate signer credentials - ask for help

            TlsEvent e = new TlsEvent(TlsEvent.EventCode.SignCredentials)
            {
                CipherSuite = KeyExchangeAlgorithm.ECDHE_ECDSA
            };

            EventHandler <TlsEvent> handler = TlsEventHandler;
            if (handler != null)
            {
                handler(this, e);
            }

            if (e.SignerCredentials != null)
            {
                return(e.SignerCredentials);
            }
            throw new TlsFatalAlert(AlertDescription.internal_error);
        }
Beispiel #19
0
        public string CreateAndStoreNewClientCertificate(string subjectName, string pvkPass, X509Certificate2 issuer)
        {
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            // Generate pseudo random number
            var randomGen = new CryptoApiRandomGenerator();
            var random    = new SecureRandom(randomGen);

            // Set certificate serial number
            var serialNumber =
                BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);

            generator.SetSerialNumber(serialNumber);

            // Set certificate subject name
            var subjectDN = new X509Name(subjectName);

            generator.SetSubjectDN(subjectDN);

            // Set issuer subject name
            var issuerDN = new X509Name(issuer.Subject);

            generator.SetIssuerDN(issuerDN);

            // Set certificate validity
            var notBefore = DateTime.UtcNow.Date;

            generator.SetNotBefore(notBefore);
            generator.SetNotAfter(notBefore.AddYears(2));

            // Generate new RSA key pair for certificate
            var keyGeneratorParameters = new KeyGenerationParameters(random, RSAKeyStrength);
            var keyPairGenerator       = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGeneratorParameters);
            var subjectKeyPair = keyPairGenerator.GenerateKeyPair();

            // Import public key into generator
            generator.SetPublicKey(subjectKeyPair.Public);

            var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey);

            // Get key pair from .net issuer certificate
            //var issuerKeyPair = DotNetUtilities.GetKeyPair(issuer.PrivateKey);
            var issuerSerialNumber = new BigInteger(issuer.GetSerialNumber());

            // Sign CA key with serial
            var caKeyIdentifier = new AuthorityKeyIdentifier(
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(issuerKeyPair.Public),
                new GeneralNames(new GeneralName(issuerDN)),
                issuerSerialNumber);

            generator.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                caKeyIdentifier);

            // Create signature factory to sign new cert
            ISignatureFactory signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, issuerKeyPair.Private);

            // Generate new bouncy castle certificate signed by issuer
            var newCertificate = generator.Generate(signatureFactory);

            var    store        = new Pkcs12Store();
            string friendlyName = newCertificate.SubjectDN.ToString().Split('=')[1];

            var certificateEntry = new X509CertificateEntry(newCertificate);

            // Set certificate
            store.SetCertificateEntry(friendlyName, certificateEntry);
            // Set private key
            store.SetKeyEntry(
                friendlyName,
                new AsymmetricKeyEntry(subjectKeyPair.Private),
                new X509CertificateEntry[] { certificateEntry });

            var privatePath = @".\certs\" + $"{friendlyName}.pfx";
            var publicPath  = @".\certs\" + $"{friendlyName}.cer";

            using (var stream = new MemoryStream())
            {
                // Convert bouncy castle cert => .net cert
                store.Save(stream, pvkPass.ToCharArray(), random);
                var dotNetCertificate = new X509Certificate2(
                    stream.ToArray(),
                    pvkPass,
                    X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);

                // Extract public part to store in server storage
                var publicCert = dotNetCertificate.Export(X509ContentType.Cert);
                // Extract private parameters to export into .pfx for distribution
                var privateCert = dotNetCertificate.Export(X509ContentType.Pfx, pvkPass);

                dotNetCertificate.Reset();
                dotNetCertificate.Import(publicCert);

                // Store public cert info in storage
                using (var storage = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                {
                    storage.Open(OpenFlags.ReadWrite);
                    storage.Add(dotNetCertificate);
                    storage.Close();
                }

                dotNetCertificate.Dispose();

                // Write private parameters to .pfx file to install at client
                File.WriteAllBytes(privatePath, privateCert);
                File.WriteAllBytes(publicPath, publicCert);
            }

            return(privatePath);
        }
        /// <inheritdoc/>
        public async Task <(X509Certificate?Certificate, RsaKeyParameters?Key)> GetLocalCertificateAsync(ApplicationDescription applicationDescription, ILogger?logger = null, CancellationToken token = default)
        {
            if (applicationDescription == null)
            {
                throw new ArgumentNullException(nameof(applicationDescription));
            }

            string?applicationUri = applicationDescription.ApplicationUri;

            if (string.IsNullOrEmpty(applicationUri))
            {
                throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'.");
            }

            string?subjectName = null;
            string?hostName    = null;
            string?appName     = null;

            UriBuilder appUri = new UriBuilder(applicationUri);

            if (appUri.Scheme == "http" && !string.IsNullOrEmpty(appUri.Host))
            {
                var path = appUri.Path.Trim('/');
                if (!string.IsNullOrEmpty(path))
                {
                    hostName    = appUri.Host;
                    appName     = path;
                    subjectName = $"CN={appName},DC={hostName}";
                }
            }

            if (appUri.Scheme == "urn")
            {
                var parts = appUri.Path.Split(new[] { ':' }, 2);
                if (parts.Length == 2)
                {
                    hostName    = parts[0];
                    appName     = parts[1];
                    subjectName = $"CN={appName},DC={hostName}";
                }
            }

            if (subjectName == null)
            {
                throw new ArgumentOutOfRangeException(nameof(applicationDescription), "Expecting ApplicationUri in the form of 'http://{hostname}/{appname}' -or- 'urn:{hostname}:{appname}'.");
            }

            var crt = default(X509Certificate);
            var key = default(RsaKeyParameters);

            // Build 'own/certs' certificate store.
            var ownCerts     = new Org.BouncyCastle.Utilities.Collections.HashSet();
            var ownCertsInfo = new DirectoryInfo(Path.Combine(_pkiPath, "own", "certs"));

            if (ownCertsInfo.Exists)
            {
                foreach (var info in ownCertsInfo.EnumerateFiles())
                {
                    using (var crtStream = info.OpenRead())
                    {
                        var c = _certParser.ReadCertificate(crtStream);
                        if (c != null)
                        {
                            ownCerts.Add(c);
                        }
                    }
                }
            }

            IX509Store ownCertStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(ownCerts));

            // Select the newest certificate that matches by subject name.
            var selector = new X509CertStoreSelector()
            {
                Subject = new X509Name(subjectName)
            };

            crt = ownCertStore.GetMatches(selector).OfType <X509Certificate>().OrderBy(c => c.NotBefore).LastOrDefault();
            if (crt != null)
            {
                // If certificate found, verify alt-name, and retrieve private key.
                var asn1OctetString = crt.GetExtensionValue(X509Extensions.SubjectAlternativeName);
                if (asn1OctetString != null)
                {
                    var          asn1Object = X509ExtensionUtilities.FromExtensionValue(asn1OctetString);
                    GeneralNames gns        = GeneralNames.GetInstance(asn1Object);
                    if (gns.GetNames().Any(n => n.TagNo == GeneralName.UniformResourceIdentifier && n.Name.ToString() == applicationUri))
                    {
                        var ki = new FileInfo(Path.Combine(_pkiPath, "own", "private", $"{crt.SerialNumber}.key"));
                        if (ki.Exists)
                        {
                            using (var keyStream = new StreamReader(ki.OpenRead()))
                            {
                                var keyReader = new PemReader(keyStream);
                                var keyPair   = keyReader.ReadObject() as AsymmetricCipherKeyPair;
                                if (keyPair != null)
                                {
                                    key = keyPair.Private as RsaKeyParameters;
                                }
                            }
                        }
                    }
                }
            }

            // If certificate and key are found, return to caller.
            if (crt != null && key != null)
            {
                logger?.LogTrace($"Found certificate with subject alt name '{applicationUri}'.");
                return(crt, key);
            }

            if (!CreateLocalCertificateIfNotExist)
            {
                return(null, null);
            }

            // Create new certificate
            var subjectDN = new X509Name(subjectName);

            // Create a keypair.
            var kp = await Task.Run <AsymmetricCipherKeyPair>(() =>
            {
                RsaKeyPairGenerator kg = new RsaKeyPairGenerator();
                kg.Init(new KeyGenerationParameters(_rng, 2048));
                return(kg.GenerateKeyPair());
            });

            key = kp.Private as RsaPrivateCrtKeyParameters;

            // Create a certificate.
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
            var subjectSN = BigInteger.ProbablePrime(120, _rng);

            cg.SetSerialNumber(subjectSN);
            cg.SetSubjectDN(subjectDN);
            cg.SetIssuerDN(subjectDN);
            cg.SetNotBefore(DateTime.Now.Date.ToUniversalTime());
            cg.SetNotAfter(DateTime.Now.Date.ToUniversalTime().AddYears(25));
            cg.SetPublicKey(kp.Public);

            cg.AddExtension(
                X509Extensions.BasicConstraints.Id,
                true,
                new BasicConstraints(false));

            cg.AddExtension(
                X509Extensions.SubjectKeyIdentifier.Id,
                false,
                new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public)));

            cg.AddExtension(
                X509Extensions.AuthorityKeyIdentifier.Id,
                false,
                new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(kp.Public), new GeneralNames(new GeneralName(subjectDN)), subjectSN));

            cg.AddExtension(
                X509Extensions.SubjectAlternativeName,
                false,
                new GeneralNames(new[] { new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri), new GeneralName(GeneralName.DnsName, hostName) }));

            cg.AddExtension(
                X509Extensions.KeyUsage,
                true,
                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature | KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

            cg.AddExtension(
                X509Extensions.ExtendedKeyUsage,
                true,
                new ExtendedKeyUsage(KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth));

            crt = cg.Generate(new Asn1SignatureFactory("SHA256WITHRSA", key, _rng));

            logger?.LogTrace($"Created certificate with subject alt name '{applicationUri}'.");

            var keyInfo = new FileInfo(Path.Combine(_pkiPath, "own", "private", $"{crt.SerialNumber}.key"));

            if (!keyInfo.Directory.Exists)
            {
                Directory.CreateDirectory(keyInfo.DirectoryName);
            }
            else if (keyInfo.Exists)
            {
                keyInfo.Delete();
            }

            using (var keystream = new StreamWriter(keyInfo.OpenWrite()))
            {
                var pemwriter = new PemWriter(keystream);
                pemwriter.WriteObject(key);
            }

            var crtInfo = new FileInfo(Path.Combine(_pkiPath, "own", "certs", $"{crt.SerialNumber}.crt"));

            if (!crtInfo.Directory.Exists)
            {
                Directory.CreateDirectory(crtInfo.DirectoryName);
            }
            else if (crtInfo.Exists)
            {
                crtInfo.Delete();
            }

            using (var crtstream = new StreamWriter(crtInfo.OpenWrite()))
            {
                var pemwriter = new PemWriter(crtstream);
                pemwriter.WriteObject(crt);
            }

            return(crt, key);
        }
Beispiel #21
0
 public void SetPublicKey(AsymmetricKeyParameter publicKey)
 {
     tbsGen.SetSubjectPublicKeyInfo(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey));
 }
Beispiel #22
0
        private void generationTest()
        {
            byte[]  data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
            ISigner s    = SignerUtilities.GetSigner("GOST3410");

            IAsymmetricCipherKeyPairGenerator g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            IAsymmetricCipherKeyPair p = g.GenerateKeyPair();

            IAsymmetricKeyParameter sKey = p.Private;
            IAsymmetricKeyParameter vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            byte[] sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // default initialisation test
            //
            s = SignerUtilities.GetSigner("GOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("GOST3410");

            // TODO This is supposed to be a 'default initialisation' test, but don't have a factory
            // These values are defaults from JCE provider
            g.Init(
                new Gost3410KeyGenerationParameters(
                    new SecureRandom(),
                    CryptoProObjectIdentifiers.GostR3410x94CryptoProA));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("GOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("GOST3410 verification failed");
            }

            //
            // encoded test
            //
            //KeyFactory f = KeyFactory.getInstance("GOST3410");
            //X509EncodedKeySpec  x509s = new X509EncodedKeySpec(vKey.GetEncoded());
            //Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)f.generatePublic(x509s);
            byte[] vKeyEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(vKey).GetDerEncoded();
            Gost3410PublicKeyParameters k1 = (Gost3410PublicKeyParameters)
                                             PublicKeyFactory.CreateKey(vKeyEnc);

            if (!k1.Y.Equals(((Gost3410PublicKeyParameters)vKey).Y))
            {
                Fail("public number not decoded properly");
            }

            //PKCS8EncodedKeySpec  pkcs8 = new PKCS8EncodedKeySpec(sKey.GetEncoded());
            //Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)f.generatePrivate(pkcs8);
            byte[] sKeyEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(sKey).GetDerEncoded();
            Gost3410PrivateKeyParameters k2 = (Gost3410PrivateKeyParameters)
                                              PrivateKeyFactory.CreateKey(sKeyEnc);

            if (!k2.X.Equals(((Gost3410PrivateKeyParameters)sKey).X))
            {
                Fail("private number not decoded properly");
            }

            //
            // ECGOST3410 generation test
            //
            s = SignerUtilities.GetSigner("ECGOST3410");
            g = GeneratorUtilities.GetKeyPairGenerator("ECGOST3410");

            IBigInteger mod_p = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564821041");             //p

            ECCurve curve = new FPCurve(
                mod_p,                                                                                            // p
                new BigInteger("7"),                                                                              // a
                new BigInteger("43308876546767276905765904595650931995942111794451039583252968842033849580414")); // b

            ECDomainParameters ecSpec = new ECDomainParameters(
                curve,
                curve.CreatePoint(
                    new BigInteger("2"),
                    new BigInteger("4018974056539037503335449422937059775635739389905545080690979365213431566280"),
                    false),
                new BigInteger("57896044618658097711785492504343953927082934583725450622380973592137631069619"));                 // q

            g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

            p = g.GenerateKeyPair();

            sKey = p.Private;
            vKey = p.Public;

            s.Init(true, sKey);

            s.BlockUpdate(data, 0, data.Length);

            sigBytes = s.GenerateSignature();

            s = SignerUtilities.GetSigner("ECGOST3410");

            s.Init(false, vKey);

            s.BlockUpdate(data, 0, data.Length);

            if (!s.VerifySignature(sigBytes))
            {
                Fail("ECGOST3410 verification failed");
            }
        }
Beispiel #23
0
            public virtual TlsCredentials GetClientCredentials(CertificateRequest certificateRequest)
            {
                if (certificateRequest.CertificateTypes == null ||
                    !Arrays.Contains(certificateRequest.CertificateTypes, ClientCertificateType.ecdsa_sign))
                {
                    return(null);
                }

                if (TlsKey != null)
                {
                    if (TlsKey.CertType == CertificateType.X509)
                    {
                        return(new DefaultTlsSignerCredentials(_mContext, new Certificate(TlsKey.X509Certificate), TlsKey.PrivateKey.AsPrivateKey(),
                                                               new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                    }
#if SUPPORT_RPK
                    else if (TlsKey.CertType == CertificateType.RawPublicKey)
                    {
                        OneKey k = TlsKey.PrivateKey;
                        if (k.HasKeyType((int)GeneralValuesInt.KeyType_EC2) &&
                            k.HasAlgorithm(AlgorithmValues.ECDSA_256))
                        {
                            X9ECParameters         p          = k.GetCurve();
                            ECDomainParameters     parameters = new ECDomainParameters(p.Curve, p.G, p.N, p.H);
                            ECPrivateKeyParameters privKey    = new ECPrivateKeyParameters("ECDSA", ConvertBigNum(k[CoseKeyParameterKeys.EC_D]), parameters);

                            ECPoint point = k.GetPoint();
                            ECPublicKeyParameters param = new ECPublicKeyParameters("ECDSA", point, /*parameters*/ SecObjectIdentifiers.SecP256r1);

                            SubjectPublicKeyInfo spi = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(param);

                            return(new DefaultTlsSignerCredentials(_mContext, new RawPublicKey(spi), privKey, new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                        }
                    }
#endif
#if SUPPORT_TLS_CWT
                    else if (TlsKey.CertType == CertificateType.CwtPublicKey)
                    {
                        OneKey k = TlsKey.PublicCwt.Cnf.Key;
                        if (k.HasKeyType((int)GeneralValuesInt.KeyType_EC2) &&
                            k.HasAlgorithm(AlgorithmValues.ECDSA_256))
                        {
                            AsymmetricKeyParameter privKey = TlsKey.PrivateKey.AsPrivateKey();

                            return(new DefaultTlsSignerCredentials(_mContext, new CwtPublicKey(TlsKey.PublicCwt.EncodeToBytes()), privKey,
                                                                   new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.ecdsa)));
                        }
                    }
#endif
                }

                // If we did not fine appropriate signer credentials - ask for help

                TlsEvent e = new TlsEvent(TlsEvent.EventCode.SignCredentials)
                {
                    CipherSuite = KeyExchangeAlgorithm.ECDHE_ECDSA
                };

                EventHandler <TlsEvent> handler = TlsEventHandler;
                if (handler != null)
                {
                    handler(this, e);
                }

                if (e.SignerCredentials != null)
                {
                    return(e.SignerCredentials);
                }
                throw new TlsFatalAlert(AlertDescription.internal_error);
            }
Beispiel #24
0
        /**
         * Verifies the supplied signed DGC. If verification is successful the method returns the contained HCERT
         * (eu_hcert_v1) in its binary representation.
         *
         * @throws SignatureException
         *           if signature validation fails
         * @throws CertificateExpiredException
         *           if the DGC has expired
         */
        public byte[] Verify(byte[] signedDGC, SignedDGC vacProof)
        {
            CoseSign1_Object obj = CoseSign1_Object.Decode(signedDGC);

            byte[] kid     = obj.GetKeyIdentifier();
            string country = obj.GetCwt().GetIssuer();

            vacProof.IssuingCountry = country;

            if (kid == null && country == null)
            {
                throw new Exception("Signed object does not contain kid or country - cannot find certificate");
            }

            List <AsymmetricKeyParameter> certs = this.certificateProvider.GetCertificates(country, kid);

            foreach (AsymmetricKeyParameter cert in certs)
            {
                Console.WriteLine("Attempting HCERT signature verification using certificate");// '{0}'", cert.Subject);//getSubjectX500Principal().getName()) ;

                try {
                    byte[] key = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(cert).GetEncoded();
                    obj.VerifySignature(key);
                    Console.WriteLine("HCERT signature verification succeeded using certificate");// '{0}'", cert.Subject); //getSubjectX500Principal().getName());
                }
                catch (Exception e)
                {
                    Console.WriteLine("HCERT signature verification failed using certificate '{0}' - {1}",
                                      cert, e.Message, e);
                    continue;
                }

                // OK, before we are done - let's ensure that the HCERT hasn't expired.
                CWT cwt = obj.GetCwt();

                DateTime expiration = cwt.GetExpiration();
                if (expiration != null)
                {
                    if (DateTime.UtcNow.CompareTo(expiration) >= 0)
                    {
                        throw new CertificateExpiredException("Signed HCERT has expired");
                    }
                }
                else
                {
                    Console.WriteLine("Signed HCERT did not contain an expiration time - assuming it is valid");
                }
                vacProof.ExpirationDate = expiration;
                vacProof.IssuedDate     = cwt.GetIssuedAt();
                // OK, everything looks fine - return the DGC
                return(cwt.GetDgcV1());
            }

            if (certs.Count <= 0)
            {
                throw new Exception("No signer certificates could be found");
            }
            else
            {
                throw new Exception("Signature verification failed for all attempted keys");
            }
        }
Beispiel #25
0
        // Only the ctor should be calling with isAuthority = true
        // if isAuthority, value for isMachineCert doesn't matter
        private X509CertificateContainer CreateCertificate(bool isAuthority, bool isMachineCert, X509Certificate signingCertificate, CertificateCreationSettings certificateCreationSettings)
        {
            if (certificateCreationSettings == null)
            {
                if (isAuthority)
                {
                    certificateCreationSettings = new CertificateCreationSettings();
                }
                else
                {
                    throw new Exception("Parameter certificateCreationSettings cannot be null when isAuthority is false");
                }
            }

            // Set to default cert creation settings if not set
            if (certificateCreationSettings.ValidityNotBefore == default(DateTime))
            {
                certificateCreationSettings.ValidityNotBefore = _defaultValidityNotBefore;
            }
            if (certificateCreationSettings.ValidityNotAfter == default(DateTime))
            {
                certificateCreationSettings.ValidityNotAfter = _defaultValidityNotAfter;
            }

            if (!isAuthority ^ (signingCertificate != null))
            {
                throw new ArgumentException("Either isAuthority == true or signingCertificate is not null");
            }
            string subject = certificateCreationSettings.Subject;

            // If certificateCreationSettings.SubjectAlternativeNames == null, then we should add exactly one SubjectAlternativeName == Subject
            // so that the default certificate generated is compatible with mainline scenarios
            // However, if certificateCreationSettings.SubjectAlternativeNames == string[0], then allow this as this is a legit scenario we want to test out
            if (certificateCreationSettings.SubjectAlternativeNames == null)
            {
                certificateCreationSettings.SubjectAlternativeNames = new string[1] {
                    subject
                };
            }

            string[] subjectAlternativeNames = certificateCreationSettings.SubjectAlternativeNames;

            if (!isAuthority && string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("Certificate Subject must not be an empty string or only whitespace", "creationSettings.Subject");
            }

            EnsureInitialized();

            s_certGenerator.Reset();
            s_certGenerator.SetSignatureAlgorithm(_signatureAlthorithm);

            X509Name authorityX509Name = CreateX509Name(_authorityCanonicalName);
            var      serialNum         = new BigInteger(64 /*sizeInBits*/, _random).Abs();

            var keyPair = isAuthority ? _authorityKeyPair : _keyPairGenerator.GenerateKeyPair();

            if (isAuthority)
            {
                s_certGenerator.SetIssuerDN(authorityX509Name);
                s_certGenerator.SetSubjectDN(authorityX509Name);

                var authorityKeyIdentifier = new AuthorityKeyIdentifier(
                    SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(_authorityKeyPair.Public),
                    new GeneralNames(new GeneralName(authorityX509Name)),
                    serialNum);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier);
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyCertSign | X509KeyUsage.KeyEncipherment | X509KeyUsage.CrlSign));
            }
            else
            {
                X509Name subjectName = CreateX509Name(subject);
                s_certGenerator.SetIssuerDN(PrincipalUtilities.GetSubjectX509Principal(signingCertificate));
                s_certGenerator.SetSubjectDN(subjectName);

                s_certGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(_authorityKeyPair.Public));
                s_certGenerator.AddExtension(X509Extensions.KeyUsage, false, new KeyUsage(X509KeyUsage.DigitalSignature | X509KeyUsage.KeyAgreement | X509KeyUsage.KeyEncipherment));
            }

            s_certGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.Public));

            s_certGenerator.SetSerialNumber(serialNum);
            s_certGenerator.SetNotBefore(certificateCreationSettings.ValidityNotBefore);
            s_certGenerator.SetNotAfter(certificateCreationSettings.ValidityNotAfter);
            s_certGenerator.SetPublicKey(keyPair.Public);

            s_certGenerator.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isAuthority));
            s_certGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPClientAuth));

            if (!isAuthority)
            {
                if (isMachineCert)
                {
                    List <Asn1Encodable> subjectAlternativeNamesAsAsn1EncodableList = new List <Asn1Encodable>();

                    // All endpoints should also be in the Subject Alt Names
                    for (int i = 0; i < subjectAlternativeNames.Length; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                        {
                            // Machine certs can have additional DNS names
                            subjectAlternativeNamesAsAsn1EncodableList.Add(new GeneralName(GeneralName.DnsName, subjectAlternativeNames[i]));
                        }
                    }

                    s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList.ToArray()));
                }
                else
                {
                    if (subjectAlternativeNames.Length > 1)
                    {
                        var subjectAlternativeNamesAsAsn1EncodableList = new Asn1EncodableVector();

                        // Only add a SAN for the user if there are any
                        for (int i = 1; i < subjectAlternativeNames.Length; i++)
                        {
                            if (!string.IsNullOrWhiteSpace(subjectAlternativeNames[i]))
                            {
                                Asn1EncodableVector otherNames = new Asn1EncodableVector();
                                otherNames.Add(new DerObjectIdentifier(_upnObjectId));
                                otherNames.Add(new DerTaggedObject(true, 0, new DerUtf8String(subjectAlternativeNames[i])));

                                Asn1Object genName = new DerTaggedObject(false, 0, new DerSequence(otherNames));

                                subjectAlternativeNamesAsAsn1EncodableList.Add(genName);
                            }
                        }
                        s_certGenerator.AddExtension(X509Extensions.SubjectAlternativeName, true, new DerSequence(subjectAlternativeNamesAsAsn1EncodableList));
                    }
                }
            }

            // Our CRL Distribution Point has the serial number in the query string to fool Windows into doing a fresh query
            // rather than using a cached copy of the CRL in the case where the CRL has been previously accessed before
            var crlDistributionPoints = new DistributionPoint[2] {
                new DistributionPoint(new DistributionPointName(
                                          new GeneralNames(new GeneralName(
                                                               GeneralName.UniformResourceIdentifier, string.Format("{0}?serialNum={1}", _crlUri, serialNum.ToString(radix: 16))))),
                                      null,
                                      null),
                new DistributionPoint(new DistributionPointName(
                                          new GeneralNames(new GeneralName(
                                                               GeneralName.UniformResourceIdentifier, string.Format("{0}?serialNum={1}", _crlUri, serialNum.ToString(radix: 16))))),
                                      null,
                                      new GeneralNames(new GeneralName(authorityX509Name)))
            };
            var revocationListExtension = new CrlDistPoint(crlDistributionPoints);

            s_certGenerator.AddExtension(X509Extensions.CrlDistributionPoints, false, revocationListExtension);

            X509Certificate cert = s_certGenerator.Generate(_authorityKeyPair.Private, _random);

            switch (certificateCreationSettings.ValidityType)
            {
            case CertificateValidityType.Revoked:
                RevokeCertificateBySerialNumber(serialNum.ToString(radix: 16));
                break;

            case CertificateValidityType.Expired:
                break;

            default:
                EnsureCertificateIsValid(cert);
                break;
            }

            // For now, given that we don't know what format to return it in, preserve the formats so we have
            // the flexibility to do what we need to

            X509CertificateContainer container = new X509CertificateContainer();

            X509CertificateEntry[] chain = new X509CertificateEntry[1];
            chain[0] = new X509CertificateEntry(cert);

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry(
                certificateCreationSettings.FriendlyName != null ? certificateCreationSettings.FriendlyName : string.Empty,
                new AsymmetricKeyEntry(keyPair.Private),
                chain);

            using (MemoryStream stream = new MemoryStream())
            {
                store.Save(stream, _password.ToCharArray(), _random);
                container.Pfx = stream.ToArray();
            }

            X509Certificate2 outputCert;

            if (isAuthority)
            {
                // don't hand out the private key for the cert when it's the authority
                outputCert = new X509Certificate2(cert.GetEncoded());
            }
            else
            {
                // Otherwise, allow encode with the private key. note that X509Certificate2.RawData will not provide the private key
                // you will have to re-export this cert if needed
                outputCert = new X509Certificate2(container.Pfx, _password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            }

            container.Subject             = subject;
            container.InternalCertificate = cert;
            container.Certificate         = outputCert;
            container.Thumbprint          = outputCert.Thumbprint;

            Trace.WriteLine("[CertificateGenerator] generated a certificate:");
            Trace.WriteLine(string.Format("    {0} = {1}", "isAuthority", isAuthority));
            if (!isAuthority)
            {
                Trace.WriteLine(string.Format("    {0} = {1}", "Signed by", signingCertificate.SubjectDN));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject (CN) ", subject));
                Trace.WriteLine(string.Format("    {0} = {1}", "Subject Alt names ", string.Join(", ", subjectAlternativeNames)));
                Trace.WriteLine(string.Format("    {0} = {1}", "Friendly Name ", certificateCreationSettings.FriendlyName));
            }
            Trace.WriteLine(string.Format("    {0} = {1}", "HasPrivateKey:", outputCert.HasPrivateKey));
            Trace.WriteLine(string.Format("    {0} = {1}", "Thumbprint", outputCert.Thumbprint));
            Trace.WriteLine(string.Format("    {0} = {1}", "CertificateValidityType", certificateCreationSettings.ValidityType));

            return(container);
        }
        private static PemObject CreatePemObject(object obj)
        {
            //IL_0008: Unknown result type (might be due to invalid IL or missing references)
            //IL_007a: Unknown result type (might be due to invalid IL or missing references)
            //IL_00b0: Unknown result type (might be due to invalid IL or missing references)
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (obj is AsymmetricCipherKeyPair)
            {
                return(CreatePemObject(((AsymmetricCipherKeyPair)obj).Private));
            }
            if (obj is PemObject)
            {
                return((PemObject)obj);
            }
            if (obj is PemObjectGenerator)
            {
                return(((PemObjectGenerator)obj).Generate());
            }
            string type;

            byte[] content;
            if (obj is X509Certificate)
            {
                type = "CERTIFICATE";
                try
                {
                    content = ((X509Certificate)obj).GetEncoded();
                }
                catch (CertificateEncodingException ex)
                {
                    throw new IOException("Cannot Encode object: " + ((global::System.Exception)ex).ToString());
                }
            }
            else if (obj is X509Crl)
            {
                type = "X509 CRL";
                try
                {
                    content = ((X509Crl)obj).GetEncoded();
                }
                catch (CrlException ex2)
                {
                    throw new IOException("Cannot Encode object: " + ((global::System.Exception)ex2).ToString());
                }
            }
            else if (obj is AsymmetricKeyParameter)
            {
                AsymmetricKeyParameter asymmetricKeyParameter = (AsymmetricKeyParameter)obj;
                if (asymmetricKeyParameter.IsPrivate)
                {
                    content = EncodePrivateKey(asymmetricKeyParameter, out var keyType);
                    type    = keyType + " PRIVATE KEY";
                }
                else
                {
                    type    = "PUBLIC KEY";
                    content = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(asymmetricKeyParameter).GetDerEncoded();
                }
            }
            else if (obj is IX509AttributeCertificate)
            {
                type    = "ATTRIBUTE CERTIFICATE";
                content = ((X509V2AttributeCertificate)obj).GetEncoded();
            }
            else if (obj is Pkcs10CertificationRequest)
            {
                type    = "CERTIFICATE REQUEST";
                content = ((Pkcs10CertificationRequest)obj).GetEncoded();
            }
            else
            {
                if (!(obj is Org.BouncyCastle.Asn1.Cms.ContentInfo))
                {
                    throw new PemGenerationException("Object type not supported: " + Platform.GetTypeName(obj));
                }
                type    = "PKCS7";
                content = ((Org.BouncyCastle.Asn1.Cms.ContentInfo)obj).GetEncoded();
            }
            return(new PemObject(type, content));
        }
 private byte[] MakeCertificateFromCSR(string CSR, AsymmetricCipherKeyPair rootKeyPair, X509Name rootSubject)
 {
     byte[] encoded;
     try
     {
         Pkcs10CertificationRequest pkcs10CertificationRequest = (Pkcs10CertificationRequest)(new PemReader(new StringReader(CSR))).ReadObject();
         AsymmetricKeyParameter     @private = rootKeyPair.Private;
         AsymmetricKeyParameter     @public  = rootKeyPair.Public;
         X509V3CertificateGenerator x509V3CertificateGenerator = new X509V3CertificateGenerator();
         x509V3CertificateGenerator.Reset();
         if (this.SerialNumber != -9223372036854775808L)
         {
             x509V3CertificateGenerator.SetSerialNumber(new BigInteger(this.SerialNumber.ToString()));
         }
         else
         {
             DateTime now = DateTime.Now;
             x509V3CertificateGenerator.SetSerialNumber(new BigInteger(128, new Random(now.Millisecond + Environment.TickCount)));
         }
         x509V3CertificateGenerator.SetIssuerDN(rootSubject);
         x509V3CertificateGenerator.SetNotBefore(this.ValidFrom.ToUniversalTime());
         x509V3CertificateGenerator.SetNotAfter(this.ValidTo.ToUniversalTime());
         x509V3CertificateGenerator.SetSubjectDN(pkcs10CertificationRequest.GetCertificationRequestInfo().Subject);
         x509V3CertificateGenerator.SetPublicKey(pkcs10CertificationRequest.GetPublicKey());
         x509V3CertificateGenerator.SetSignatureAlgorithm(string.Concat(this.SignatureAlgorithm.ToString(), "Encryption"));
         x509V3CertificateGenerator.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pkcs10CertificationRequest.GetPublicKey())));
         x509V3CertificateGenerator.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(@public)));
         int extensionType = 0;
         Asn1EncodableVector asn1EncodableVectors = new Asn1EncodableVector(new Asn1Encodable[0]);
         foreach (ExtensionInfo extension in this.Extensions.extensionInfo)
         {
             if (!extension.ExtendedKeyUsage)
             {
                 extensionType |= (int)extension.ExtensionType;
             }
             if (!extension.ExtendedKeyUsage)
             {
                 continue;
             }
             asn1EncodableVectors.Add(new Asn1Encodable[] { (Asn1Encodable)extension.ExtensionType });
         }
         if (extensionType != 0)
         {
             x509V3CertificateGenerator.AddExtension(X509Extensions.KeyUsage, this.Extensions.KeyUsageIsCritical, new KeyUsage(extensionType));
         }
         if (asn1EncodableVectors.Count > 0)
         {
             x509V3CertificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage, this.Extensions.EnhancedKeyUsageIsCritical, ExtendedKeyUsage.GetInstance(new DerSequence(asn1EncodableVectors)));
         }
         X509Certificate x509Certificate = x509V3CertificateGenerator.Generate(@private, this.GetSecureRandom());
         x509Certificate.Verify(@public);
         encoded = x509Certificate.GetEncoded();
     }
     catch
     {
         throw;
     }
     return(encoded);
 }
Beispiel #28
0
        public override void PerformTest()
        {
            X509CertificateParser certParser = new X509CertificateParser();
            X509CrlParser         crlParser  = new X509CrlParser();

            X509Certificate rootCert  = certParser.ReadCertificate(CertPathTest.rootCertBin);
            X509Certificate interCert = certParser.ReadCertificate(CertPathTest.interCertBin);
            X509Certificate finalCert = certParser.ReadCertificate(CertPathTest.finalCertBin);
            X509Crl         rootCrl   = crlParser.ReadCrl(CertPathTest.rootCrlBin);
            X509Crl         interCrl  = crlParser.ReadCrl(CertPathTest.interCrlBin);

            // Testing CollectionCertStore generation from List
            IList certList = new ArrayList();

            certList.Add(rootCert);
            certList.Add(interCert);
            certList.Add(finalCert);

            IX509Store certStore = X509StoreFactory.Create(
                "Certificate/Collection",
                new X509CollectionStoreParameters(certList));

            // set default to be the same as for SUN X500 name
            X509Name.DefaultReverse = true;

            // Searching for rootCert by subjectDN

            X509CertStoreSelector targetConstraints = new X509CertStoreSelector();

            targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert);
            IList certs = new ArrayList(certStore.GetMatches(targetConstraints));

            if (certs.Count != 1 || !certs.Contains(rootCert))
            {
                Fail("rootCert not found by subjectDN");
            }

            // Searching for rootCert by subjectDN encoded as byte
            targetConstraints         = new X509CertStoreSelector();
            targetConstraints.Subject = PrincipalUtilities.GetSubjectX509Principal(rootCert);
            certs = new ArrayList(certStore.GetMatches(targetConstraints));
            if (certs.Count != 1 || !certs.Contains(rootCert))
            {
                Fail("rootCert not found by encoded subjectDN");
            }

            X509Name.DefaultReverse = false;

            // Searching for rootCert by public key encoded as byte
            targetConstraints = new X509CertStoreSelector();
            targetConstraints.SubjectPublicKey =
                SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(rootCert.GetPublicKey());
            certs = new ArrayList(certStore.GetMatches(targetConstraints));
            if (certs.Count != 1 || !certs.Contains(rootCert))
            {
                Fail("rootCert not found by encoded public key");
            }

            // Searching for interCert by issuerDN
            targetConstraints        = new X509CertStoreSelector();
            targetConstraints.Issuer = PrincipalUtilities.GetSubjectX509Principal(rootCert);
            certs = new ArrayList(certStore.GetMatches(targetConstraints));
            if (certs.Count != 2)
            {
                Fail("did not found 2 certs");
            }
            if (!certs.Contains(rootCert))
            {
                Fail("rootCert not found");
            }
            if (!certs.Contains(interCert))
            {
                Fail("interCert not found");
            }

            // Searching for rootCrl by issuerDN
            IList crlList = new ArrayList();

            crlList.Add(rootCrl);
            crlList.Add(interCrl);
            IX509Store store = X509StoreFactory.Create(
                "CRL/Collection",
                new X509CollectionStoreParameters(crlList));

            X509CrlStoreSelector targetConstraintsCRL = new X509CrlStoreSelector();

            ArrayList issuers = new ArrayList();

            issuers.Add(rootCrl.IssuerDN);
            targetConstraintsCRL.Issuers = issuers;

            IList crls = new ArrayList(store.GetMatches(targetConstraintsCRL));

            if (crls.Count != 1 || !crls.Contains(rootCrl))
            {
                Fail("rootCrl not found");
            }

            crls = new ArrayList(certStore.GetMatches(targetConstraintsCRL));
            if (crls.Count != 0)
            {
                Fail("error using wrong selector (CRL)");
            }
            certs = new ArrayList(store.GetMatches(targetConstraints));
            if (certs.Count != 0)
            {
                Fail("error using wrong selector (certs)");
            }
            // Searching for attribute certificates
            X509V2AttributeCertificate attrCert  = new X509V2AttributeCertificate(AttrCertTest.attrCert);
            IX509AttributeCertificate  attrCert2 = new X509V2AttributeCertificate(AttrCertTest.certWithBaseCertificateID);

            IList attrList = new ArrayList();

            attrList.Add(attrCert);
            attrList.Add(attrCert2);
            store = X509StoreFactory.Create(
                "AttributeCertificate/Collection",
                new X509CollectionStoreParameters(attrList));

            X509AttrCertStoreSelector attrSelector = new X509AttrCertStoreSelector();

            attrSelector.Holder = attrCert.Holder;
            if (!attrSelector.Holder.Equals(attrCert.Holder))
            {
                Fail("holder get not correct");
            }
            IList attrs = new ArrayList(store.GetMatches(attrSelector));

            if (attrs.Count != 1 || !attrs.Contains(attrCert))
            {
                Fail("attrCert not found on holder");
            }
            attrSelector.Holder = attrCert2.Holder;
            if (attrSelector.Holder.Equals(attrCert.Holder))
            {
                Fail("holder get not correct");
            }
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 1 || !attrs.Contains(attrCert2))
            {
                Fail("attrCert2 not found on holder");
            }
            attrSelector        = new X509AttrCertStoreSelector();
            attrSelector.Issuer = attrCert.Issuer;
            if (!attrSelector.Issuer.Equals(attrCert.Issuer))
            {
                Fail("issuer get not correct");
            }
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 1 || !attrs.Contains(attrCert))
            {
                Fail("attrCert not found on issuer");
            }
            attrSelector.Issuer = attrCert2.Issuer;
            if (attrSelector.Issuer.Equals(attrCert.Issuer))
            {
                Fail("issuer get not correct");
            }
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 1 || !attrs.Contains(attrCert2))
            {
                Fail("attrCert2 not found on issuer");
            }
            attrSelector = new X509AttrCertStoreSelector();
            attrSelector.AttributeCert = attrCert;
            if (!attrSelector.AttributeCert.Equals(attrCert))
            {
                Fail("attrCert get not correct");
            }
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 1 || !attrs.Contains(attrCert))
            {
                Fail("attrCert not found on attrCert");
            }
            attrSelector = new X509AttrCertStoreSelector();
            attrSelector.SerialNumber = attrCert.SerialNumber;
            if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber))
            {
                Fail("serial number get not correct");
            }
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 1 || !attrs.Contains(attrCert))
            {
                Fail("attrCert not found on serial number");
            }
            attrSelector = (X509AttrCertStoreSelector)attrSelector.Clone();
            if (!attrSelector.SerialNumber.Equals(attrCert.SerialNumber))
            {
                Fail("serial number get not correct");
            }
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 1 || !attrs.Contains(attrCert))
            {
                Fail("attrCert not found on serial number");
            }

            attrSelector = new X509AttrCertStoreSelector();
            attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore);
            if (attrSelector.AttributeCertificateValid.Value != attrCert.NotBefore)
            {
                Fail("valid get not correct");
            }
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 1 || !attrs.Contains(attrCert))
            {
                Fail("attrCert not found on valid");
            }
            attrSelector = new X509AttrCertStoreSelector();
            attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotBefore.AddMilliseconds(-100));
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 0)
            {
                Fail("attrCert found on before");
            }
            attrSelector.AttributeCertificateValid = new DateTimeObject(attrCert.NotAfter.AddMilliseconds(100));
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 0)
            {
                Fail("attrCert found on after");
            }
            attrSelector.SerialNumber = BigInteger.ValueOf(10000);
            attrs = new ArrayList(store.GetMatches(attrSelector));
            if (attrs.Count != 0)
            {
                Fail("attrCert found on wrong serial number");
            }

            attrSelector.AttributeCert             = null;
            attrSelector.AttributeCertificateValid = null;
            attrSelector.Holder       = null;
            attrSelector.Issuer       = null;
            attrSelector.SerialNumber = null;
            if (attrSelector.AttributeCert != null)
            {
                Fail("null attrCert");
            }
            if (attrSelector.AttributeCertificateValid != null)
            {
                Fail("null attrCertValid");
            }
            if (attrSelector.Holder != null)
            {
                Fail("null attrCert holder");
            }
            if (attrSelector.Issuer != null)
            {
                Fail("null attrCert issuer");
            }
            if (attrSelector.SerialNumber != null)
            {
                Fail("null attrCert serial");
            }

            attrs = new ArrayList(certStore.GetMatches(attrSelector));
            if (attrs.Count != 0)
            {
                Fail("error using wrong selector (attrs)");
            }

            certPairTest();
        }
        /// <summary>
        /// 生成X509 V3证书
        /// </summary>
        /// <param name="certPath">Cert证书路径</param>
        /// <param name="endDate">证书失效时间</param>
        /// <param name="keySize">密钥长度</param>
        /// <param name="password">证书密码</param>
        /// <param name="signatureAlgorithm">设置将用于签署此证书的签名算法</param>
        /// <param name="issuer">设置此证书颁发者的DN</param>
        /// <param name="subject">设置此证书使用者的DN</param>
        /// <param name="pfxPath">Pfx证书路径</param>
        /// <param name="friendlyName">设置证书友好名称(可选)</param>
        /// <param name="startDate">证书生效时间</param>
        /// <param name="algorithm">加密算法</param>
        public static void X509V3(string algorithm, int keySize, string password, string signatureAlgorithm,
                                  DateTime startDate, DateTime endDate, X509Name issuer, X509Name subject, string certPath, string pfxPath,
                                  string friendlyName = "")
        {
            //generate Random Numbers
            CryptoApiRandomGenerator randomGenerator = new CryptoApiRandomGenerator();
            SecureRandom             random          = new SecureRandom(randomGenerator);

            var keyGenerator = GeneratorUtilities.GetKeyPairGenerator(algorithm);

            keyGenerator.Init(new KeyGenerationParameters(new SecureRandom(), keySize));

            var keyPair = keyGenerator.GenerateKeyPair();

            var v3CertGen    = new X509V3CertificateGenerator();
            var serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            v3CertGen.SetSerialNumber(serialNumber);                                                   //设置证书的序列号

            v3CertGen.SetIssuerDN(issuer);                                                             //设置颁发者信息
            v3CertGen.SetSubjectDN(subject);                                                           //设置使用者信息

            v3CertGen.SetNotBefore(startDate);                                                         //设置证书的生效日期
            v3CertGen.SetNotAfter(endDate);                                                            //设置证书失效的日期
            v3CertGen.SetPublicKey(keyPair.Public);                                                    //设置此证书的公钥

            ISignatureFactory sigFact = new Asn1SignatureFactory(signatureAlgorithm, keyPair.Private); //签名算法&设置此证书的私钥

            var spki = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);

            //设置一些扩展字段
            //基本约束
            v3CertGen.AddExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
            //使用者密钥标识符
            v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki));
            //授权密钥标识符
            v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(spki));

            var x509Certificate = v3CertGen.Generate(sigFact); //生成证书

            x509Certificate.CheckValidity();                   //检查当前日期是否在证书的有效期内
            x509Certificate.Verify(keyPair.Public);            //使用公钥验证证书的签名

            var certificate2 = new X509Certificate2(DotNetUtilities.ToX509Certificate(x509Certificate))
            {
                FriendlyName = friendlyName, //设置友好名称
            };

            //cer公钥文件
            var bytes = certificate2.Export(X509ContentType.Cert);

            using (var fs = new FileStream(certPath, FileMode.Create))
            {
                fs.Write(bytes, 0, bytes.Length);
            }

            //pfx证书,包含公钥私钥
            //CopyWithPrivateKey netstandard2.1支持
            certificate2 =
                certificate2.CopyWithPrivateKey(DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private));

            var bytes2 = certificate2.Export(X509ContentType.Pfx, password);

            using (var fs = new FileStream(pfxPath, FileMode.Create))
            {
                fs.Write(bytes2, 0, bytes2.Length);
            }


            //如果使用 netstandard2.0 请使用下面的代码
#if NETSTANDARD2_0
            var certEntry = new X509CertificateEntry(x509Certificate);
            var store     = new Pkcs12StoreBuilder().Build();
            store.SetCertificateEntry(friendlyName, certEntry);   //设置证书
            var chain = new X509CertificateEntry[1];
            chain[0] = certEntry;
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(keyPair.Private), chain);   //设置私钥
            using (var fs = File.Create(pfxPath))
            {
                store.Save(fs, password.ToCharArray(), new SecureRandom()); //保存
            }
#endif
        }
Beispiel #30
0
        private void doTestGP(
            int size,
            int privateValueSize,
            BigInteger g,
            BigInteger p)
        {
            IAsymmetricCipherKeyPairGenerator keyGen = GeneratorUtilities.GetKeyPairGenerator("ElGamal");

//			DHParameterSpec elParams = new DHParameterSpec(p, g);
//			keyGen.initialize(elParams);
            ElGamalParameters elParams           = new ElGamalParameters(p, g, privateValueSize);
            ElGamalKeyGenerationParameters elKgp = new ElGamalKeyGenerationParameters(
                new SecureRandom(), elParams);

            keyGen.Init(elKgp);

            AsymmetricCipherKeyPair keyPair = keyGen.GenerateKeyPair();
            SecureRandom            rand    = new SecureRandom();

            checkKeySize(privateValueSize, keyPair);

            IBufferedCipher cipher = CipherUtilities.GetCipher("ElGamal");

            cipher.Init(true, new ParametersWithRandom(keyPair.Public, rand));

            byte[] inBytes = Encoding.ASCII.GetBytes("This is a test");

            if (cipher.GetOutputSize(inBytes.Length) != (size / 8) * 2)
            {
                Fail("getOutputSize wrong on encryption");
            }

            byte[] outBytes = cipher.DoFinal(inBytes);

            cipher.Init(false, keyPair.Private);

            if (cipher.GetOutputSize(outBytes.Length) != (size / 8) - 1)
            {
                Fail("GetOutputSize wrong on decryption");
            }


            //
            // No Padding - maximum length
            //
            byte[] modBytes = ((ElGamalPublicKeyParameters)keyPair.Public).Parameters.P.ToByteArray();
            byte[] maxInput = new byte[modBytes.Length - 1];

            maxInput[0] |= 0x7f;

            cipher.Init(true, new ParametersWithRandom(keyPair.Public, rand));

            outBytes = cipher.DoFinal(maxInput);

            cipher.Init(false, keyPair.Private);

            outBytes = cipher.DoFinal(outBytes);

            if (!AreEqual(outBytes, maxInput))
            {
                Fail("NoPadding test failed on decrypt expected "
                     + Hex.ToHexString(maxInput) + " got "
                     + Hex.ToHexString(outBytes));
            }


            //
            // encrypt/decrypt
            //
            IBufferedCipher c1 = CipherUtilities.GetCipher("ElGamal");
            IBufferedCipher c2 = CipherUtilities.GetCipher("ElGamal");

            c1.Init(true, new ParametersWithRandom(keyPair.Public, rand));

            byte[] out1 = c1.DoFinal(inBytes);

            c2.Init(false, keyPair.Private);

            byte[] out2 = c2.DoFinal(out1);

            if (!AreEqual(inBytes, out2))
            {
                Fail(size + " encrypt test failed");
            }


            //
            // encrypt/decrypt with update
            //
            int outLen = c1.ProcessBytes(inBytes, 0, 2, out1, 0);

            outLen += c1.DoFinal(inBytes, 2, inBytes.Length - 2, out1, outLen);

            outLen = c2.ProcessBytes(out1, 0, 2, out2, 0);

            outLen += c2.DoFinal(out1, 2, out1.Length - 2, out2, outLen);

            if (!AreEqual(inBytes, out2))
            {
                Fail(size + " encrypt with update test failed");
            }



            //
            // public key encoding test
            //
//			byte[] pubEnc = keyPair.Public.GetEncoded();
            byte[] pubEnc = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public).GetDerEncoded();

//			KeyFactory keyFac = KeyFactory.GetInstance("ElGamal");
//			X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(pubEnc);
//			DHPublicKeyParameters pubKey = (DHPublicKeyParameters)keyFac.generatePublic(pubX509);
            ElGamalPublicKeyParameters pubKey = (ElGamalPublicKeyParameters)
                                                PublicKeyFactory.CreateKey(pubEnc);
            ElGamalParameters spec = pubKey.Parameters;

            if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P))
            {
                Fail(size + " bit public key encoding/decoding test failed on parameters");
            }

            if (!((ElGamalPublicKeyParameters)keyPair.Public).Y.Equals(pubKey.Y))
            {
                Fail(size + " bit public key encoding/decoding test failed on y value");
            }

/*
 *                      //
 *                      // public key serialisation test
 *                      //
 *                      // TODO Is there some standard this serialization must conform to?
 *                      BinaryFormatter formatter = new BinaryFormatter();
 *
 *                      MemoryStream bOut = new MemoryStream();
 * //			ObjectOutputStream oOut = new ObjectOutputStream(bOut);
 * //			oOut.writeObject(keyPair.Public);
 *                      formatter.Serialize(bOut, keyPair.Public);
 *
 *                      MemoryStream bIn = new MemoryStream(bOut.ToArray(), false);
 * //			ObjectInputStream oIn = new ObjectInputStream(bIn);
 * //			pubKey = (DHPublicKeyParameters)oIn.readObject();
 *                      pubKey = (ElGamalPublicKeyParameters) formatter.Deserialize(bIn);
 *                      spec = pubKey.Parameters;
 *
 *                      if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P))
 *                      {
 *                              Fail(size + " bit public key serialisation test failed on parameters");
 *                      }
 *
 *                      if (!((ElGamalPublicKeyParameters )keyPair.Public).Y.Equals(pubKey.Y))
 *                      {
 *                              Fail(size + " bit public key serialisation test failed on y value");
 *                      }
 */

            //
            // private key encoding test
            //
            // TODO Keys don't support GetEncoded
//			byte[] privEnc = keyPair.Private.GetEncoded();
            byte[] privEnc = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private).GetDerEncoded();

//			PKCS8EncodedKeySpec privPKCS8 = new PKCS8EncodedKeySpec(privEnc);
//			DHPrivateKeyParameters privKey = (DHPrivateKeyParameters)keyFac.generatePrivate(privPKCS8);
            ElGamalPrivateKeyParameters privKey = (ElGamalPrivateKeyParameters)
                                                  PrivateKeyFactory.CreateKey(privEnc);

            spec = privKey.Parameters;

            if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P))
            {
                Fail(size + " bit private key encoding/decoding test failed on parameters");
            }

            if (!((ElGamalPrivateKeyParameters)keyPair.Private).X.Equals(privKey.X))
            {
                Fail(size + " bit private key encoding/decoding test failed on y value");
            }

/*
 *                      //
 *                      // private key serialisation test
 *                      //
 *                      bOut = new MemoryStream();
 * //			oOut = new ObjectOutputStream(bOut);
 * //			oOut.writeObject(keyPair.Private);
 *                      formatter.Serialize(bOut, keyPair.Private);
 *
 *                      bIn = new MemoryStream(bOut.ToArray(), false);
 * //			oIn = new ObjectInputStream(bIn);
 * //			privKey = (DHPrivateKeyParameters)oIn.readObject();
 *                      privKey = (ElGamalPrivateKeyParameters) formatter.Deserialize(bIn);
 *                      spec = privKey.Parameters;
 *
 *                      if (!spec.G.Equals(elParams.G) || !spec.P.Equals(elParams.P))
 *                      {
 *                              Fail(size + " bit private key serialisation test failed on parameters");
 *                      }
 *
 *                      if (!((ElGamalPrivateKeyParameters) keyPair.Private).X.Equals(privKey.X))
 *                      {
 *                              Fail(size + " bit private key serialisation test failed on y value");
 *                      }
 */
        }