示例#1
0
        public async Task <RsaKeyPair> CreateKeyPair()
        {
            var kpgen      = new RsaKeyPairGenerator();
            var privateKey = string.Empty;
            var publicKey  = string.Empty;

            kpgen.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            await Task.Run(() =>
            {
                var keyPair = kpgen.GenerateKeyPair();

                PrivateKeyInfo pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
                privateKey            = Convert.ToBase64String(pkInfo.GetDerEncoded());

                SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
                publicKey = Convert.ToBase64String(info.GetDerEncoded());
            });

            return(new RsaKeyPair {
                PrivateKey = privateKey, PublicKey = publicKey
            });
        }
示例#2
0
        /// <summary>
        /// DSA密钥对生成
        /// </summary>
        /// <param name="size">size must be from 512 - 1024 and a multiple of 64</param>
        /// <returns></returns>
        public static KeyParameter Generator(int size = 1024)
        {
            var pGen = new DsaParametersGenerator();

            pGen.Init(size, 80, new SecureRandom());
            var dsaParams = pGen.GenerateParameters();
            var kgp       = new DsaKeyGenerationParameters(new SecureRandom(), dsaParams);
            var kpg       = GeneratorUtilities.GetKeyPairGenerator("DSA");

            kpg.Init(kgp);

            var kp = kpg.GenerateKeyPair();

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

            return(new KeyParameter
            {
                PrivateKey = Base64.ToBase64String(privateKeyInfo.GetEncoded()),
                PublicKey = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded())
            });
        }
        /// <summary>
        /// RSA私钥格式转换,.net->java
        /// </summary>
        /// <param name="privateKey">.net生成的私钥</param>
        /// <returns></returns>
        public static string RSAPrivateKeyDotNet2Java(string privateKey)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(privateKey);
            BigInteger m    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Modulus")[0].InnerText));
            BigInteger exp  = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Exponent")[0].InnerText));
            BigInteger d    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("D")[0].InnerText));
            BigInteger p    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("P")[0].InnerText));
            BigInteger q    = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("Q")[0].InnerText));
            BigInteger dp   = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DP")[0].InnerText));
            BigInteger dq   = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("DQ")[0].InnerText));
            BigInteger qinv = new BigInteger(1, Convert.FromBase64String(doc.DocumentElement.GetElementsByTagName("InverseQ")[0].InnerText));

            RsaPrivateCrtKeyParameters privateKeyParam = new RsaPrivateCrtKeyParameters(m, exp, d, p, q, dp, dq, qinv);

            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKeyParam);

            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
            //return serializedPrivateBytes;
            return(Convert.ToBase64String(serializedPrivateBytes));
        }
示例#4
0
        public override string ComputeSharedSecret(string otherKey, bool isBase64 = true)
        {
            byte[] blob = (isBase64 ? Convert.FromBase64String(otherKey) : Encoding.UTF8.GetBytes(otherKey));

            // the shared secret is the x-coordinate of a point on the EC. the point
            // is calculated by multiplying the remote entity's public key (which itself is
            // a point on the curve) by our private key (an integer value).
            // the following calculation follows the code example here:
            // https://stackoverflow.com/questions/15430784/
            PrivateKeyInfo         info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(_keyPair.Private);
            ECPrivateKeyParameters priv = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(info);
            ECPoint point             = priv.Parameters.Curve.DecodePoint(blob);
            ECPublicKeyParameters pub = new ECPublicKeyParameters(point, priv.Parameters);

            IBasicAgreement agree = new ECDHBasicAgreement();

            agree.Init(priv);
            BigInteger value = agree.CalculateAgreement(pub);

            SharedSecret = Convert.ToBase64String(value.ToByteArrayUnsigned());
            return(SharedSecret);
        }
        public (string publicKey, string privateKey) GetDsaKeys()
        {
            var secureRandom        = new SecureRandom();
            var parametersGenerator = new DsaParametersGenerator(new Sha1Digest());

            parametersGenerator.Init(1024, 100, secureRandom);
            var parameters = parametersGenerator.GenerateParameters();

            var g = new DsaKeyPairGenerator();

            g.Init(new DsaKeyGenerationParameters(secureRandom, parameters));
            var keyPair = g.GenerateKeyPair();

            var pkInfo     = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
            var privateKey = Convert.ToBase64String(pkInfo.ToAsn1Object().GetDerEncoded());

            var publicKeyInfo         = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
            var serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();
            var publicKey             = Convert.ToBase64String(serializedPublicBytes);

            return(publicKey, privateKey);
        }
        public override void ExportPrivateKey(PrivateKey pk, EncodingFormat fmt, Stream target)
        {
            var rsaPk = pk as RsaPrivateKey;

            if (rsaPk != null)
            {
                switch (fmt)
                {
                case EncodingFormat.PEM:
                    var bytes = Encoding.UTF8.GetBytes(rsaPk.Pem);
                    target.Write(bytes, 0, bytes.Length);
                    break;

                case EncodingFormat.DER:
                    using (var tr = new StringReader(rsaPk.Pem))
                    {
                        var pr   = new PemReader(tr);
                        var pem  = pr.ReadObject();
                        var ackp = pem as AsymmetricCipherKeyPair;

                        if (ackp != null)
                        {
                            var prv = ackp.Private as RsaPrivateCrtKeyParameters;
                            var der = PrivateKeyInfoFactory.CreatePrivateKeyInfo(prv).GetDerEncoded();
                            target.Write(der, 0, der.Length);
                            break;
                        }
                    }
                    throw new NotSupportedException("unsupported or invalid private key format");

                default:
                    throw new NotSupportedException("unsupported encoding format");
                }
            }
            else
            {
                throw new NotSupportedException("unsupported private key type");
            }
        }
