コード例 #1
0
        private static RSA CreateRSAKeyFromPem(string key)
        {
            TextReader reader    = new StringReader(key);
            PemReader  pemReader = new PemReader(reader);

            object result = pemReader.ReadObject();

            RSA provider = RSA.Create();

            if (result is AsymmetricCipherKeyPair keyPair)
            {
                var rsaParams = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)keyPair.Private);
                provider.ImportParameters(rsaParams);
                return(provider);
            }
            else if (result is RsaKeyParameters keyParameters)
            {
                var rsaParams = DotNetUtilities.ToRSAParameters(keyParameters);
                provider.ImportParameters(rsaParams);
                return(provider);
            }

            throw new Exception("Unexpected PEM type");
        }
コード例 #2
0
        public void ReadInvalidLabel()
        {
            const string pem = @"
-----BEGIN CERTIFICATE
MIIDCDCCAfCgAwIBAgIUB9Mxn1KLNBaTKu6pYdn3W1EBvWkwDQYJKoZIhvcNAQEL
BQAwFDESMBAGA1UEAwwJQXp1cmUgU0RLMB4XDTIxMDIwNDE5MzUzNVoXDTIxMTAy
NzE5MzUzNVowFDESMBAGA1UEAwwJQXp1cmUgU0RLMIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEA20VE95MMlyn7yu76XmEPBV5Gj7Sn0BzavGTYc497HXRp
y4Ec8edX5C6u7QpO+eQOVlFAbeyIg1/IMGdod8Quarx11mqCyBhXVlStrjqoNTIo
00OA9EFrWjka2ZYrLxlnS6k/w2k18nQE+FP63DIX1OkXU3TxHfVhZWwHgObq5jWz
x4EjG37hnYSJknAB/71N9f2g63cUM28HcGDfMzNrEhbk+TpFfGg3rZiosHybDyDH
x88jTxRxFYBiaWQpNOzZA+M9XUeUK3rdxOfj5JL8ExWGuPMj9QNKGcKkccrLoMtM
5hFP9R8f9nBeeYrmAUsZwU7HWUfaTzWH4goWfZRFQQIDAQABo1IwUDAJBgNVHRME
AjAAMAsGA1UdDwQEAwIF4DATBgNVHSUEDDAKBggrBgEFBQcDATAhBgNVHREEGjAY
gRZhenVyZXNka0BtaWNyb3NvZnQuY29tMA0GCSqGSIb3DQEBCwUAA4IBAQAbUn/U
IrlqGYv417Zwx00VEKOsis3Hafof6KjxQKzHwhNZ2EhLSNIRPrzK3ITbR2f0ZoCO
J5RnL11/KiLA1C9i38aAiekMxxYYikVWkpQHc3BB85v+lhSm5cuSvrdVeTcCXDTA
rJUjjPW4aQuo0GyzL4v1M1U2pByKsVCYAikuLmQKS2zXLoyW3ana1aQYyh2/3cXm
lkApwUZg00+9hRWxv0DTh/mRS2zu5i/9W+cZbIcRah0JHgOzAjvsyY9RHjqZ9r7c
Md7RrFHxnAKJj5TZJJJOf5h3OaaF3A5W8gf9Bc68aGQLFT5Y2afIawkYNSULypc3
pn29yMivL7r48dlo";

            Assert.IsFalse(PemReader.TryRead(pem.AsSpan(), out _));
        }
コード例 #3
0
        public void ReadsPrivateKey(string lineEnding)
        {
            string pem =
                $"-----BEGIN PRIVATE KEY-----{lineEnding}" +
                $"MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDbRUT3kwyXKfvK{lineEnding}" +
                $"7vpeYQ8FXkaPtKfQHNq8ZNhzj3sddGnLgRzx51fkLq7tCk755A5WUUBt7IiDX8gw{lineEnding}" +
                $"Z2h3xC5qvHXWaoLIGFdWVK2uOqg1MijTQ4D0QWtaORrZlisvGWdLqT/DaTXydAT4{lineEnding}" +
                $"U/rcMhfU6RdTdPEd9WFlbAeA5urmNbPHgSMbfuGdhImScAH/vU31/aDrdxQzbwdw{lineEnding}" +
                $"YN8zM2sSFuT5OkV8aDetmKiwfJsPIMfHzyNPFHEVgGJpZCk07NkD4z1dR5Qret3E{lineEnding}" +
                $"5+PkkvwTFYa48yP1A0oZwqRxysugy0zmEU/1Hx/2cF55iuYBSxnBTsdZR9pPNYfi{lineEnding}" +
                $"ChZ9lEVBAgMBAAECggEBALOLCcjrCLEyeHGXszzanrEXnBGJrKt1JQqETNR7FSVu{lineEnding}" +
                $"MD6pjyjo9IfsTeHcwgROYAr/5xDbUIC6SjKQSfNfmV5eyOJ0PnhXrhQLrFdwwlEk{lineEnding}" +
                $"rFco/AuFEcFD5x9pnhyn4XQLtyFsIfdQVs17/nqVLfxxjF8S72hHh6PDjHVZH9i1{lineEnding}" +
                $"daF4woC7obyKqv8+uoc/MEqTgE/bbaQoL8tDUhCcuoKjcBEXpRryWFaeMoolnuTU{lineEnding}" +
                $"D7656CHKFAnloGpNaeNPy8XmpicRxHEODXSoEZDxYoj3SSbPqn/7FDzHqh/Fk3kD{lineEnding}" +
                $"tfjhYdhwZFrlTkvC766DxEBgIQHvJbdjujsX4uLJVQECgYEA/HoOKmA2KgK+f126{lineEnding}" +
                $"oKmF38o4S/8hBd4vT7Qq2Q88zFom7MWrdlHdg5WO0ZLXS+l6LTOVkS2NM+WtbeeF{lineEnding}" +
                $"5el4ICEl0x/Z1/e3vZl0QTDDOKqzfWsVxNwM9FD2bmVjVZHU0o9DPy45ugZdV0ti{lineEnding}" +
                $"9YTm9TLIachAjU5vIIwz6CJ5g9ECgYEA3lSWtSeo76q0hlXE/FN5jn9BeuZHYmCJ{lineEnding}" +
                $"aHYhtG50tXUxghwPRzfTVoQFbUQa1w/Ex4Ny2xZ+OnQTzdBjC13Xz2PAaldrNYlH{lineEnding}" +
                $"5C/LjhbFdOvuQWU3nli9wXq25GTvzla3F5dn0NCUP3xwUIMld1Yq7mCaIy9HrP4i{lineEnding}" +
                $"gn6jZimzNnECgYEAsXdR0bODHxCCuqA1eIzwTxejbrfMjIVamBm6LIyrXbDYv4FK{lineEnding}" +
                $"PobYv482rlUbBH7+pBsoPL3aDOqadzBQTAVJrLvgDIDM7SNwgdMFhnUyI/jI5ZWJ{lineEnding}" +
                $"3bAXYvwt2/dkVVeGUuLkj9p8NSgYIC4bRxy+AwhJGyHpTeod7rDeI4NoCqECgYB1{lineEnding}" +
                $"DKWXU/ztyLpn6undSfk6GycXE/tLALX2yBKwkmJhUgSxkiI9BVf/OVw+DVfwF34q{lineEnding}" +
                $"57plO69TCN+QQICUcGB47/RSSBnKQq8VpFAPS0/DYZ660RX6CJBGN1voXHef8ylL{lineEnding}" +
                $"g0uFtPoHfnUG/jSQYk4R18vucCrVGaqDdzaBR7zxEQKBgCEqovhMGJ1xOrkzetBB{lineEnding}" +
                $"+zgh5zJbAWx5DQk5ZdmAcAnEeqconM2yhFB636wC07UbeAZaQmhB5kQYMOuiCstt{lineEnding}" +
                $"30sdQlNG9EGdqNsoVn/363Cg1iKJy4JU5uW/5kjh4UfBZG6DDwjLK88ZWh0OHPRV{lineEnding}" +
                $"h8q0or9YnvqnVrELMR8cjUkZ{lineEnding}" +
                $"-----END PRIVATE KEY-----";

            Assert.IsTrue(PemReader.TryRead(pem.AsSpan(), out PemReader.PemField field));
            Assert.AreEqual("PRIVATE KEY", field.Label.ToString());
            Assert.AreEqual(PrivateKeyBytes, field.FromBase64Data());
        }