示例#7
0
        public RSAKEY GetKey()
        {
            //RSA密钥对的构造器
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();

            //RSA密钥构造器的参数
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度
                25);

            //用参数初始化密钥构造器
            keyGenerator.Init(param);
            //产生密钥对
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和密钥
            AsymmetricKeyParameter publicKey  = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo       privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);


            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[]     publicInfoByte    = asn1ObjectPublic.GetEncoded("UTF-8");
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();

            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");

            RSAKEY item = new RSAKEY()
            {
                PublicKey  = Convert.ToBase64String(publicInfoByte),
                PrivateKey = Convert.ToBase64String(privateInfoByte)
            };

            return(item);
        }
示例#8
0
        /// <summary>
        /// Save certificate as pfx file with private key
        /// </summary>
        /// <param name="issuerKeyPair"></param>
        /// <param name="x509"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private X509Certificate2 SaveToPFX(AsymmetricCipherKeyPair issuerKeyPair, X509Certificate2 x509, string fileName)
        {
            // add private key to x509
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(issuerKeyPair.Private);
            var            seq  = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            // It should thow if seq.c**t != 9 because folowing info should be stored in RSA key.
            // following page has more info: https://tls.mbed.org/kb/cryptography/asn1-key-structures-in-der-and-pem
            // version           Version,
            // modulus INTEGER,  --n
            // publicExponent INTEGER,  --e
            // privateExponent INTEGER,  --d
            // prime1 INTEGER,  --p
            // prime2 INTEGER,  --q
            // exponent1 INTEGER,  --d mod(p - 1)
            // exponent2 INTEGER,  --d mod(q - 1)
            // coefficient INTEGER,  --(inverse of q) mod p
            // otherPrimeInfos OtherPrimeInfos OPTIONAL
            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);


            x509.PrivateKey = DotNetUtilities.ToRSA(rsaparams);
            var utils = new GeneralUtils();

            if (!fileName.EndsWith(".pfx"))
            {
                fileName += ".pfx";
            }
            File.WriteAllBytes(utils.PathWithName(fileName), x509.Export(X509ContentType.Pkcs12, GetCertPassword()));
            return(x509);
        }
示例#9
0
        public void TestDH()
        {
            BigInteger DHParraP = new BigInteger(Base64.Decode("ALJCm1CUL6mOnyVqWTSV6Z2+DVSGOvgboOhmbyyxCrym59uVnXMmPjIgQTrmniFg7PvdcN7NNFwFmcZleULso1s="));
            BigInteger DHParraQ = new BigInteger(Base64.Decode("WSFNqEoX1MdPkrUsmkr0zt8GqkMdfA3QdDM3lliFXlNz7crOuZMfGRAgnXNPELB2fe64b2aaLgLM4zK8oXZRrQ=="));
            BigInteger DHPubY   = new BigInteger(Base64.Decode("AIki+8/zggCS2e488AsTNULI4LujdUeQQsZI949Dc9lKXZRmrPIC1h8NRoneHQEhpAe4Rhe0nhUOGZJekT5++SA="));
            BigInteger DHPrivX  = new BigInteger(Base64.Decode("Apo67noMRO5eDWo/TtpRiBmKGw7ywh25shIu0Rs03krQmWKRbDPvdygWdJ5IpW6ZbKlCTAMhSxpz03YSeSEDmw=="));


            DHParameters           dhPara    = new DHParameters(DHParraP, DHParraQ);
            DHPublicKeyParameters  dhPublic  = new DHPublicKeyParameters(DHPubY, dhPara);
            DHPrivateKeyParameters dhPrivate = new DHPrivateKeyParameters(DHPrivX, dhPara);

            SubjectPublicKeyInfo pubInfo  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(dhPublic);
            PrivateKeyInfo       privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(dhPrivate);

            DHPublicKeyParameters  testPubKey  = (DHPublicKeyParameters)PublicKeyFactory.CreateKey(pubInfo);
            DHPrivateKeyParameters testPrivKey = (DHPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo);

            Assert.IsFalse(!testPrivKey.Equals(dhPrivate), "DH: Private key to info back to key");
            Assert.IsFalse(!testPubKey.Equals(dhPublic), "DH: Public key to info back to key");

            Assert.IsTrue(true, "Diffe Helman Test worked.");
        }
示例#10
0
        public static string XmlToPem(string xml)
        {
            using (RSA rsa = RSA.Create())
            {
                rsa.FromXmlString(xml);

                AsymmetricCipherKeyPair keyPair = Org.BouncyCastle.Security.DotNetUtilities.GetRsaKeyPair(rsa); // try get private and public key pair
                if (keyPair != null)                                                                            // if XML RSA key contains private key
                {
                    PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
                    return(FormatPem(Convert.ToBase64String(privateKeyInfo.GetEncoded()), "PRIVATE KEY"));
                }

                RsaKeyParameters publicKey = Org.BouncyCastle.Security.DotNetUtilities.GetRsaPublicKey(rsa); // try get public key
                if (publicKey != null)                                                                       // if XML RSA key contains public key
                {
                    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
                    return(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY"));
                }
            }

            throw new InvalidKeyException("Invalid RSA Xml Key");
        }
示例#11
0
        public byte[] GetBlob()
        {
            // get private key as byte array, and length of private key as byte array.
            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(_keyPair.Private);

            byte[] priv    = info.GetDerEncoded();
            byte[] privLen = BitConverter.GetBytes((Int32)priv.Length);

            // get public key as byte array.
            AsymmetricKeyParameter pubKey = _keyPair.Public;
            SubjectPublicKeyInfo   spki   = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubKey);

            byte[] pub = spki.GetDerEncoded();

            // output byte array uses first 4 bytes for the length of the base64 private key,
            // followed by the base64 private key, then the base64 public key.
            // this is a completely homegrown non-standard format; for testing only.
            byte[] result = new byte[privLen.Length + priv.Length + pub.Length];
            privLen.CopyTo(result, 0);
            priv.CopyTo(result, privLen.Length);
            pub.CopyTo(result, privLen.Length + priv.Length);
            return(result);
        }
示例#12
0
 public PemObject Generate()
 {
     if (algorithm == null)
     {
         PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
         return(new PemObject("PRIVATE KEY", privateKeyInfo.GetEncoded()));
     }
     byte[] array = new byte[20];
     if (random == null)
     {
         random = new SecureRandom();
     }
     random.NextBytes(array);
     try
     {
         EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = EncryptedPrivateKeyInfoFactory.CreateEncryptedPrivateKeyInfo(algorithm, password, array, iterationCount, privKey);
         return(new PemObject("ENCRYPTED PRIVATE KEY", encryptedPrivateKeyInfo.GetEncoded()));
     }
     catch (Exception exception)
     {
         throw new PemGenerationException("Couldn't encrypt private key", exception);
     }
 }
示例#13
0
        public static string XmlToPem(string xml)
        {
            using (var rsa = RSA.Create())
            {
                rsa.FromXmlString(xml);

                var keyPair = rsa.GetKeyPair(); // try get private and public key pair
                if (keyPair != null)            // if XML RSA key contains private key
                {
                    var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
                    return(FormatPem(Convert.ToBase64String(privateKeyInfo.GetEncoded()), "PRIVATE KEY"));
                }

                var publicKey = rsa.GetPublicKey(); // try get public key
                if (publicKey != null)              // if XML RSA key contains public key
                {
                    var publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
                    return(FormatPem(Convert.ToBase64String(publicKeyInfo.GetEncoded()), "PUBLIC KEY"));
                }
            }

            throw new InvalidKeyException("Invalid RSA Xml Key");
        }
示例#14
0
        public RSAKey GetKey(int keyLen = 1024)
        {
            //RSA密钥对的构造器
            var keyGenerator = new RsaKeyPairGenerator();

            //RSA密钥构造器的参数
            var param = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(3),
                new SecureRandom(),
                keyLen,   //密钥长度
                25);

            //用参数初始化密钥构造器
            keyGenerator.Init(param);
            //产生密钥对
            var keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和密钥
            var publicKey  = keyPair.Public;
            var privateKey = keyPair.Private;

            var subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            var privateKeyInfo       = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);


            var asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            var publicInfoByte    = asn1ObjectPublic.GetEncoded("UTF-8");
            var asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
            var privateInfoByte   = asn1ObjectPrivate.GetEncoded("UTF-8");

            var pub = Convert.ToBase64String(publicInfoByte);
            var pri = Convert.ToBase64String(privateInfoByte);

            var item = new RSAKey(pub, pri);

            return(item);
        }
示例#15
0
        public IActionResult Index()
        {
            var id   = _userManager.GetUserId(User);
            var user = _aadeDbIntegration.GetUser(id);

            // first time there is no public/private key pair for encryption
            // so generate now
            // generated keypair using RSA that is unique to this aade user
            // https://cryptobook.nakov.com/asymmetric-key-ciphers/the-rsa-cryptosystem-concepts
            if (string.IsNullOrEmpty(user.PrivateKey))
            {
                var keyGenerator = new RsaKeyPairGenerator();
                var param        = new KeyGenerationParameters(
                    new SecureRandom(),
                    4096);
                keyGenerator.Init(param);
                var keyPair = keyGenerator.GenerateKeyPair();

                // need to save these keys in the db so must serialize into strings
                // https://stackoverflow.com/questions/22008337/generating-keypair-using-bouncy-castle
                PrivateKeyInfo       pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
                SubjectPublicKeyInfo info   = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);

                var aadeprivateKey = Convert.ToBase64String(pkInfo.GetDerEncoded());
                var aadepublicKey  = Convert.ToBase64String(info.GetDerEncoded());

                user.PrivateKey = aadeprivateKey;
                user.PublicKey  = aadepublicKey;
                _aadeDbIntegration.UpdateUser(user);
            }

            var model = new HomeViewModel();
            var m     = _messageDbIntegration.GetMessageForAadeUser(id);

            model.MyMessages = m;
            return(View(model));
        }
        public (string PrivateKey, string PublicKey) GenerateRsaKeys(string companyName)
        {
            var rsaKeyPairGenerator = new RsaKeyPairGenerator();

            rsaKeyPairGenerator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            var pair = rsaKeyPairGenerator.GenerateKeyPair();

            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);

            byte[] privateKeyPkcs8DerEncodedBytes = privateKeyInfo.ToAsn1Object().GetDerEncoded();

            // privateKeyPkcs8DerEncodedBytes contains PKCS#8 DER-encoded private key as a byte[]
            var pkcs8PrivateKeyInfo = PrivateKeyInfo.GetInstance(privateKeyPkcs8DerEncodedBytes);
            var pkcs1Key            = RsaPrivateKeyStructure.GetInstance(pkcs8PrivateKeyInfo.ParsePrivateKey());

            byte[] privateKeyPkcs1EncodedBytes = pkcs1Key.GetEncoded();

            var sb = new StringBuilder();

            sb.AppendLine("-----BEGIN RSA PRIVATE KEY-----");
            sb.AppendLine(Convert.ToBase64String(privateKeyPkcs1EncodedBytes, Base64FormattingOptions.InsertLineBreaks));
            sb.AppendLine("-----END RSA PRIVATE KEY-----");
            var serializedPrivate = sb.ToString();

            var caName      = new X509Name($"CN={companyName}");
            var caCert      = GenerateCertificate(caName, caName, pair.Private, pair.Public);
            var certEncoded = caCert.GetEncoded();

            sb = new StringBuilder();
            sb.AppendLine("-----BEGIN CERTIFICATE-----");
            sb.AppendLine(Convert.ToBase64String(certEncoded, Base64FormattingOptions.InsertLineBreaks));
            sb.AppendLine("-----END CERTIFICATE-----");
            var serializedPublic = sb.ToString();

            return(serializedPrivate, serializedPublic);
        }