コード例 #4
0
        public override Crt ImportCertificate(EncodingFormat fmt, Stream source)
        {
            if (false)
            {
                throw new NotImplementedException();
            }

            X509Certificate bcCert = null;

            if (fmt == EncodingFormat.DER)
            {
                var certParser = new X509CertificateParser();
                bcCert = certParser.ReadCertificate(source);
            }
            else if (fmt == EncodingFormat.PEM)
            {
                using (var tr = new StreamReader(source))
                {
                    var pr = new PemReader(tr);
                    bcCert = (X509Certificate)pr.ReadObject();
                }
            }
            else
            {
                throw new NotSupportedException("encoding format has not been implemented");
            }

            using (var tw = new StringWriter())
            {
                var pw = new PemWriter(tw);
                pw.WriteObject(bcCert);
                return(new Crt {
                    Pem = tw.GetStringBuilder().ToString()
                });
            }
        }
コード例 #5
0
        public void ExportSubjectPublicKeyInfo(AsnFormat format)
        {
            using ECDsa ecdsa = ECDsa.Create(ECCurve.NamedCurves.nistP256);
            byte[] exported = ecdsa.ExportSubjectPublicKeyInfo(format);

            if (format == AsnFormat.Der)
            {
                SubjectPublicKeyInfo info = SubjectPublicKeyInfo.GetInstance(Asn1Object.FromByteArray(exported));
                Assert.IsNotNull(info);
                Assert.IsNotNull(info.AlgorithmID);
                Assert.IsNotNull(info.PublicKeyData);
            }

            if (format == AsnFormat.Pem)
            {
                using MemoryStream ms = new MemoryStream(exported);
                using TextReader tr   = new StreamReader(ms, Encoding.ASCII);
                PemReader pemReader = new PemReader(tr);
                object    obj       = pemReader.ReadObject();
                Assert.IsNotNull(obj);
            }

            this.CheckFormat(format, exported);
        }
コード例 #6
0
 private void InitializeRsa()
 {
     using (RSA publicRsa = RSA.Create())
     {
         var publicKeyXml = _settings.UseRsaFilePath ?
                            System.IO.File.ReadAllText(_settings.RsaPublicKeyXML) :
                            _settings.RsaPublicKeyXML;
         RSACryptoServiceProviderExtensions.FromXmlString(publicRsa, publicKeyXml);
         _issuerSigningKey = new RsaSecurityKey(publicRsa);
     }
     if (_settings.RsaPrivateKey.Empty())
     {
         return;
     }
     using (RSA privateRsa = RSA.Create())
     {
         if (_settings.UseRsaFilePath)
         {
             using (var streamReader = File.OpenText(_settings.RsaPrivateKey))
             {
                 var pemReader = new PemReader(streamReader);
                 privateRsa.ImportParameters(pemReader.ReadPrivatekey());
             }
         }
         else
         {
             using (var stringReader = new StringReader(_settings.RsaPrivateKey))
             {
                 var pemReader = new PemReader(stringReader);
                 privateRsa.ImportParameters(pemReader.ReadPrivatekey());
             }
         }
         var privateKey = new RsaSecurityKey(privateRsa);
         _signingCredentials = new SigningCredentials(privateKey, SecurityAlgorithms.RsaSha256);
     }
 }
コード例 #7
0
        /// <summary>
        /// Gets the decrypted password using the RSA private key which can be found in the
        /// PEM file for the key pair.
        /// </summary>
        /// <param name="rsaPrivateKey">The RSA private key from the PEM file</param>
        /// <returns>The decrypted password</returns>
        public string GetDecryptedPassword(string rsaPrivateKey)
        {
            RSAParameters rsaParams;

            try
            {
                rsaParams = new PemReader(new StringReader(rsaPrivateKey.Trim())).ReadPrivatekey();
            }
            catch (Exception e)
            {
                throw new AmazonEC2Exception("Invalid RSA Private Key", e);
            }

            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(rsaParams);

            byte[] encryptedBytes = Convert.FromBase64String(this.PasswordData);
            var    decryptedBytes = rsa.Decrypt(encryptedBytes, false);

            string decrypted = Encoding.UTF8.GetString(decryptedBytes);

            return(decrypted);
        }
コード例 #8
0
        public static BcCertificate ImportCertificate(EncodingFormat fmt, Stream source)
        {
            X509Certificate bcCert = null;

            if (fmt == EncodingFormat.DER)
            {
                var certParser = new X509CertificateParser();
                bcCert = certParser.ReadCertificate(source);
            }
            else if (fmt == EncodingFormat.PEM)
            {
                using (var tr = new StreamReader(source))
                {
                    var pr = new PemReader(tr);
                    bcCert = (X509Certificate)pr.ReadObject();
                }
            }
            else
            {
                throw new NotSupportedException("encoding format has not been implemented");
            }

            return(bcCert);
        }
コード例 #9
0
        public static ECDsa GetTestUserPlatformEcdsaProvider()
        {
            using (var stringReader = new StringReader(TestUserEcdsaPrivKey))
            {
                var pemReader          = new PemReader(stringReader);
                var ecdsaPrivKeyParams = pemReader.ReadObject() as ECPrivateKeyParameters;

                var Q = ecdsaPrivKeyParams.Parameters.G.Multiply(ecdsaPrivKeyParams.D);
                var ecdsaPubKeyParams = new ECPublicKeyParameters(Q, ecdsaPrivKeyParams.Parameters);

                ECParameters ecParams = new ECParameters()
                {
                    Curve = ECCurve.CreateFromValue(ecdsaPrivKeyParams.PublicKeyParamSet.Id),
                    D     = ecdsaPrivKeyParams.D.ToByteArrayUnsigned(),
                    Q     = new ECPoint()
                    {
                        X = ecdsaPubKeyParams.Q.XCoord.ToBigInteger().ToByteArrayUnsigned(),
                        Y = ecdsaPubKeyParams.Q.YCoord.ToBigInteger().ToByteArrayUnsigned()
                    }
                };

                return(ECDsa.Create(ecParams));
            }
        }
コード例 #10
0
        AsymmetricKeyParameter DnsLookup(string domain, string selector, CancellationToken cancellationToken)
        {
            var query = selector + "._domainkey." + domain;
            AsymmetricKeyParameter pubkey;

            // checked if we've already fetched this key
            if (cache.TryGetValue(query, out pubkey))
            {
                return(pubkey);
            }

            // make a DNS query
            var response = resolver.Query(query, QType.TXT);
            var builder  = new StringBuilder();

            // combine the TXT records into 1 string buffer
            foreach (var record in response.RecordsTXT)
            {
                foreach (var text in record.TXT)
                {
                    builder.Append(text);
                }
            }

            var    txt = builder.ToString();
            string k = null, p = null;
            int    index = 0;

            // parse the response (will look something like: "k=rsa; p=<base64>")
            while (index < txt.Length)
            {
                while (index < txt.Length && char.IsWhiteSpace(txt[index]))
                {
                    index++;
                }

                if (index == txt.Length)
                {
                    break;
                }

                // find the end of the key
                int startIndex = index;
                while (index < txt.Length && txt[index] != '=')
                {
                    index++;
                }

                if (index == txt.Length)
                {
                    break;
                }

                var key = txt.Substring(startIndex, index - startIndex);

                // skip over the '='
                index++;

                // find the end of the value
                startIndex = index;
                while (index < txt.Length && txt[index] != ';')
                {
                    index++;
                }

                var value = txt.Substring(startIndex, index - startIndex);

                switch (key)
                {
                case "k": k = value; break;

                case "p": p = value; break;
                }

                // skip over the ';'
                index++;
            }

            if (k != null && p != null)
            {
                var data    = "-----BEGIN PUBLIC KEY-----\r\n" + p + "\r\n-----END PUBLIC KEY-----\r\n";
                var rawData = Encoding.ASCII.GetBytes(data);

                using (var stream = new MemoryStream(rawData, false)) {
                    using (var reader = new StreamReader(stream)) {
                        var pem = new PemReader(reader);

                        pubkey = pem.ReadObject() as AsymmetricKeyParameter;

                        if (pubkey != null)
                        {
                            cache.Add(query, pubkey);

                            return(pubkey);
                        }
                    }
                }
            }

            throw new Exception(string.Format("Failed to look up public key for: {0}", domain));
        }