示例#17
0
        private byte[] CreatePfxFile(Org.BouncyCastle.X509.X509Certificate cert, AsymmetricKeyParameter privateKey, string password, string keyFriendlyName)
        {
            var certEntry    = new X509CertificateEntry(cert);
            var friendlyName = cert.SubjectDN.ToString();

            var keyInfo  = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
            var keyBytes = keyInfo.ToAsn1Object().GetEncoded();

            var builder = new Pkcs12StoreBuilder();

            builder.SetUseDerEncoding(true);
            var store = builder.Build();

            store.SetKeyEntry(keyFriendlyName, new AsymmetricKeyEntry(privateKey), new[] { certEntry });
            byte[] pfxBytes;

            using (var ms = new MemoryStream())
            {
                store.Save(ms, password.ToCharArray(), new SecureRandom());
                pfxBytes = ms.ToArray();
            }

            return(Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes));
        }
示例#18
0
        private static byte[] EncodePrivateKey(AsymmetricKeyParameter akp, out string keyType)
        {
            PrivateKeyInfo      privateKeyInfo      = PrivateKeyInfoFactory.CreatePrivateKeyInfo(akp);
            AlgorithmIdentifier privateKeyAlgorithm = privateKeyInfo.PrivateKeyAlgorithm;
            DerObjectIdentifier objectID            = privateKeyAlgorithm.ObjectID;

            if (objectID.Equals(X9ObjectIdentifiers.IdDsa))
            {
                keyType = "DSA";
                DsaParameter instance = DsaParameter.GetInstance(privateKeyAlgorithm.Parameters);
                BigInteger   x        = ((DsaPrivateKeyParameters)akp).X;
                BigInteger   value    = instance.G.ModPow(x, instance.P);
                return(new DerSequence(new Asn1Encodable[]
                {
                    new DerInteger(0),
                    new DerInteger(instance.P),
                    new DerInteger(instance.Q),
                    new DerInteger(instance.G),
                    new DerInteger(value),
                    new DerInteger(x)
                }).GetEncoded());
            }
            if (objectID.Equals(PkcsObjectIdentifiers.RsaEncryption))
            {
                keyType = "RSA";
            }
            else
            {
                if (!objectID.Equals(CryptoProObjectIdentifiers.GostR3410x2001) && !objectID.Equals(X9ObjectIdentifiers.IdECPublicKey))
                {
                    throw new ArgumentException("Cannot handle private key of type: " + akp.GetType().FullName, "akp");
                }
                keyType = "EC";
            }
            return(privateKeyInfo.ParsePrivateKey().GetEncoded());
        }
示例#19
0
        /// <summary>
        /// Exports the key into a supported key format.
        /// </summary>
        public byte[] Export(PkiEncodingFormat format, char[] password = null)
        {
            switch (format)
            {
            case PkiEncodingFormat.Pem:
                using (var sw = new StringWriter())
                {
                    object pemObject = NativeKey;
                    if (IsPrivate && password != null)
                    {
                        var pkcs8Gen = new Pkcs8Generator(NativeKey,
                                                          Pkcs8Generator.PbeSha1_3DES);
                        pkcs8Gen.Password = password;
                        pemObject         = pkcs8Gen.Generate();
                    }
                    var pemWriter = new PemWriter(sw);
                    pemWriter.WriteObject(pemObject);
                    return(Encoding.UTF8.GetBytes(sw.GetStringBuilder().ToString()));
                }

            case PkiEncodingFormat.Der:
                if (IsPrivate)
                {
                    var keyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(NativeKey);
                    return(keyInfo.GetDerEncoded());
                }
                else
                {
                    var keyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(NativeKey);
                    return(keyInfo.GetDerEncoded());
                }

            default:
                throw new NotSupportedException();
            }
        }
示例#20
0
        /// <summary>
        ///  XML格式私钥转PEM
        /// </summary>
        /// <param name="xml">XML格式私钥</param>
        /// <param name="saveFile">保存文件的物理路径</param>
        public static string Xml2PemPrivate(string xml, string saveFile)
        {
            var rsa = new RSACryptoServiceProvider();

            rsa.FromXmlString(xml);
            var p   = rsa.ExportParameters(true);
            var key = new RsaPrivateCrtKeyParameters(
                new BigInteger(1, p.Modulus), new BigInteger(1, p.Exponent), new BigInteger(1, p.D),
                new BigInteger(1, p.P), new BigInteger(1, p.Q), new BigInteger(1, p.DP), new BigInteger(1, p.DQ),
                new BigInteger(1, p.InverseQ));

            using (var sw = new StreamWriter(saveFile))
            {
                var pemWriter = new Org.BouncyCastle.OpenSsl.PemWriter(sw);
                pemWriter.WriteObject(key);
            }

            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(key);

            byte[] serializedPrivateBytes = privateKeyInfo.ToAsn1Object().GetEncoded();
            string privateKey             = Convert.ToBase64String(serializedPrivateBytes);

            return(Format(privateKey, 2));
        }
示例#21
0
        /// <summary>
        /// Create random EC private key based on secp256r1
        /// </summary>
        public static string CreatePrivateKey()
        {
            // creating private key
            SecureRandom              secureRandom = new SecureRandom();
            X9ECParameters            ecParams     = SecNamedCurves.GetByName("secp256r1");
            ECDomainParameters        ccdParams    = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed());
            ECKeyGenerationParameters keyGenParams = new ECKeyGenerationParameters(ccdParams, secureRandom);
            ECKeyPairGenerator        generator    = new ECKeyPairGenerator("ECDH");

            generator.Init(keyGenParams);

            // getting public key
            AsymmetricCipherKeyPair keyPair    = generator.GenerateKeyPair();
            ECPrivateKeyParameters  privParams = keyPair.Private as ECPrivateKeyParameters;
            PrivateKeyInfo          privInfo   = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privParams);
            ECPoint q = privParams.Parameters.G.Multiply(privParams.D);
            ECPublicKeyParameters pubParams = new ECPublicKeyParameters(privParams.AlgorithmName, q, privParams.Parameters);
            SubjectPublicKeyInfo  pubInfo   = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(pubParams);

            // ugly hack
            byte[] der        = privInfo.GetDerEncoded();
            byte[] privateKey = der.Skip(der.Length - 32).ToArray();
            der = pubInfo.GetDerEncoded();
            byte[] publicKey = der.Skip(der.Length - 65).ToArray();

            // repack DER
            DerSequence seq = new DerSequence(
                new DerInteger(1),
                new DerOctetString(privateKey),
                new DerTaggedObject(0, new DerObjectIdentifier("1.2.840.10045.3.1.7")),
                new DerTaggedObject(1, new DerBitString(publicKey))
                );

            der = seq.GetDerEncoded();
            return(Hex.ToHexString(der));
        }
示例#22
0
        public static string XmlToPem(string xml)
        {
            using (RSA rsa = RSA.Create())
            {
                rsa.FromXmlString(xml);

                AsymmetricCipherKeyPair keyPair = rsa.GetKeyPair(); // try get private and public key pair
                if (keyPair != null)                                // if XML RSA key contains private key
                {
                    PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
                    return(FormatPem(privateKeyInfo.GetEncoded().ToBase64(), "RSA PRIVATE KEY"));
                }

                RsaKeyParameters publicKey = rsa.GetPublicKey(); // try get public key
                if (publicKey != null)                           // if XML RSA key contains public key
                {
                    SubjectPublicKeyInfo publicKeyInfo =
                        SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
                    return(FormatPem(publicKeyInfo.GetEncoded().ToBase64(), "PUBLIC KEY"));
                }
            }

            throw new InvalidKeyException("Invalid RSA Xml Key");
        }
示例#23
0
        public void TestEC()
        {
            BigInteger ECParraGX = new BigInteger(Base64.Decode("D/qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqv"));
            BigInteger ECParraGY = new BigInteger(Base64.Decode("AhQXGxb1olGRv6s1LPRfuatMF+cx3ZTGgzSE/Q5R"));
            BigInteger ECParraH  = new BigInteger(Base64.Decode("AQ=="));
            BigInteger ECParraN  = new BigInteger(Base64.Decode("f///////////////f///nl6an12QcfvRUiaIkJ0L"));
            BigInteger ECPubQX   = new BigInteger(Base64.Decode("HWWi17Yb+Bm3PYr/DMjLOYNFhyOwX1QY7ZvqqM+l"));
            BigInteger ECPubQY   = new BigInteger(Base64.Decode("JrlJfxu3WGhqwtL/55BOs/wsUeiDFsvXcGhB8DGx"));
            BigInteger ECPrivD   = new BigInteger(Base64.Decode("GYQmd/NF1B+He1iMkWt3by2Az6Eu07t0ynJ4YCAo"));

            FpCurve curve = new FpCurve(
                new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q
                new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16),         // a
                new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16),         // b
                ECParraN, ECParraH);

            ECDomainParameters ecDomain = new ECDomainParameters(
                curve,
                curve.ValidatePoint(ECParraGX, ECParraGY),
                ECParraN, ECParraH);

            ECPublicKeyParameters ecPub = new ECPublicKeyParameters(
                curve.ValidatePoint(ECPubQX, ECPubQY),
                ecDomain);

            ECPrivateKeyParameters ecPriv = new ECPrivateKeyParameters(ECPrivD, ecDomain);

            SubjectPublicKeyInfo subinfo  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(ecPub);
            PrivateKeyInfo       privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(ecPriv);

            ECPublicKeyParameters  tecPub  = (ECPublicKeyParameters)PublicKeyFactory.CreateKey(subinfo);
            ECPrivateKeyParameters tecPriv = (ECPrivateKeyParameters)PrivateKeyFactory.CreateKey(privInfo);

            Assert.IsTrue(tecPub.Equals(ecPub), "EC: public key to info back to public key");
            Assert.IsTrue(tecPriv.Equals(ecPriv), "EC: private key to info back to private key");
        }
        /**
         * decrypt the content and return an input stream.
         */
        public override CmsTypedStream GetContentStream(
//			Key key)
            ICipherParameters key)
        {
            if (!(key is AsymmetricKeyParameter))
            {
                throw new ArgumentException("KeyAgreement requires asymmetric key", "key");
            }

            AsymmetricKeyParameter privKey = (AsymmetricKeyParameter)key;

            if (!privKey.IsPrivate)
            {
                throw new ArgumentException("Expected private key", "key");
            }

            try
            {
                OriginatorPublicKey    origK    = _info.Originator.OriginatorKey;
                PrivateKeyInfo         privInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privKey);
                SubjectPublicKeyInfo   pubInfo  = new SubjectPublicKeyInfo(privInfo.AlgorithmID, origK.PublicKey.GetBytes());
                AsymmetricKeyParameter pubKey   = PublicKeyFactory.CreateKey(pubInfo);

                string wrapAlg = DerObjectIdentifier.GetInstance(
                    Asn1Sequence.GetInstance(_keyEncAlg.Parameters)[0]).Id;

                IBasicAgreement agreement = AgreementUtilities.GetBasicAgreementWithKdf(
                    _keyEncAlg.ObjectID, wrapAlg);

                agreement.Init(privKey);

                BigInteger wKeyNum = agreement.CalculateAgreement(pubKey);
                // TODO Fix the way bytes are derived from the secret
                byte[]       wKeyBytes = wKeyNum.ToByteArrayUnsigned();
                KeyParameter wKey      = ParameterUtilities.CreateKeyParameter(wrapAlg, wKeyBytes);

                IWrapper keyCipher = WrapperUtilities.GetWrapper(wrapAlg);

                keyCipher.Init(false, wKey);

                AlgorithmIdentifier aid = _encAlg;
                string alg = aid.ObjectID.Id;

                byte[] encryptedKey = _encryptedKey.GetOctets();
                byte[] sKeyBytes    = keyCipher.Unwrap(encryptedKey, 0, encryptedKey.Length);

                KeyParameter sKey = ParameterUtilities.CreateKeyParameter(alg, sKeyBytes);

                return(GetContentFromSessionKey(sKey));
            }
            catch (SecurityUtilityException e)
            {
                throw new CmsException("couldn't create cipher.", e);
            }
            catch (InvalidKeyException e)
            {
                throw new CmsException("key invalid in message.", e);
            }
            catch (Exception e)
            {
                throw new CmsException("originator key invalid.", e);
            }
        }