コード例 #11
0
        private void keyPairTest(
			string					name,
			IAsymmetricCipherKeyPair	pair)
        {
            MemoryStream bOut = new MemoryStream();
            PemWriter pWrt = new PemWriter(new StreamWriter(bOut));

            pWrt.WriteObject(pair.Public);
            pWrt.Writer.Close();

            PemReader pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));

            IAsymmetricKeyParameter pubK = (AsymmetricKeyParameter) pemRd.ReadObject();
            if (!pubK.Equals(pair.Public))
            {
                Fail("Failed public key read: " + name);
            }

            bOut = new MemoryStream();
            pWrt = new PemWriter(new StreamWriter(bOut));

            pWrt.WriteObject(pair.Private);
            pWrt.Writer.Close();

            pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));

            IAsymmetricCipherKeyPair kPair = (AsymmetricCipherKeyPair) pemRd.ReadObject();
            if (!kPair.Private.Equals(pair.Private))
            {
                Fail("Failed private key read: " + name);
            }

            if (!kPair.Public.Equals(pair.Public))
            {
                Fail("Failed private key public read: " + name);
            }
        }
コード例 #12
0
        /// <summary>
        /// Load an RSA private key from a OpenSSL style file (DER or PEM)
        /// </summary>
        /// <param name="keyFile">The file to load</param>
        /// <param name="password">The optional password</param>
        /// <param name="signature">Whether to load  the key as a signature or key exchange</param>
        /// <returns>The RSA algorithm object</returns>
        public static RSA ImportPrivateKeyFromPEM(string keyFile, string password, bool signature)
        {
            RSA ret = null;

            byte[] data = File.ReadAllBytes(keyFile);
            RsaPrivateCrtKeyParameters keyParams = null;

            if (data.Length > 0)
            {
                if (data[0] != 0x30)
                {
                    try
                    {
                        // Probably a PEM file
                        using (StreamReader reader = new StreamReader(new MemoryStream(data)))
                        {
                            PemReader pem;

                            if (password != null)
                            {
                                pem = new PemReader(reader, new PasswordFinderClass(password));
                            }
                            else
                            {
                                pem = new PemReader(reader);
                            }

                            object o = pem.ReadObject();

                            while (o != null)
                            {
                                if (o is RsaPrivateCrtKeyParameters)
                                {
                                    keyParams = o as RsaPrivateCrtKeyParameters;
                                    break;
                                }
                                else if (o is AsymmetricCipherKeyPair)
                                {
                                    AsymmetricCipherKeyPair pair = o as AsymmetricCipherKeyPair;

                                    keyParams = pair.Private as RsaPrivateCrtKeyParameters;
                                    break;
                                }

                                o = pem.ReadObject();
                            }
                        }
                    }
                    catch (InvalidCipherTextException)
                    {
                        // Catch this exception and convert to standard CryptographicException
                        throw new CryptographicException("Cannot decrypt private key");
                    }
                }
                else
                {
                    Asn1Sequence seq = (Asn1Sequence)Asn1Object.FromByteArray(data);

                    if (seq.Count != 9)
                    {
                        throw new CryptographicException("Malformed ASN.1 Sequence");
                    }

                    RsaPrivateKeyStructure rsa = RsaPrivateKeyStructure.GetInstance(seq);

                    keyParams = new RsaPrivateCrtKeyParameters(
                        rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent,
                        rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2,
                        rsa.Coefficient);
                }

                if (keyParams != null)
                {
                    ret = LoadKey(keyParams, signature);
                }
            }

            return(ret);
        }
コード例 #13
0
 public void LoadECDsaCertificateAutomatically()
 {
     // Support for ECDsa certificates are not supported by default. See Azure.Security.KeyVault.Certificates for support.
     Assert.Throws <NotSupportedException>(() => PemReader.LoadCertificate(ECDsaCertificate.AsSpan(), keyType: PemReader.KeyType.Auto));
 }
コード例 #14
0
ファイル: Utils.cs プロジェクト: Fart03/lau
        public static byte[] GetRSABytes(byte[] bytes, string key)
        {
            if (key == null)
            {
                key =
                    "-----BEGIN RSA PUBLIC KEY-----\n" +
                    "MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6\n" +
                    "lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS\n" +
                    "an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw\n" +
                    "Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+\n" +
                    "8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n\n" +
                    "Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB\n" +
                    "-----END RSA PUBLIC KEY-----";
            }

            using (var text = new StringReader(key))
            {
                var reader    = new PemReader(text);
                var parameter = reader.ReadObject() as RsaKeyParameters;
                if (parameter != null)
                {
                    var modulus  = parameter.Modulus;
                    var exponent = parameter.Exponent;

                    var num = new BigInteger(new byte[] { 0x00 }.Concat(bytes).ToArray());
                    var rsa = num.ModPow(exponent, modulus).ToByteArray();

#if LOG_REGISTRATION
                    TLUtils.WriteLog("RSA bytes length " + rsa.Length);
#endif
                    if (rsa.Length == 257)
                    {
                        if (rsa[0] != 0x00)
                        {
                            throw new Exception("rsa last byte is " + rsa[0]);
                        }

#if LOG_REGISTRATION
                        TLUtils.WriteLog("First RSA byte removes: byte value is " + rsa[0]);
#endif
                        TLUtils.WriteLine("First RSA byte removes: byte value is " + rsa[0]);
                        rsa = rsa.SubArray(1, 256);
                    }
                    else if (rsa.Length < 256)
                    {
                        var correctedRsa = new byte[256];
                        Array.Copy(rsa, 0, correctedRsa, 256 - rsa.Length, rsa.Length);
                        for (var i = 0; i < 256 - rsa.Length; i++)
                        {
                            correctedRsa[i] = 0;
#if LOG_REGISTRATION
                            TLUtils.WriteLog("First RSA bytes added i=" + i + " " + correctedRsa[i]);
#endif
                        }
                        rsa = correctedRsa;
                    }

                    return(rsa);
                }
            }

            return(null);
        }
コード例 #15
0
        public async Task ValidateMergeCertificate()
        {
            string serverCertificateName = Recording.GenerateId();

            // Generate the request.
            CertificatePolicy policy = new CertificatePolicy(WellKnownIssuerNames.Unknown, "CN=Azure SDK")
            {
                CertificateTransparency = false,
                ContentType             = CertificateContentType.Pkcs12,
            };

            CertificateOperation operation = await Client.StartCreateCertificateAsync(serverCertificateName, policy);

            RegisterForCleanup(serverCertificateName);
            await using IAsyncDisposable disposableOperation = EnsureDeleted(operation);

            // Read the CA.
            byte[]           caCertificateBytes = Convert.FromBase64String(CaPublicKeyBase64);
            X509Certificate2 caCertificate      = new X509Certificate2(caCertificateBytes);

            // Read CA private key since getting it from caCertificate above throws.
            AsymmetricCipherKeyPair caPrivateKey;

            using (StringReader caPrivateKeyReader = new StringReader(CaPrivateKeyPem))
            {
                PemReader reader = new PemReader(caPrivateKeyReader);
                caPrivateKey = (AsymmetricCipherKeyPair)reader.ReadObject();
            }

            // Read the CSR.
            Pkcs10CertificationRequest csr     = new Pkcs10CertificationRequest(operation.Properties.Csr);
            CertificationRequestInfo   csrInfo = csr.GetCertificationRequestInfo();

            // Parse the issuer subject name.
            Hashtable oidLookup = new Hashtable(X509Name.DefaultLookup)
            {
                { "s", new DerObjectIdentifier("2.5.4.8") },
            };

            X509Name issuerName = new X509Name(true, oidLookup, caCertificate.Subject);

            // Sign the request.
            X509V3CertificateGenerator generator = new X509V3CertificateGenerator();

            generator.SetIssuerDN(issuerName);
            generator.SetSerialNumber(BigInteger.One);
            generator.SetNotBefore(DateTime.Now);
            generator.SetNotAfter(DateTime.Now.AddDays(1));
            generator.SetSubjectDN(csrInfo.Subject);
            generator.SetPublicKey(csr.GetPublicKey());

            Asn1SignatureFactory signatureFactory      = new Asn1SignatureFactory("SHA256WITHRSA", caPrivateKey.Private);
            X509Certificate      serverSignedPublicKey = generator.Generate(signatureFactory);

            // Merge the certificate chain.
            MergeCertificateOptions       options = new MergeCertificateOptions(serverCertificateName, new[] { serverSignedPublicKey.GetEncoded(), caCertificateBytes });
            KeyVaultCertificateWithPolicy mergedServerCertificate = await Client.MergeCertificateAsync(options);

            X509Certificate2 serverCertificate = new X509Certificate2(mergedServerCertificate.Cer);

            Assert.AreEqual(csrInfo.Subject.ToString(), serverCertificate.Subject);
            Assert.AreEqual(serverCertificateName, mergedServerCertificate.Name);

            KeyVaultCertificateWithPolicy completedServerCertificate = await WaitForCompletion(operation);

            Assert.AreEqual(mergedServerCertificate.Name, completedServerCertificate.Name);
            CollectionAssert.AreEqual(mergedServerCertificate.Cer, completedServerCertificate.Cer);
        }