示例#25
0
        public byte[] ToDer()
        {
            var privateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(KeyPair.Private);

            return(privateKey.GetDerEncoded());
        }
示例#26
0
        /// <summary>	Generates a self signed certificate. </summary>
        /// <exception cref="PemException">	Thrown when a Pem error condition occurs. </exception>
        /// <param name="subjectName">      Name of the subject. </param>
        /// <param name="issuerName">       Name of the issuer. </param>
        /// <param name="issuerPrivKey">	The issuer priv key. </param>
        /// <param name="validTill">		The valid till Date/Time. </param>
        /// <param name="keyStrength">      (Optional) The key strength. </param>
        /// <returns>	The self signed certificate. </returns>
        public static X509Certificate2 GenerateSelfSignedCertificate(string subjectName, string issuerName,
                                                                     AsymmetricKeyParameter issuerPrivKey, DateTime validTill, int keyStrength = 2048)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber =
                BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), random);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            // Valid For
            var notBefore = DateTime.UtcNow.Date;
            var notAfter  = validTill;

            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(random, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // selfsign certificate
            var signatureFactory = new Asn1SignatureFactory(SignatureAlgorithm, issuerPrivKey);
            var certificate      = certificateGenerator.Generate(signatureFactory);

            // correcponding private key
            var info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            // merge into X509Certificate2
            var x509 = new X509Certificate2(certificate.GetEncoded());

            var seq = (Asn1Sequence)info.ParsePrivateKey();

            if (seq.Count != 9)
            {
                throw new PemException("malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1,
                rsa.Exponent2,
                rsa.Coefficient);

            x509.PrivateKey = ToDotNetKey(rsaparams);

            return(x509);
        }
        public static byte[] GetRootCertificate()
        {
            Issuer certificationAuthority = GetCurrentCertificationAuthority();

            if (certificationAuthority == null)
            {
                throw new Exception("Cannot find certification authority!");
            }

            var certificate = DatabaseInstance.GetInstance().Certs
                              .Include(elm => elm.Ver_Cert)
                              .Include(elm => elm.SignAlg_Cert).ThenInclude(elm => elm.AlgParSet_SignAlg).ThenInclude(elm => elm.AlgName_AlgParSet)
                              .Include(elm => elm.SignAlg_Cert).ThenInclude(elm => elm.AlgParSet_SignAlg).ThenInclude(elm => elm.HashType_AlgParSet)
                              .Include(elm => elm.SignAlg_Cert).ThenInclude(elm => elm.AlgParSet_SignAlg).ThenInclude(elm => elm.Len_AlgParSet)
                              .Include(elm => elm.Subj_Cert).ThenInclude(elm => elm.Gender_Subj)
                              .Include(elm => elm.Subj_Cert).ThenInclude(elm => elm.Citizen_Subj)
                              .Include(elm => elm.Subj_Cert).ThenInclude(elm => elm.City_Subj).ThenInclude(elm => elm.Region_City).ThenInclude(elm => elm.Country_Region)
                              .Include(elm => elm.Issuer_Cert).ThenInclude(elm => elm.City_Issuer).ThenInclude(elm => elm.Region_City).ThenInclude(elm => elm.Country_Region)
                              .FirstOrDefault(elm => elm.SerialNumber_Cert == elm.SignSerialNumber_Cert);

            if (certificate == null || !IsValid(CreateCertificateFromDatabaseInfo(certificate).GetEncoded()))
            {
                var par = DatabaseInstance.GetInstance().AlgParSets
                          .Include(elm => elm.Len_AlgParSet)
                          .Include(elm => elm.AlgName_AlgParSet)
                          .Include(elm => elm.HashType_AlgParSet)
                          .FirstOrDefault(elm => elm.Len_AlgParSet.Value_Len == 256);
                var    keys   = GenerateKeyPair(par);
                string serial = string.Empty;
                do
                {
                    serial = BigIntegers.CreateRandomBigInteger(512, new SecureRandom()).ToString();
                }while (DatabaseInstance.GetInstance().Certs.FirstOrDefault(elm => elm.SerialNumber_Cert == serial) != null);

                certificate = new Cert
                {
                    Ver_Cert     = DatabaseInstance.GetInstance().Vers.FirstOrDefault(),
                    SignAlg_Cert = new SignAlg
                    {
                        AlgParSet_SignAlg  = par,
                        PrivateKey_SignAlg = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private).ToAsn1Object().GetEncoded(),
                        PublicKey_SignAlg  = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public).ToAsn1Object().GetEncoded()
                    },
                    Issuer_Cert = certificationAuthority,
                    Subj_Cert   = new Subj
                    {
                        Surname_Subj        = "",
                        Name_Subj           = certificationAuthority.Name_Issuer,
                        BirthDate_Subj      = DateTime.Now,
                        Gender_Subj         = DatabaseInstance.GetInstance().Genders.FirstOrDefault(),
                        Citizen_Subj        = DatabaseInstance.GetInstance().Citizens.FirstOrDefault(),
                        City_Subj           = certificationAuthority.City_Issuer,
                        Phone_Subj          = certificationAuthority.Phone_Issuer,
                        EMail_Subj          = certificationAuthority.EMail_Issuer,
                        PassportSerias_Subj = "",
                        PassportNumber_Subj = "",
                        INN_Subj            = certificationAuthority.INN_Issuer,
                        SNILS_Subj          = ""
                    },
                    SerialNumber_Cert     = serial,
                    ValidFrom_Cert        = DateTime.Now,
                    ValidBy_Cert          = DateTimeOffset.Now.AddYears(5).UtcDateTime,
                    SignSerialNumber_Cert = serial
                };

                var cert = CreateCertificateFromDatabaseInfo(certificate);
                certificate.SignValue_Cert = string.Join("", BitConverter.ToString(cert.GetSignature()).Split('-'));

                DatabaseInstance.GetInstance().Certs.Add(certificate);
                DatabaseInstance.GetInstance().SaveChanges();

                return(cert.GetEncoded());
            }

            return(CreateCertificateFromDatabaseInfo(certificate).GetEncoded());
        }