コード例 #16
0
        public void LoadCertificateWithoutPrivateKey()
        {
            Exception ex = Assert.Throws <InvalidDataException>(() => PemReader.LoadCertificate(ECDsaCertificate.AsSpan(), keyType: PemReader.KeyType.ECDsa));

            Assert.AreEqual("The certificate is missing the private key", ex.Message);
        }
コード例 #17
0
        public void LoadCertificateWithNoKeys()
        {
            Exception ex = Assert.Throws <InvalidDataException>(() => PemReader.LoadCertificate(Span <char> .Empty, keyType: PemReader.KeyType.ECDsa));

            Assert.AreEqual("The certificate is missing the public key", ex.Message);
        }
コード例 #18
0
ファイル: CngBuilder.cs プロジェクト: holytshirt/Jwt4Net
 public CngBuilder(PemReader theReader)
 {
     _theReader = theReader;
 }
コード例 #19
0
        /// <summary>
        /// Get the public key from a DNS TXT record.
        /// </summary>
        /// <remarks>
        /// Gets the public key from a DNS TXT record.
        /// </remarks>
        /// <param name="txt">The DNS TXT record.</param>
        /// <returns>The public key.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// The <paramref name="txt"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="ParseException">
        /// There was an error parsing the DNS TXT record.
        /// </exception>
        protected AsymmetricKeyParameter GetPublicKey(string txt)
        {
            AsymmetricKeyParameter pubkey;
            string k = null, p = null;
            int    index = 0;

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

            // parse the response (will look something like: "k=rsa; p=<base64>")
            while (index < txt.Length)
            {
                while (index < txt.Length && char.IsWhiteSpace(txt[index]))
                {
                    index++;
                }

                if (index == txt.Length)
                {
                    break;
                }

                // find the end of the key
                int startIndex = index;
                while (index < txt.Length && txt[index] != '=')
                {
                    index++;
                }

                if (index == txt.Length)
                {
                    break;
                }

                var key = txt.Substring(startIndex, index - startIndex);

                // skip over the '='
                index++;

                // find the end of the value
                startIndex = index;
                while (index < txt.Length && txt[index] != ';')
                {
                    index++;
                }

                var value = txt.Substring(startIndex, index - startIndex);

                switch (key)
                {
                case "k":
                    switch (value)
                    {
                    case "rsa":
                    case "ed25519": k = value; break;

                    default: throw new ParseException($"Unknown public key algorithm: {value}", startIndex, index);
                    }
                    break;

                case "p":
                    p = value.Replace(" ", "");
                    break;
                }

                // skip over the ';'
                index++;
            }

            if (k != null && p != null)
            {
                if (k == "ed25519")
                {
                    var decoded = Convert.FromBase64String(p);

                    return(new Ed25519PublicKeyParameters(decoded, 0));
                }

                var data    = "-----BEGIN PUBLIC KEY-----\r\n" + p + "\r\n-----END PUBLIC KEY-----\r\n";
                var rawData = Encoding.ASCII.GetBytes(data);

                using (var stream = new MemoryStream(rawData, false)) {
                    using (var reader = new StreamReader(stream)) {
                        var pem = new PemReader(reader);

                        pubkey = pem.ReadObject() as AsymmetricKeyParameter;

                        if (pubkey != null)
                        {
                            return(pubkey);
                        }
                    }
                }
            }

            throw new ParseException("Public key parameters not found in DNS TXT record.", 0, txt.Length);
        }
コード例 #20
0
        public void TestMalformed()
        {
            PemReader rd = new PemReader(new StringReader("-----BEGIN \n"));

            Assert.IsNull(rd.ReadPemObject());
        }
コード例 #21
0
        private void ConfigureClientWithMachineEnv()
        {
            var envResult = RunDockerMachine("env", MachineName);

            if (envResult.ExitCode != 0)
            {
                throw new DockerMachineExecutionException("Could not read machine environment", envResult.ExitCode, envResult.Output);
            }

            var outputLines = envResult.Output.Split('\n').Where(x => x.Contains('=')).ToArray();
            var envOutput   = outputLines
                              .Select(x => x.StartsWith("$Env:") ? x.Substring("$Env:".Length) : x)
                              .Select(x => x.StartsWith("SET") ? x.Substring("SET".Length) : x)
                              .Select(x => x.Split('='))
                              .Select(x => (key: x[0].Trim(), value: x[1].Trim()))
                              .ToDictionary(x => x.key, x => x.value);

            var host        = envOutput["DOCKER_HOST"];
            var machineName = envOutput["DOCKER_MACHINE_NAME"];

            var machineUsesTls = false;

            try {
                var tlsVerify = envOutput["DOCKER_TLS_VERIFY"];

                if (!string.IsNullOrEmpty(tlsVerify))
                {
                    machineUsesTls = true;
                }
            } catch (KeyNotFoundException) { }

            var certsPath = envOutput["DOCKER_CERT_PATH"];
            var pfxPath   = Path.Combine(certsPath, "key.pfx");

            // Adapted from https://stackoverflow.com/a/46598020/528131
            if (machineUsesTls)
            {
                var cerPath = Path.Combine(certsPath, "cert.pem");
                var keyPath = Path.Combine(certsPath, "key.pem");

                X509Certificate         publicKey  = null;
                AsymmetricCipherKeyPair privateKey = null;

                using (var cerFile = File.OpenRead(cerPath)) {
                    using (var cerDataReader = new StreamReader(cerFile)) {
                        var cerReader = new PemReader(cerDataReader);
                        publicKey = (X509Certificate)cerReader.ReadObject();
                    }
                }

                using (var keyFile = File.OpenRead(keyPath)) {
                    using (var keyDataReader = new StreamReader(keyFile)) {
                        var keyReader = new PemReader(keyDataReader);
                        privateKey = (AsymmetricCipherKeyPair)keyReader.ReadObject();
                    }
                }

                var certStore = new Pkcs12StoreBuilder().Build();
                var certChain = new X509CertificateEntry[1];

                var privateKeyEntry = new AsymmetricKeyEntry(privateKey.Private);
                var publicKeyEntry  = new X509CertificateEntry(publicKey);

                certChain[0] = publicKeyEntry;
                certStore.SetKeyEntry("dockerHostKey", privateKeyEntry, certChain);

                if (File.Exists(pfxPath))
                {
                    File.Delete(pfxPath);
                }

                using (var pfxFile = File.Create(pfxPath)) {
                    certStore.Save(pfxFile, new char[0], new SecureRandom());
                }
            }

            ConfigureClientWithHost(host, machineUsesTls, pfxPath);
        }
コード例 #22
0
        public static AsymmetricCipherKeyPair LoadRsaKey(StreamReader keyStream)
        {
            var pemReader = new PemReader(keyStream);

            return((AsymmetricCipherKeyPair)pemReader.ReadObject());
        }
コード例 #23
0
 public void ReadWithExtraneousData()
 {
     Assert.IsTrue(PemReader.TryRead(RsaPemPrivateKey.AsSpan(), out PemReader.PemField field));
     Assert.AreEqual("PRIVATE KEY", field.Label.ToString());
     Assert.AreEqual(s_rsaPrivateKeyBytes, field.FromBase64Data());
 }
コード例 #24
0
        /**
         * Determines whether the current AppKeyPair (as specified by {@link #pemFilePathname}) is a valid X.509 certificate.
         * <br /><br />
         * Writes diagnostic messages to the console if the the current AppKeyPair does not exist or is not valid.
         * This is useful since SkypeKit currently reports only "TLS handshake failure" (with no further explanation)
         * if the certificate can't be found/accessed or is not validly formatted.
         *
         * @return
         * 	<ul>
         *	  <li>true: Valid certificate file</li>
         *	  <li>false:
         *	    <ul>
         *	      <li>Could not open the file</li>
         *	      <li>Could not read the file</li>
         *	      <li>Not a valid certificate file</li>
         *	    </ul>
         *	  </li>
         *	</ul>
         *
         * @see #pemFilePathname
         * @see com.skype.tutorial.util.MySession#myClientConfiguration
         * @since 2.0
         */
        public bool isValidCertificate()
        {
            java.security.cert.X509Certificate x509CertificateData;
            java.security.PrivateKey privateKeyData;

            String pathName = getPemFilePathname();

            try
            {
                String derPath = pathName.Substring(0, pathName.Length - 3);
                derPath += "der";

                PemReader myPemReader = new PemReader(getPemFilePathname());
                x509CertificateData = myPemReader.getCertificate();
                privateKeyData = myPemReader.getKey();
            }
            catch (FileNotFoundException e1)
            {
                MySession.myConsole.printf("%s/isValidCertificate: Could not find certificate file:%n\t%s%n",
                        MY_CLASS_TAG, pathName);
                return (false);
            }
            catch (IOException e2)
            {
                MySession.myConsole.printf("%s/isValidCertificate: Unable to read certificate file:%n\t%s%n",
                           MY_CLASS_TAG, pathName);
                return (false);
            }
            catch (Exception e3)
            {
                MySession.myConsole.printf("%s/isValidCertificate: Certificate file %s contains invalid certficate data.%n",
                        MY_CLASS_TAG, pathName);
                return (false);
            }

            if ((x509CertificateData != null) && (privateKeyData != null))
            {
                MySession.myConsole.printf("%s/isValidCertificate: Certificate has valid format%n",
                       MY_CLASS_TAG);
                return (true);
            }
            else
            {
                MySession.myConsole.printf("%s/isValidCertificate: Certificate has invalid format%n",
                        MY_CLASS_TAG);
                return (false);
            }
        }
コード例 #25
0
        public async void StartMQTT(string clientid, string cafile, string clientcertfile, string clientprivate, string clientprivatepassword = "")
        {
            var ca = new X509Certificate(cafile, "");

            var reader     = new PemReader(File.OpenText(clientprivate));
            var privatekey = (AsymmetricCipherKeyPair)reader.ReadObject();
            var pkinfo     = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)privatekey.Private;

            var ce1 = new X509Certificate2(File.ReadAllBytes(clientcertfile), clientprivatepassword,
                                           X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            CspParameters parms = new CspParameters();

            parms.Flags            = CspProviderFlags.NoFlags;
            parms.KeyContainerName = Guid.NewGuid().ToString().ToUpperInvariant();
            parms.ProviderType     = ((Environment.OSVersion.Version.Major > 5) || ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1))) ? 0x18 : 1;

            System.Security.Cryptography.RSACryptoServiceProvider rcsp =
                new System.Security.Cryptography.RSACryptoServiceProvider(parms)
            {
                PersistKeyInCsp = true
            };

            rcsp.ImportParameters(DotNetUtilities.ToRSAParameters(pkinfo));
            ce1.PrivateKey = rcsp;

            //var clientcert = CertificatesToDBandBack.Certificate.GetCertificateFromPEMstring(File.ReadAllText(clientcertfile), File.ReadAllText(clientprivate), clientprivatepassword);

            MQTTClient = new MqttFactory().CreateMqttClient();
            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(mqtt_host, mqtt_port).WithClientId(clientid).WithTls(new MqttClientOptionsBuilderTlsParameters
            {
                AllowUntrustedCertificates        = false,
                IgnoreCertificateChainErrors      = false,
                IgnoreCertificateRevocationErrors = false,
                UseTls       = true,
                SslProtocol  = System.Security.Authentication.SslProtocols.Tls12,
                Certificates = new List <byte[]>
                {
                    ca.Export(X509ContentType.SerializedCert),
                    ce1.Export(X509ContentType.SerializedCert)
                },
                CertificateValidationCallback = (X509Certificate x, X509Chain y, SslPolicyErrors z, IMqttClientOptions o) =>
                {
                    return(true);
                }
            }).Build();

            MQTTClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
            });
            MQTTClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async a =>
            {
                Console.WriteLine("### CONNECTED WITH SERVER ###");
                await MQTTClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
            });
            MQTTClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async a =>
            {
                Console.WriteLine("### DISCONNECTED FROM SERVER ###");
            });

            var connect = await MQTTClient.ConnectAsync(options);

            var sub = MQTTClient.SubscribeAsync(new TopicFilter
            {
                Topic = "test", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
            });
        }
コード例 #26
0
        public AsymmetricKeyParameter LocatePublicKey(string methods, string domain, string selector, CancellationToken cancellationToken = default(CancellationToken))
        {
            var query = selector + "._domainkey." + domain;

            if (keys.TryGetValue(query, out string txt))
            {
                AsymmetricKeyParameter pubkey;
                string k = null, p = null;
                int    index = 0;

                // parse the response (will look something like: "k=rsa; p=<base64>")
                while (index < txt.Length)
                {
                    while (index < txt.Length && char.IsWhiteSpace(txt[index]))
                    {
                        index++;
                    }

                    if (index == txt.Length)
                    {
                        break;
                    }

                    // find the end of the key
                    int startIndex = index;
                    while (index < txt.Length && txt[index] != '=')
                    {
                        index++;
                    }

                    if (index == txt.Length)
                    {
                        break;
                    }

                    var key = txt.Substring(startIndex, index - startIndex);

                    // skip over the '='
                    index++;

                    // find the end of the value
                    startIndex = index;
                    while (index < txt.Length && txt[index] != ';')
                    {
                        index++;
                    }

                    var value = txt.Substring(startIndex, index - startIndex).Replace(" ", "");

                    switch (key)
                    {
                    case "k": k = value; break;

                    case "p": p = value; break;
                    }

                    // skip over the ';'
                    index++;
                }

                if (k != null && p != null)
                {
                    if (k == "rsa")
                    {
                        var data    = "-----BEGIN PUBLIC KEY-----\r\n" + p + "\r\n-----END PUBLIC KEY-----\r\n";
                        var rawData = Encoding.ASCII.GetBytes(data);

                        using (var stream = new MemoryStream(rawData, false)) {
                            using (var reader = new StreamReader(stream)) {
                                var pem = new PemReader(reader);

                                pubkey = pem.ReadObject() as AsymmetricKeyParameter;

                                if (pubkey != null)
                                {
                                    return(pubkey);
                                }
                            }
                        }
                    }
                    else if (k == "ed25519")
                    {
                        var decoded = Convert.FromBase64String(p);

                        return(new Ed25519PublicKeyParameters(decoded, 0));
                    }
                }
            }

            throw new Exception(string.Format("Failed to look up public key for: {0}", domain));
        }
コード例 #27
0
        /// <summary>
        /// Generates pfx from client configuration
        /// </summary>
        /// <param name="config">Kubernetes Client Configuration</param>
        /// <returns>Generated Pfx Path</returns>
        public static X509Certificate2 GeneratePfx(KubernetesClientConfiguration config)
        {
            byte[] keyData  = null;
            byte[] certData = null;

            if (!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData))
            {
                keyData = Convert.FromBase64String(config.ClientCertificateKeyData);
            }
            if (!string.IsNullOrWhiteSpace(config.ClientKeyFilePath))
            {
                keyData = File.ReadAllBytes(config.ClientKeyFilePath);
            }

            if (keyData == null)
            {
                throw new KubeConfigException("keyData is empty");
            }

            if (!string.IsNullOrWhiteSpace(config.ClientCertificateData))
            {
                certData = Convert.FromBase64String(config.ClientCertificateData);
            }
            if (!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath))
            {
                certData = File.ReadAllBytes(config.ClientCertificateFilePath);
            }

            if (certData == null)
            {
                throw new KubeConfigException("certData is empty");
            }

            var cert = new X509CertificateParser().ReadCertificate(new MemoryStream(certData));

            // key usage is a bit string, zero-th bit is 'digitalSignature'
            // See https://www.alvestrand.no/objectid/2.5.29.15.html for more details.
            if (cert != null && cert.GetKeyUsage() != null && !cert.GetKeyUsage()[0])
            {
                throw new Exception(
                          "Client certificates must be marked for digital signing. " +
                          "See https://github.com/kubernetes-client/csharp/issues/319");
            }
            object obj;

            using (var reader = new StreamReader(new MemoryStream(keyData)))
            {
                obj = new PemReader(reader).ReadObject();
                var key = obj as AsymmetricCipherKeyPair;
                if (key != null)
                {
                    var cipherKey = key;
                    obj = cipherKey.Private;
                }
            }

            var keyParams = (AsymmetricKeyParameter)obj;

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

            store.SetKeyEntry("K8SKEY", new AsymmetricKeyEntry(keyParams), new[] { new X509CertificateEntry(cert) });

            using (var pkcs = new MemoryStream())
            {
                store.Save(pkcs, new char[0], new SecureRandom());

                if (config.ClientCertificateKeyStoreFlags.HasValue)
                {
                    return(new X509Certificate2(pkcs.ToArray(), "", config.ClientCertificateKeyStoreFlags.Value));
                }
                else
                {
                    return(new X509Certificate2(pkcs.ToArray()));
                }
            }
        }