示例#28
0
            public static string PrivateKeyPkcs1ToXml(string privateKey)
            {
                var pemReader = new PemReader(new StringReader(privateKey.AppendPkcs1PrivateKeyFormat()));

                if (pemReader.ReadObject() is not AsymmetricCipherKeyPair asymmetricCipherKeyPair)
                {
                    throw new Exception("Private key format is incorrect");
                }

                var rsaPrivateCrtKeyParameters = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(PrivateKeyInfoFactory.CreatePrivateKeyInfo(asymmetricCipherKeyPair.Private));

                var element = new XElement("RSAKeyValue");

                var privateModulus  = new XElement("Modulus", Convert.ToBase64String(rsaPrivateCrtKeyParameters.Modulus.ToByteArrayUnsigned()));
                var privateExponent = new XElement("Exponent", Convert.ToBase64String(rsaPrivateCrtKeyParameters.PublicExponent.ToByteArrayUnsigned()));
                var privateP        = new XElement("P", Convert.ToBase64String(rsaPrivateCrtKeyParameters.P.ToByteArrayUnsigned()));
                var privateQ        = new XElement("Q", Convert.ToBase64String(rsaPrivateCrtKeyParameters.Q.ToByteArrayUnsigned()));
                var privateDp       = new XElement("DP", Convert.ToBase64String(rsaPrivateCrtKeyParameters.DP.ToByteArrayUnsigned()));
                var privateDq       = new XElement("DQ", Convert.ToBase64String(rsaPrivateCrtKeyParameters.DQ.ToByteArrayUnsigned()));
                var privateInverseQ = new XElement("InverseQ", Convert.ToBase64String(rsaPrivateCrtKeyParameters.QInv.ToByteArrayUnsigned()));
                var privateD        = new XElement("D", Convert.ToBase64String(rsaPrivateCrtKeyParameters.Exponent.ToByteArrayUnsigned()));

                element.Add(privateModulus);
                element.Add(privateExponent);
                element.Add(privateP);
                element.Add(privateQ);
                element.Add(privateDp);
                element.Add(privateDq);
                element.Add(privateInverseQ);
                element.Add(privateD);

                return(element.ToString());
            }
        private static void GenerateSigningCertificate(ICertificatePolicy certificatePolicy, out string thumbprint, out string pemPublicCert, out byte[] pkcs12Data, out System.Security.Cryptography.X509Certificates.X509Certificate2 x509Certificate2)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var random          = new SecureRandom(randomGenerator);

            var kpgen = new RsaKeyPairGenerator();

            kpgen.Init(new KeyGenerationParameters(random, 2048));
            var subjectKeyPair = kpgen.GenerateKeyPair();

            var gen = new X509V3CertificateGenerator();

            X509Name certName;

            if (certificatePolicy.X509NameDictionary == null || !certificatePolicy.X509NameDictionary.Any())
            {
                certName = new X509Name("CN=" + certificatePolicy.CommonName);
            }
            else
            {
                var list = new Dictionary <string, string>();
                AddSubjectNameItem(list, "CN", certificatePolicy.CommonName);
                foreach (var item in certificatePolicy.X509NameDictionary)
                {
                    AddSubjectNameItem(list, item.Key, item.Value);
                }
                certName = new X509Name(GetSubjectNameItemString(list));
            }

            BigInteger serialNo;

            serialNo = BigInteger.ProbablePrime(120, random);

            gen.SetSerialNumber(serialNo);
            gen.SetSubjectDN(certName);
            gen.SetIssuerDN(certName);

            gen.SetNotBefore(DateTime.UtcNow.AddHours(-2)); // go back 2 hours just to be safe
            gen.SetNotAfter(DateTime.UtcNow.AddDays(certificatePolicy.ValidForDays));
            gen.SetSignatureAlgorithm("SHA256WithRSA");
            gen.SetPublicKey(subjectKeyPair.Public);

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

            gen.AddExtension(X509Extensions.KeyUsage.Id,
                             true,
                             new KeyUsage(KeyUsage.DigitalSignature));

            // handle our key purposes
            if (!certificatePolicy.AllPurposes)
            {
                var purposes = new List <KeyPurposeID>();
                if (certificatePolicy.ServerAuthentication)
                {
                    purposes.Add(KeyPurposeID.IdKPServerAuth);
                }
                if (certificatePolicy.ClientAuthentication)
                {
                    purposes.Add(KeyPurposeID.IdKPClientAuth);
                }
                if (certificatePolicy.CodeSigning)
                {
                    purposes.Add(KeyPurposeID.IdKPCodeSigning);
                }
                if (purposes.Any())
                {
                    gen.AddExtension(
                        X509Extensions.ExtendedKeyUsage.Id,
                        true,
                        new ExtendedKeyUsage(purposes.ToArray()));
                }
            }

            var certificate = gen.Generate(subjectKeyPair.Private, random);

            PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key.");
            }

            var rsa = new RsaPrivateKeyStructure(seq);
            RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters(
                rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient);

            // this is exportable to get the bytes of the key to our file system in an encrypted manner
            RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams);
            CspParameters cspParameters = new CspParameters();

            cspParameters.KeyContainerName = Guid.NewGuid().ToString();
            RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters);

            rsaKey.PersistKeyInCsp = false; // do not persist
            rsaKey.ImportParameters(rsaParameters);

            var x509 = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());

            x509.PrivateKey = rsaKey;

            // this is non-exportable
            CspParameters cspParametersNoExport = new CspParameters();

            cspParametersNoExport.KeyContainerName = Guid.NewGuid().ToString();
            cspParametersNoExport.Flags            = CspProviderFlags.UseNonExportableKey;
            RSACryptoServiceProvider rsaKey2 = new RSACryptoServiceProvider(2048, cspParametersNoExport);

            rsaKey2.PersistKeyInCsp = false; // do not persist
            rsaKey2.ImportParameters(rsaParameters);

            x509Certificate2            = new System.Security.Cryptography.X509Certificates.X509Certificate2(certificate.GetEncoded());
            x509Certificate2.PrivateKey = rsaKey2;

            //// Generating Random Numbers
            //var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!";
            //var rnd = new Random();

            //password = new string(
            //    Enumerable.Repeat(chars, 15)
            //              .Select(s => s[rnd.Next(s.Length)])
            //              .ToArray());

            thumbprint = x509.Thumbprint.ToLower();

            var publicKeyPem       = new StringBuilder();
            var utf8WithoutBom     = new System.Text.UTF8Encoding(false);
            var publicKeyPemWriter = new PemWriter(new StringWriterWithEncoding(publicKeyPem, utf8WithoutBom));

            publicKeyPemWriter.WriteObject(certificate);
            publicKeyPemWriter.Writer.Flush();
            pemPublicCert = publicKeyPem.ToString();
            pemPublicCert = pemPublicCert.Replace(Environment.NewLine, "\n"); //only use newline and not returns

            pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx);
        }