コード例 #28
0
ファイル: ReaderTest.cs プロジェクト: tcz1237/MissionPlanner
        public override void PerformTest()
        {
            IPasswordFinder         pGet  = new Password("secret".ToCharArray());
            PemReader               pemRd = OpenPemResource("test.pem", pGet);
            AsymmetricCipherKeyPair pair;

            object o;

            while ((o = pemRd.ReadObject()) != null)
            {
//				if (o is AsymmetricCipherKeyPair)
//				{
//					ackp = (AsymmetricCipherKeyPair)o;
//
//					Console.WriteLine(ackp.Public);
//					Console.WriteLine(ackp.Private);
//				}
//				else
//				{
//					Console.WriteLine(o.ToString());
//				}
            }

            //
            // pkcs 7 data
            //
            pemRd = OpenPemResource("pkcs7.pem", null);

            ContentInfo d = (ContentInfo)pemRd.ReadObject();

            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
            {
                Fail("failed envelopedData check");
            }

            /*
             * {
             *  //
             *  // ECKey
             *  //
             *  pemRd = OpenPemResource("eckey.pem", null);
             *
             *  // TODO Resolve return type issue with EC keys and fix PemReader to return parameters
             * //				ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec)pemRd.ReadObject();
             *
             *  pair = (AsymmetricCipherKeyPair)pemRd.ReadObject();
             *  ISigner sgr = SignerUtilities.GetSigner("ECDSA");
             *
             *  sgr.Init(true, pair.Private);
             *
             *  byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };
             *
             *  sgr.BlockUpdate(message, 0, message.Length);
             *
             *  byte[] sigBytes = sgr.GenerateSignature();
             *
             *  sgr.Init(false, pair.Public);
             *
             *  sgr.BlockUpdate(message, 0, message.Length);
             *
             *  if (!sgr.VerifySignature(sigBytes))
             *  {
             *      Fail("EC verification failed");
             *  }
             *
             *  // TODO Resolve this issue with the algorithm name, study Java version
             * //				if (!((ECPublicKeyParameters) pair.Public).AlgorithmName.Equals("ECDSA"))
             * //				{
             * //					Fail("wrong algorithm name on public got: " + ((ECPublicKeyParameters) pair.Public).AlgorithmName);
             * //				}
             * //
             * //				if (!((ECPrivateKeyParameters) pair.Private).AlgorithmName.Equals("ECDSA"))
             * //				{
             * //					Fail("wrong algorithm name on private got: " + ((ECPrivateKeyParameters) pair.Private).AlgorithmName);
             * //				}
             * }
             */

            //
            // writer/parser test
            //
            IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");

            kpGen.Init(
                new RsaKeyGenerationParameters(
                    BigInteger.ValueOf(0x10001),
                    new SecureRandom(),
                    768,
                    25));

            pair = kpGen.GenerateKeyPair();

            keyPairTest("RSA", pair);

//			kpGen = KeyPairGenerator.getInstance("DSA");
//			kpGen.initialize(512, new SecureRandom());
            DsaParametersGenerator pGen = new DsaParametersGenerator();

            pGen.Init(512, 80, new SecureRandom());

            kpGen = GeneratorUtilities.GetKeyPairGenerator("DSA");
            kpGen.Init(
                new DsaKeyGenerationParameters(
                    new SecureRandom(),
                    pGen.GenerateParameters()));

            pair = kpGen.GenerateKeyPair();

            keyPairTest("DSA", pair);

            //
            // PKCS7
            //
            MemoryStream bOut = new MemoryStream();
            PemWriter    pWrt = new PemWriter(new StreamWriter(bOut));

            pWrt.WriteObject(d);
            pWrt.Writer.Close();

            pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
            d     = (ContentInfo)pemRd.ReadObject();

            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
            {
                Fail("failed envelopedData recode check");
            }


            // OpenSSL test cases (as embedded resources)
            doOpenSslDsaTest("unencrypted");
            doOpenSslRsaTest("unencrypted");

            doOpenSslTests("aes128");
            doOpenSslTests("aes192");
            doOpenSslTests("aes256");
            doOpenSslTests("blowfish");
            doOpenSslTests("des1");
            doOpenSslTests("des2");
            doOpenSslTests("des3");
            doOpenSslTests("rc2_128");

            doOpenSslDsaTest("rc2_40_cbc");
            doOpenSslRsaTest("rc2_40_cbc");
            doOpenSslDsaTest("rc2_64_cbc");
            doOpenSslRsaTest("rc2_64_cbc");

            doDudPasswordTest("7fd98", 0, "Corrupted stream - out of bounds length found");
            doDudPasswordTest("ef677", 1, "Corrupted stream - out of bounds length found");
            doDudPasswordTest("800ce", 2, "unknown tag 26 encountered");
            doDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56");
            doDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28");
            doDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11");
            doDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35");
            doDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9");
            doDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14");
            doDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65");
            doDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57");
            doDudPasswordTest("41af75", 11, "unknown tag 16 encountered");
            doDudPasswordTest("1704a5", 12, "corrupted stream detected");
            doDudPasswordTest("1c5822", 13, "extra data found after object");
            doDudPasswordTest("5a3d16", 14, "corrupted stream detected");
            doDudPasswordTest("8d0c97", 15, "corrupted stream detected");
            doDudPasswordTest("bc0daf", 16, "corrupted stream detected");
            doDudPasswordTest("aaf9c4d", 17, "Corrupted stream - out of bounds length found");

            // encrypted private key test
            pGet  = new Password("password".ToCharArray());
            pemRd = OpenPemResource("enckey.pem", pGet);

            RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject();

            if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
            {
                Fail("decryption of private key data check failed");
            }

            // general PKCS8 test
            pGet  = new Password("password".ToCharArray());
            pemRd = OpenPemResource("pkcs8test.pem", pGet);

            while ((privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject()) != null)
            {
                if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
                {
                    Fail("decryption of private key data check failed");
                }
            }
        }
コード例 #29
0
        public override void PerformTest()
        {
            IPasswordFinder pGet = new Password("secret".ToCharArray());
            PemReader pemRd = OpenPemResource("test.pem", pGet);
            IAsymmetricCipherKeyPair pair;

            object o;
            while ((o = pemRd.ReadObject()) != null)
            {
            //				if (o is AsymmetricCipherKeyPair)
            //				{
            //					ackp = (AsymmetricCipherKeyPair)o;
            //
            //					Console.WriteLine(ackp.Public);
            //					Console.WriteLine(ackp.Private);
            //				}
            //				else
            //				{
            //					Console.WriteLine(o.ToString());
            //				}
            }

            //
            // pkcs 7 data
            //
            pemRd = OpenPemResource("pkcs7.pem", null);

            ContentInfo d = (ContentInfo)pemRd.ReadObject();

            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
            {
                Fail("failed envelopedData check");
            }

            /*
            {
                //
                // ECKey
                //
                pemRd = OpenPemResource("eckey.pem", null);

                // TODO Resolve return type issue with EC keys and fix PemReader to return parameters
            //				ECNamedCurveParameterSpec spec = (ECNamedCurveParameterSpec)pemRd.ReadObject();

                pair = (AsymmetricCipherKeyPair)pemRd.ReadObject();
                ISigner sgr = SignerUtilities.GetSigner("ECDSA");

                sgr.Init(true, pair.Private);

                byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' };

                sgr.BlockUpdate(message, 0, message.Length);

                byte[] sigBytes = sgr.GenerateSignature();

                sgr.Init(false, pair.Public);

                sgr.BlockUpdate(message, 0, message.Length);

                if (!sgr.VerifySignature(sigBytes))
                {
                    Fail("EC verification failed");
                }

                // TODO Resolve this issue with the algorithm name, study Java version
            //				if (!((ECPublicKeyParameters) pair.Public).AlgorithmName.Equals("ECDSA"))
            //				{
            //					Fail("wrong algorithm name on public got: " + ((ECPublicKeyParameters) pair.Public).AlgorithmName);
            //				}
            //
            //				if (!((ECPrivateKeyParameters) pair.Private).AlgorithmName.Equals("ECDSA"))
            //				{
            //					Fail("wrong algorithm name on private got: " + ((ECPrivateKeyParameters) pair.Private).AlgorithmName);
            //				}
            }
            */

            //
            // writer/parser test
            //
            IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpGen.Init(
                new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x10001),
                new SecureRandom(),
                768,
                25));

            pair = kpGen.GenerateKeyPair();

            keyPairTest("RSA", pair);

            //			kpGen = KeyPairGenerator.getInstance("DSA");
            //			kpGen.initialize(512, new SecureRandom());
            DsaParametersGenerator pGen = new DsaParametersGenerator();
            pGen.Init(512, 80, new SecureRandom());

            kpGen = GeneratorUtilities.GetKeyPairGenerator("DSA");
            kpGen.Init(
                new DsaKeyGenerationParameters(
                    new SecureRandom(),
                    pGen.GenerateParameters()));

            pair = kpGen.GenerateKeyPair();

            keyPairTest("DSA", pair);

            //
            // PKCS7
            //
            MemoryStream bOut = new MemoryStream();
            PemWriter pWrt = new PemWriter(new StreamWriter(bOut));

            pWrt.WriteObject(d);
            pWrt.Writer.Close();

            pemRd = new PemReader(new StreamReader(new MemoryStream(bOut.ToArray(), false)));
            d = (ContentInfo)pemRd.ReadObject();

            if (!d.ContentType.Equals(CmsObjectIdentifiers.EnvelopedData))
            {
                Fail("failed envelopedData recode check");
            }

            // OpenSSL test cases (as embedded resources)
            doOpenSslDsaTest("unencrypted");
            doOpenSslRsaTest("unencrypted");

            doOpenSslTests("aes128");
            doOpenSslTests("aes192");
            doOpenSslTests("aes256");
            doOpenSslTests("blowfish");
            doOpenSslTests("des1");
            doOpenSslTests("des2");
            doOpenSslTests("des3");
            doOpenSslTests("rc2_128");

            doOpenSslDsaTest("rc2_40_cbc");
            doOpenSslRsaTest("rc2_40_cbc");
            doOpenSslDsaTest("rc2_64_cbc");
            doOpenSslRsaTest("rc2_64_cbc");

            // TODO Figure out why exceptions differ for commented out cases
            doDudPasswordTest("7fd98", 0, "Corrupted stream - out of bounds length found");
            doDudPasswordTest("ef677", 1, "Corrupted stream - out of bounds length found");
            //			doDudPasswordTest("800ce", 2, "cannot recognise object in stream");
            doDudPasswordTest("b6cd8", 3, "DEF length 81 object truncated by 56");
            doDudPasswordTest("28ce09", 4, "DEF length 110 object truncated by 28");
            doDudPasswordTest("2ac3b9", 5, "DER length more than 4 bytes: 11");
            doDudPasswordTest("2cba96", 6, "DEF length 100 object truncated by 35");
            doDudPasswordTest("2e3354", 7, "DEF length 42 object truncated by 9");
            doDudPasswordTest("2f4142", 8, "DER length more than 4 bytes: 14");
            doDudPasswordTest("2fe9bb", 9, "DER length more than 4 bytes: 65");
            doDudPasswordTest("3ee7a8", 10, "DER length more than 4 bytes: 57");
            doDudPasswordTest("41af75", 11, "malformed sequence in DSA private key");
            doDudPasswordTest("1704a5", 12, "corrupted stream detected");
            //			doDudPasswordTest("1c5822", 13, "corrupted stream detected");
            //			doDudPasswordTest("5a3d16", 14, "corrupted stream detected");
            doDudPasswordTest("8d0c97", 15, "corrupted stream detected");
            doDudPasswordTest("bc0daf", 16, "corrupted stream detected");
            doDudPasswordTest("aaf9c4d",17, "Corrupted stream - out of bounds length found");

            // encrypted private key test
            pGet = new Password("password".ToCharArray());
            pemRd = OpenPemResource("enckey.pem", pGet);

            RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject();

            if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
            {
                Fail("decryption of private key data check failed");
            }

            // general PKCS8 test
            pGet = new Password("password".ToCharArray());
            pemRd = OpenPemResource("pkcs8test.pem", pGet);

            while ((privKey = (RsaPrivateCrtKeyParameters)pemRd.ReadObject()) != null)
            {
                if (!privKey.PublicExponent.Equals(new BigInteger("10001", 16)))
                {
                    Fail("decryption of private key data check failed");
                }
            }
        }
コード例 #30
0
        public PkiCertificateSigningRequest(PkiEncodingFormat format, byte[] encoded,
                                            PkiHashAlgorithm hashAlgorithm)
        {
            Pkcs10CertificationRequest pkcs10;

            switch (format)
            {
            case PkiEncodingFormat.Pem:
                var encodedString = Encoding.UTF8.GetString(encoded);
                using (var sr = new StringReader(encodedString))
                {
                    var pemReader = new PemReader(sr);
                    pkcs10 = pemReader.ReadObject() as Pkcs10CertificationRequest;
                    if (pkcs10 == null)
                    {
                        throw new Exception("invalid PEM object is not PKCS#10 archive");
                    }
                }
                break;

            case PkiEncodingFormat.Der:
                pkcs10 = new Pkcs10CertificationRequest(encoded);
                break;

            default:
                throw new NotSupportedException();
            }

            var info            = pkcs10.GetCertificationRequestInfo();
            var nativePublicKey = pkcs10.GetPublicKey();
            var rsaKey          = nativePublicKey as RsaKeyParameters;
            var ecdsaKey        = nativePublicKey as ECPublicKeyParameters;

            if (rsaKey != null)
            {
                PublicKey = new PkiKey(nativePublicKey, PkiAsymmetricAlgorithm.Rsa);
            }
            else if (ecdsaKey != null)
            {
                PublicKey = new PkiKey(nativePublicKey, PkiAsymmetricAlgorithm.Ecdsa);
            }
            else
            {
                throw new NotSupportedException("unsupported asymmetric algorithm key");
            }
            SubjectName   = info.Subject.ToString();
            HashAlgorithm = hashAlgorithm;


            // // // Based on:
            // // //    http://forum.rebex.net/4284/pkcs10-certificate-request-example-provided-castle-working

            // // var extGen = new X509ExtensionsGenerator();
            // // foreach (var ext in CertificateExtensions)
            // // {
            // //     extGen.AddExtension(ext.Identifier, ext.IsCritical, ext.Value);
            // // }
            // // var attr = new AttributeX509(PkcsObjectIdentifiers.Pkcs9AtExtensionRequest,
            // //         new DerSet(extGen.Generate()));


            // Based on:
            //    http://unitstep.net/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/
            //    https://stackoverflow.com/q/24448909/5428506
            foreach (var attr in info.Attributes.ToArray())
            {
                if (attr is DerSequence derSeq && derSeq.Count == 2)
                {
                    var attrX509 = AttributeX509.GetInstance(attr);
                    if (object.Equals(attrX509.AttrType, PkcsObjectIdentifiers.Pkcs9AtExtensionRequest))
                    {
                        // The `Extension Request` attribute is present.
                        // The X509Extensions are contained as a value of the ASN.1 Set.
                        // Assume that it is the first value of the set.
                        if (attrX509.AttrValues.Count >= 1)
                        {
                            var csrExts = X509Extensions.GetInstance(attrX509.AttrValues[0]);
                            foreach (var extOid in csrExts.GetExtensionOids())
                            {
                                if (object.Equals(extOid, X509Extensions.SubjectAlternativeName))
                                {
                                    var ext    = csrExts.GetExtension(extOid);
                                    var extVal = ext.Value;
                                    var der    = extVal.GetDerEncoded();
                                    // The ext value, which is an ASN.1 Octet String, **MIGHT** be tagged with
                                    // a leading indicator that it's an Octet String and its length, so we want
                                    // to remove it if that's the case to extract the GeneralNames collection
                                    if (der.Length > 2 && der[0] == 4 && der[1] == der.Length - 2)
                                    {
                                        der = der.Skip(2).ToArray();
                                    }
                                    var asn1obj = Asn1Object.FromByteArray(der);
                                    var gnames  = GeneralNames.GetInstance(asn1obj);
                                    CertificateExtensions.Add(new PkiCertificateExtension
                                    {
                                        Identifier = extOid,
                                        IsCritical = ext.IsCritical,
                                        Value      = gnames,
                                    });
                                }
                            }

                            // No need to search any more.
                            break;
                        }
                    }
                }
            }
        }