示例#30
0
        /// <summary>
        ///     Generates the certificate.
        /// </summary>
        /// <param name="subjectName">Name of the subject.</param>
        /// <param name="issuerName">Name of the issuer.</param>
        /// <param name="validFrom">The valid from.</param>
        /// <param name="validTo">The valid to.</param>
        /// <param name="keyStrength">The key strength.</param>
        /// <param name="signatureAlgorithm">The signature algorithm.</param>
        /// <param name="issuerPrivateKey">The issuer private key.</param>
        /// <param name="hostName">The host name</param>
        /// <returns>X509Certificate2 instance.</returns>
        /// <exception cref="PemException">Malformed sequence in RSA private key</exception>
        private static X509Certificate2 generateCertificate(string?hostName,
                                                            string subjectName,
                                                            string issuerName, DateTime validFrom,
                                                            DateTime validTo, int keyStrength       = 2048,
                                                            string signatureAlgorithm               = "SHA256WithRSA",
                                                            AsymmetricKeyParameter?issuerPrivateKey = null)
        {
            // Generating Random Numbers
            var randomGenerator = new CryptoApiRandomGenerator();
            var secureRandom    = new SecureRandom(randomGenerator);

            // The Certificate Generator
            var certificateGenerator = new X509V3CertificateGenerator();

            // Serial Number
            var serialNumber =
                BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(long.MaxValue), secureRandom);

            certificateGenerator.SetSerialNumber(serialNumber);

            // Issuer and Subject Name
            var subjectDn = new X509Name(subjectName);
            var issuerDn  = new X509Name(issuerName);

            certificateGenerator.SetIssuerDN(issuerDn);
            certificateGenerator.SetSubjectDN(subjectDn);

            certificateGenerator.SetNotBefore(validFrom);
            certificateGenerator.SetNotAfter(validTo);

            if (hostName != null)
            {
                // add subject alternative names
                var nameType = GeneralName.DnsName;
                if (IPAddress.TryParse(hostName, out _))
                {
                    nameType = GeneralName.IPAddress;
                }

                var subjectAlternativeNames = new Asn1Encodable[] { new GeneralName(nameType, hostName) };

                var subjectAlternativeNamesExtension = new DerSequence(subjectAlternativeNames);
                certificateGenerator.AddExtension(X509Extensions.SubjectAlternativeName.Id, false,
                                                  subjectAlternativeNamesExtension);
            }

            // Subject Public Key
            var keyGenerationParameters = new KeyGenerationParameters(secureRandom, keyStrength);
            var keyPairGenerator        = new RsaKeyPairGenerator();

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

            certificateGenerator.SetPublicKey(subjectKeyPair.Public);

            // Set certificate intended purposes to only Server Authentication
            certificateGenerator.AddExtension(X509Extensions.ExtendedKeyUsage.Id, false,
                                              new ExtendedKeyUsage(KeyPurposeID.IdKPServerAuth));
            if (issuerPrivateKey == null)
            {
                certificateGenerator.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(true));
            }

            var signatureFactory = new Asn1SignatureFactory(signatureAlgorithm,
                                                            issuerPrivateKey ?? subjectKeyPair.Private, secureRandom);

            // Self-sign the certificate
            var certificate = certificateGenerator.Generate(signatureFactory);

            // Corresponding private key
            var privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private);

            var seq = (Asn1Sequence)Asn1Object.FromByteArray(privateKeyInfo.ParsePrivateKey().GetDerEncoded());

            if (seq.Count != 9)
            {
                throw new PemException("Malformed sequence in RSA private key");
            }

            var rsa       = RsaPrivateKeyStructure.GetInstance(seq);
            var rsaparams = new RsaPrivateCrtKeyParameters(rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                                                           rsa.Prime1, rsa.Prime2, rsa.Exponent1,
                                                           rsa.Exponent2, rsa.Coefficient);

            // Set private key onto certificate instance
            var x509Certificate = withPrivateKey(certificate, rsaparams);

            if (!doNotSetFriendlyName)
            {
                try
                {
                    x509Certificate.FriendlyName = ProxyConstants.CNRemoverRegex.Replace(subjectName, string.Empty);
                }
                catch (PlatformNotSupportedException)
                {
                    doNotSetFriendlyName = true;
                }
            }

            return(x509Certificate);
        }