コード例 #31
0
ファイル: CertUtils.cs プロジェクト: Wema/csharp
        /// <summary>
        /// Generates pfx from client configuration
        /// </summary>
        /// <param name="config">Kubernetes Client Configuration</param>
        /// <returns>Generated Pfx Path</returns>
        public static X509Certificate2 GeneratePfx(KubernetesClientConfiguration config)
        {
            byte[] keyData  = null;
            byte[] certData = null;

            if (!string.IsNullOrWhiteSpace(config.ClientCertificateKeyData))
            {
                keyData = Convert.FromBase64String(config.ClientCertificateKeyData);
            }
            if (!string.IsNullOrWhiteSpace(config.ClientKeyFilePath))
            {
                keyData = File.ReadAllBytes(config.ClientKeyFilePath);
            }

            if (keyData == null)
            {
                throw new KubeConfigException("keyData is empty");
            }

            if (!string.IsNullOrWhiteSpace(config.ClientCertificateData))
            {
                certData = Convert.FromBase64String(config.ClientCertificateData);
            }
            if (!string.IsNullOrWhiteSpace(config.ClientCertificateFilePath))
            {
                certData = File.ReadAllBytes(config.ClientCertificateFilePath);
            }

            if (certData == null)
            {
                throw new KubeConfigException("certData is empty");
            }

            var cert = new X509CertificateParser().ReadCertificate(new MemoryStream(certData));

            object obj;

            using (var reader = new StreamReader(new MemoryStream(keyData)))
            {
                obj = new PemReader(reader).ReadObject();
                var key = obj as AsymmetricCipherKeyPair;
                if (key != null)
                {
                    var cipherKey = key;
                    obj = cipherKey.Private;
                }
            }

            var rsaKeyParams = (RsaPrivateCrtKeyParameters)obj;

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

            store.SetKeyEntry("K8SKEY", new AsymmetricKeyEntry(rsaKeyParams), new[] { new X509CertificateEntry(cert) });

            using (var pkcs = new MemoryStream())
            {
                store.Save(pkcs, new char[0], new SecureRandom());

                if (config.ClientCertificateKeyStoreFlags.HasValue)
                {
                    return(new X509Certificate2(pkcs.ToArray(), "", config.ClientCertificateKeyStoreFlags.Value));
                }
                else
                {
                    return(new X509Certificate2(pkcs.ToArray()));
                }
            }
        }
コード例 #32
0
        public async Task <int> Run(VerifyOptions options, string httpMessage)
        {
            ISignatureAlgorithm signatureAlgorithmForVerification;

            if (string.IsNullOrEmpty(options.KeyType) || options.KeyType.Equals("RSA", StringComparison.OrdinalIgnoreCase))
            {
                RSAParameters rsaPublicKey;
                using (var stream = File.OpenRead(options.PublicKey)) {
                    using (var reader = new PemReader(stream)) {
                        rsaPublicKey = reader.ReadRsaKey();
                    }
                }
                signatureAlgorithmForVerification = RSASignatureAlgorithm.CreateForVerification(HashAlgorithmName.SHA512, rsaPublicKey);
            }
            else if (options.KeyType.Equals("P256", StringComparison.OrdinalIgnoreCase) || options.KeyType.Equals("ECDSA", StringComparison.OrdinalIgnoreCase))
            {
                ECParameters ecPublicKey;
                using (var stream = File.OpenRead(options.PublicKey)) {
                    using (var reader = new StreamReader(stream)) {
                        var fileContents = reader.ReadToEnd();
                        var lines        = fileContents.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                        lines = lines.Skip(1).Take(lines.Length - 2).ToArray();
                        var pem      = string.Join("", lines);
                        var ecdsa    = ECDsa.Create();
                        var derArray = Convert.FromBase64String(pem);
                        ecdsa.ImportSubjectPublicKeyInfo(derArray, out _);
                        ecPublicKey = ecdsa.ExportParameters(false);
                    }
                }
                signatureAlgorithmForVerification = ECDsaSignatureAlgorithm.CreateForVerification(HashAlgorithmName.SHA512, ecPublicKey);
            }
            else if (options.KeyType.Equals("HMAC", StringComparison.OrdinalIgnoreCase))
            {
                signatureAlgorithmForVerification = SignatureAlgorithm.CreateForVerification(options.PublicKey, HashAlgorithmName.SHA512);
            }
            else
            {
                throw new NotSupportedException("The specified key type is not supported.");
            }

            var serviceProvider = new ServiceCollection()
                                  .AddHttpMessageSignatureVerification(provider => {
                var clientStore = new InMemoryClientStore();
                clientStore.Register(new Client(
                                         new KeyId("test"),
                                         "ConformanceClient",
                                         signatureAlgorithmForVerification,
                                         TimeSpan.FromSeconds(30),
                                         TimeSpan.FromMinutes(1)));
                return(clientStore);
            })
                                  .BuildServiceProvider();

            var verifier = serviceProvider.GetRequiredService <IRequestSignatureVerifier>();

            var clientRequest   = HttpRequestMessageParser.Parse(httpMessage);
            var requestToVerify = await clientRequest.ToServerSideHttpRequest();

            var verificationResult = await verifier.VerifySignature(requestToVerify, new SignedRequestAuthenticationOptions {
                OnSignatureParsed = (request, signature) => {
                    if (!string.IsNullOrEmpty(options.Algorithm))
                    {
                        signature.Algorithm = options.Algorithm;
                    }

                    return(Task.CompletedTask);
                }
            });

            return(verificationResult is RequestSignatureVerificationResultSuccess
                ? 0
                : 1);
        }
コード例 #33
0
 public void LoadCertificateWithOnlyPublicKeyAllowed()
 {
     using X509Certificate2 certificate = PemReader.LoadCertificate(ECDsaCertificate.AsSpan(), allowCertificateOnly: true, keyType: PemReader.KeyType.ECDsa);
     Assert.AreEqual("CN=Azure SDK", certificate.Subject);
     Assert.IsFalse(certificate.HasPrivateKey);
 }
コード例 #34
0
        private void EncryptedTest(IAsymmetricKeyParameter privKey, string algorithm)
        {
            StringWriter sw = new StringWriter();
            PemWriter pWrt = new PemWriter(sw);
            Pkcs8Generator pkcs8 = new Pkcs8Generator(privKey, algorithm);
            pkcs8.Password = "******".ToCharArray();

            pWrt.WriteObject(pkcs8);
            pWrt.Writer.Close();

            String result = sw.ToString();

            PemReader pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray()));

            IAsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject();
            pRd.Reader.Close();

            Assert.AreEqual(privKey, rdKey);
        }
コード例 #35
0
        /// <inheritdoc/>
        public async Task <(X509Certificate Certificate, RsaKeyParameters Key)> GetLocalCertificateAsync(ApplicationDescription applicationDescription, ILogger logger = null)
        {
            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(this.pkiPath, "own", "certs"));

            if (ownCertsInfo.Exists)
            {
                foreach (var info in ownCertsInfo.EnumerateFiles())
                {
                    using (var crtStream = info.OpenRead())
                    {
                        var c = this.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(this.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 (!this.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(this.rng, 2048));
                return(kg.GenerateKeyPair());
            });

            key = kp.Private as RsaPrivateCrtKeyParameters;

            // Create a certificate.
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
            var subjectSN = BigInteger.ProbablePrime(120, this.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, this.rng));

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

            var keyInfo = new FileInfo(Path.Combine(this.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(this.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);
        }
コード例 #36
0
        public void TestPkcs8Plain()
        {
            IAsymmetricCipherKeyPairGenerator kpGen = GeneratorUtilities.GetKeyPairGenerator("RSA");
            kpGen.Init(new KeyGenerationParameters(new SecureRandom(), 1024));

            IAsymmetricKeyParameter privKey = kpGen.GenerateKeyPair().Private;

            StringWriter sw = new StringWriter();
            PemWriter pWrt = new PemWriter(sw);

            Pkcs8Generator pkcs8 = new Pkcs8Generator(privKey);
            pWrt.WriteObject(pkcs8);
            pWrt.Writer.Close();

            string result = sw.ToString();

            PemReader pRd = new PemReader(new StringReader(result), new Password("hello".ToCharArray()));

            IAsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject();
            pRd.Reader.Close();

            Assert.AreEqual(privKey, rdKey);
        }