Ejemplo n.º 1
2
        private static RsaKeyPair GetRsaKeyPair(RSA rsa, string comment)
        {
            const string sshrsa = "ssh-rsa";

            // Use Bouncy castle's pem reader to get the modulus and exponent as a byte array
            PemReader reader = new PemReader(new StringReader(rsa.PublicKeyAsPEM));
            RsaKeyParameters r = (RsaKeyParameters)reader.ReadObject();

            byte[] sshrsa_bytes = Encoding.Default.GetBytes(sshrsa);
            byte[] n = r.Modulus.ToByteArray();
            byte[] e = r.Exponent.ToByteArray();

            Buffer buf = new Buffer(sshrsa_bytes.Length + 4 + e.Length + 4 + n.Length + 4);

            // Add the bytes
            buf.add(sshrsa_bytes, e, n);

            // Encode in Base64
            string buffer64 = buf.AsBase64String();

            // Set the base DTO
            RsaKeyPair pair = new RsaKeyPair()
            {
                PublicSSHKey = string.Format("ssh-rsa {0} {1}", buffer64, comment),
                PublicKeyAsPEM = rsa.PublicKeyAsPEM,
                PrivateKeyAsPEM = rsa.PrivateKeyAsPEM,
                // Later add parameters if required.
            };

            return pair;
        }
Ejemplo n.º 2
0
        private static AsymmetricKeyParameter getAsymmetricKeyParameter(String publicKeyPem)
        {
            TextReader reader    = new StringReader(publicKeyPem);
            var        pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);

            return(pemReader.ReadObject() as AsymmetricKeyParameter);
        }
        /// <summary>
        /// verify data signature with public key
        /// </summary>
        /// <param name="macdata">source data</param>
        /// <param name="mac">signature string</param>
        /// <param name="pkInfo">public key</param>
        /// <returns>verify result</returns>
        public static bool VerifyData(string macdata, string mac, string pkInfo)
        {
            byte[] data      = Encoding.UTF8.GetBytes(macdata);
            byte[] signature = Convert.FromBase64String(mac);
            string pub;

            if (!pkInfo.Contains("CERTIFICATE") && !pkInfo.Contains("PUBLIC KEY"))
            {
                pub = ReadPK(pkInfo);
            }
            else
            {
                pub = pkInfo;
            }

            Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters ecdsaPublicKey = null;
            if (pub.Contains("CERTIFICATE"))
            {
                Org.BouncyCastle.X509.X509Certificate cert = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(Encoding.UTF8.GetBytes(pub));

                ecdsaPublicKey = (Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters)cert.GetPublicKey();
            }
            else if (pub.Contains("PUBLIC KEY"))
            {
                TextReader ptr = new StringReader(pub);
                Org.BouncyCastle.OpenSsl.PemReader pem = new Org.BouncyCastle.OpenSsl.PemReader(ptr);
                ecdsaPublicKey = (Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters)pem.ReadObject();
            }

            string curveName = "P-256";
            var    nistCurve = Org.BouncyCastle.Asn1.Nist.NistNamedCurves.GetByName(curveName);

            return(nistCurve.Verify(ecdsaPublicKey, data, signature));
        }
Ejemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        public static X509Certificate RetrieveAndVerifyCertificate(string certChainUrl)
        {
            // making requests to externally-supplied URLs is an open invitation to DoS
            // so restrict host to an Alexa controlled subdomain/path
            if (!VerifyCertificateUrl(certChainUrl))
            {
                return(null);
            }

            var httpClient = new HttpClient();
            var content    = httpClient.GetStringAsync(certChainUrl).Result;

            var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(content));
            var cert      = (X509Certificate)pemReader.ReadObject();

            try {
                cert.CheckValidity();
                if (!CheckCertSubjectNames(cert))
                {
                    return(null);
                }
            }
            catch (CertificateExpiredException) {
                return(null);
            }
            catch (CertificateNotYetValidException) {
                return(null);
            }

            return(cert);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Windows TLS needs the Alias public + private key in a PFX file
        /// </summary>
        /// <param name="certFile"></param>
        /// <param name="keyFile"></param>
        internal static void MakePFXFile(string certFile, string keyFile, string outputPfxFile, string password)
        {
            CryptoApiRandomGenerator rg = new CryptoApiRandomGenerator();
            var rng = new SecureRandom(rg);
            // get the cert
            var parser = new X509CertificateParser();
            var cert   = parser.ReadCertificate(File.ReadAllBytes(certFile));

            // get the key
            Org.BouncyCastle.OpenSsl.PemReader pemReader =
                new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(File.ReadAllText(keyFile)));
            AsymmetricCipherKeyPair kp = pemReader.ReadObject() as AsymmetricCipherKeyPair;


            // Put the key and cert in an PKCS12 store so that the WIndows TLS stack can use it
            var    store            = new Pkcs12Store();
            string friendlyName     = cert.SubjectDN.ToString();
            var    certificateEntry = new X509CertificateEntry(cert);

            store.SetCertificateEntry(friendlyName, certificateEntry);
            store.SetKeyEntry(friendlyName, new AsymmetricKeyEntry(kp.Private), new[] { certificateEntry });

            var stream = new MemoryStream();
            var pwd    = password == null ? null : password.ToCharArray();

            store.Save(stream, pwd, rng);
            File.WriteAllBytes(outputPfxFile, stream.ToArray());
            return;
        }
        /// <summary>
        ///
        /// </summary>
        public static X509Certificate RetrieveAndVerifyCertificate(string certChainUrl)
        {
            // making requests to externally-supplied URLs is an open invitation to DoS
            // so restrict host to an Alexa controlled subdomain/path
            if (!Regex.IsMatch(certChainUrl, Sdk.SIGNATURE_CERT_URL_MASK_REGEX))
            {
                return(null);
            }

            var webClient = new WebClient();
            var content   = webClient.DownloadString(certChainUrl);

            var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(content));
            var cert      = (X509Certificate)pemReader.ReadObject();

            try {
                cert.CheckValidity();
                if (!CheckCertSubjectNames(cert))
                {
                    return(null);
                }
            }
            catch (CertificateExpiredException) {
                return(null);
            }
            catch (CertificateNotYetValidException) {
                return(null);
            }

            return(cert);
        }
Ejemplo n.º 7
0
        internal static RsaKeyParameters ReadRsaKeyPair(string pemFileName)
        {
            var fileStream = System.IO.File.OpenText(pemFileName);
            var pemReader  = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);

            return((RsaKeyParameters)pemReader.ReadObject());
        }
        } // End Function ReadPublicKey

        public static Org.BouncyCastle.Crypto.AsymmetricKeyParameter ReadPrivateKey(string privateKey)
        {
            Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair keyPair = null;

            using (System.IO.TextReader reader = new System.IO.StringReader(privateKey))
            {
                Org.BouncyCastle.OpenSsl.PemReader pemReader =
                    new Org.BouncyCastle.OpenSsl.PemReader(reader);

                object obj = pemReader.ReadObject();

                if (obj is Org.BouncyCastle.Crypto.AsymmetricKeyParameter)
                {
                    throw new System.ArgumentException("The given privateKey is a public key, not a privateKey...", "privateKey");
                }

                if (!(obj is Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair))
                {
                    throw new System.ArgumentException("The given privateKey is not a valid assymetric key.", "privateKey");
                }

                keyPair = (Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair)obj;
            } // End using reader

            // Org.BouncyCastle.Crypto.AsymmetricKeyParameter priv = keyPair.Private;
            // Org.BouncyCastle.Crypto.AsymmetricKeyParameter pub = keyPair.Public;

            // Note:
            // cipher.Init(false, key);
            // !!!

            return(keyPair.Private);
        } // End Function ReadPrivateKey
Ejemplo n.º 9
0
        /// <summary>
        /// PEM 私钥转换为XML
        /// </summary>
        public static string PEMPrivatekeyToXML(string privateKey)
        {
            AsymmetricCipherKeyPair keyPair;
            var buffer = System.Text.Encoding.UTF8.GetBytes(privateKey);

            using (var stream = new MemoryStream(buffer))
            {
                using (var sr = new StreamReader(stream))
                {
                    var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                    keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
                }
            }
            var key = (RsaPrivateCrtKeyParameters)keyPair.Private;
            var p   = new RSAParameters
            {
                Modulus  = key.Modulus.ToByteArrayUnsigned(),
                Exponent = key.PublicExponent.ToByteArrayUnsigned(),
                D        = key.Exponent.ToByteArrayUnsigned(),
                P        = key.P.ToByteArrayUnsigned(),
                Q        = key.Q.ToByteArrayUnsigned(),
                DP       = key.DP.ToByteArrayUnsigned(),
                DQ       = key.DQ.ToByteArrayUnsigned(),
                InverseQ = key.QInv.ToByteArrayUnsigned(),
            };
            var rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(p);
            return(rsa.ToXmlString(true));
        }
Ejemplo n.º 10
0
Archivo: SHA1.cs Proyecto: sachem1/IDDD
        public static string PemPrivateKeyToXml(string privateKey)
        {
            AsymmetricCipherKeyPair keyPair;

            using (var sr = new StringReader(privateKey))
            {
                var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
            }
            var key = (RsaPrivateCrtKeyParameters)keyPair.Private;
            var p   = new RSAParameters
            {
                Modulus  = key.Modulus.ToByteArrayUnsigned(),
                Exponent = key.PublicExponent.ToByteArrayUnsigned(),
                D        = key.Exponent.ToByteArrayUnsigned(),
                P        = key.P.ToByteArrayUnsigned(),
                Q        = key.Q.ToByteArrayUnsigned(),
                DP       = key.DP.ToByteArrayUnsigned(),
                DQ       = key.DQ.ToByteArrayUnsigned(),
                InverseQ = key.QInv.ToByteArrayUnsigned(),
            };
            var rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(p);
            return(rsa.ToXmlString(true));
        }
Ejemplo n.º 11
0
        } // End Sub WritePrivatePublic

        public static Org.BouncyCastle.Crypto.AsymmetricKeyParameter ReadPublicKey(string publicKey)
        {
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter keyParameter = null;

            using (System.IO.TextReader reader = new System.IO.StringReader(publicKey))
            {
                Org.BouncyCastle.OpenSsl.PemReader pemReader =
                    new Org.BouncyCastle.OpenSsl.PemReader(reader);

                object obj = pemReader.ReadObject();

                if ((obj is Org.BouncyCastle.Crypto.AsymmetricCipherKeyPair))
                {
                    throw new System.ArgumentException("The given publicKey is actually a private key.", "publicKey");
                }

                if (!(obj is Org.BouncyCastle.Crypto.AsymmetricKeyParameter))
                {
                    throw new System.ArgumentException("The given publicKey is not a valid assymetric key.", "publicKey");
                }

                keyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)obj;
                if (keyParameter.IsPrivate)
                {
                    throw new System.ArgumentException("The given publicKey is actually a private key.", "publicKey");
                }
            } // End Using reader

            if (!(keyParameter is Org.BouncyCastle.Crypto.Parameters.ECPublicKeyParameters))
            {
                throw new System.ArgumentException("The given privateKey is an asymmetric publicKey, but not an ECDSA public key.", "publicKey");
            }

            return(keyParameter);
        } // End Function ReadPublicKey
Ejemplo n.º 12
0
        public static string EncodeToken(string uid, Dictionary <string, object> claims)
        {
            // Get the RsaPrivateCrtKeyParameters if we haven't already determined them
            if (_rsaParams == null)
            {
                lock (_rsaParamsLocker)
                {
                    if (_rsaParams == null)
                    {
                        StreamReader sr = new StreamReader(GenerateStreamFromString(firebasePrivateKey.Replace(@"\n", "\n")));
                        var          pr = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                        _rsaParams = (RsaPrivateCrtKeyParameters)pr.ReadObject();
                    }
                }
            }

            var payload = new Dictionary <string, object> {
                { "claims", claims }
                , { "uid", uid }
                , { "iat", SecondsSinceEpoch(DateTime.UtcNow) }
                , { "exp", SecondsSinceEpoch(DateTime.UtcNow.AddSeconds(firebaseTokenExpirySecs)) }
                , { "aud", firebasePayloadAUD }
                , { "iss", firebasePayloadISS }
                , { "sub", firebasePayloadSUB }
            };

            return(Jose.JWT.Encode(payload, Org.BouncyCastle.Security.DotNetUtilities.ToRSA(_rsaParams), JwsAlgorithm.RS256));
        }
Ejemplo n.º 13
0
 /***
  * Creates a TLSCertificateKeyPair out of the given {@link X509Certificate} and {@link KeyPair}
  * encoded in PEM and also in DER for the certificate
  * @param x509Cert the certificate to process
  * @param keyPair  the key pair to process
  * @return a TLSCertificateKeyPair
  * @throws IOException upon failure
  */
 public TLSCertificateKeyPair(Certificate x509Cert, KeyPair keyPair)
 {
     using (MemoryStream baos = new MemoryStream())
     {
         StreamWriter writer = new StreamWriter(baos);
         PemWriter    w      = new PemWriter(writer);
         w.WriteObject(x509Cert.X509Certificate);
         writer.Flush();
         writer.Close();
         CertPEMBytes = baos.ToArray();
     }
     using (MemoryStream isr = new MemoryStream(CertPEMBytes))
     {
         StreamReader reader = new StreamReader(isr);
         PemReader    pr     = new PemReader(reader);
         PemObject    po     = pr.ReadPemObject();
         CertDERBytes = po.Content;
     }
     using (MemoryStream baos = new MemoryStream())
     {
         StreamWriter writer = new StreamWriter(baos);
         PemWriter    w      = new PemWriter(writer);
         w.WriteObject(keyPair.PrivateKey);
         writer.Flush();
         writer.Close();
         KeyPEMBytes = baos.ToArray();
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Helper function for reading PEM encoding
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pem"></param>
        /// <returns></returns>
        public T?ParsePem <T>(string pem) where T : class
        {
            using var tr = new StringReader(pem);
            var pr = new bc.OpenSsl.PemReader(tr);

            return(pr.ReadObject() as T);
        }
Ejemplo n.º 15
0
            public static void PEMConvertToXML(string strpem, string strxml)//PEM格式密钥转XML
            {
                AsymmetricCipherKeyPair keyPair;

                using (var sr = new StreamReader(strpem))
                {
                    var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                    keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
                }
                var key = (RsaPrivateCrtKeyParameters)keyPair.Private;
                var p   = new RSAParameters
                {
                    Modulus  = key.Modulus.ToByteArrayUnsigned(),
                    Exponent = key.PublicExponent.ToByteArrayUnsigned(),
                    D        = key.Exponent.ToByteArrayUnsigned(),
                    P        = key.P.ToByteArrayUnsigned(),
                    Q        = key.Q.ToByteArrayUnsigned(),
                    DP       = key.DP.ToByteArrayUnsigned(),
                    DQ       = key.DQ.ToByteArrayUnsigned(),
                    InverseQ = key.QInv.ToByteArrayUnsigned(),
                };
                var rsa = new RSACryptoServiceProvider();

                rsa.ImportParameters(p);
                using (var sw = new StreamWriter(strxml))
                {
                    sw.Write(rsa.ToXmlString(true));
                }
            }
Ejemplo n.º 16
0
        public static AsymmetricCipherKeyPair GetPrivateKey(string privateKey)
        {
            StreamReader sr = null;

            try
            {
                sr = new StreamReader(privateKey);
                Org.BouncyCastle.OpenSsl.PemReader pr      = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                AsymmetricCipherKeyPair            keyPair = (AsymmetricCipherKeyPair)pr.ReadObject();

                return(keyPair);
            }
            catch
            {
                // ignored
            }
            finally
            {
                try
                {
                    sr.Close();
                }
                catch
                {
                    // ignored
                }
            }
            return(null);
        }
Ejemplo n.º 17
0
        public static AsymmetricKeyParameter GetPublicKey(string publicKey)
        {
            StreamReader sr = null;

            try
            {
                sr = new StreamReader(publicKey);
                Org.BouncyCastle.OpenSsl.PemReader pr      = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                AsymmetricKeyParameter             KeyPair = (AsymmetricKeyParameter)pr.ReadObject();
                return(KeyPair);
            }
            catch
            {
            }
            finally
            {
                try
                {
                    sr.Close();
                }
                catch
                {
                }
            }
            return(null);
        }
Ejemplo n.º 18
0
        //PEM 私鑰轉換為 XML 私鑰(應先載入私鑰,privateXmlKeyPath 如果为空则不保存文件,仅加载)
        public static void privateKeyPem2Xml2(string privatePemKeyPath = "PrivateKey.pem", string privateXmlKeyPath = "PrivateKey.xml")
        {
            AsymmetricCipherKeyPair keyPair;

            using (StreamReader sr = new StreamReader(privatePemKeyPath))
            {
                var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
            }
            RsaPrivateCrtKeyParameters key = (RsaPrivateCrtKeyParameters)keyPair.Private;
            RSAParameters p = new RSAParameters
            {
                Modulus  = key.Modulus.ToByteArrayUnsigned(),
                Exponent = key.PublicExponent.ToByteArrayUnsigned(),
                D        = key.Exponent.ToByteArrayUnsigned(),
                P        = key.P.ToByteArrayUnsigned(),
                Q        = key.Q.ToByteArrayUnsigned(),
                DP       = key.DP.ToByteArrayUnsigned(),
                DQ       = key.DQ.ToByteArrayUnsigned(),
                InverseQ = key.QInv.ToByteArrayUnsigned(),
            };
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            rsa.ImportParameters(p);
            string xmlString = rsa.ToXmlString(true);

            RSACSPrivate.FromXmlString(xmlString);
            if (privateXmlKeyPath.Length > 0)
            {
                using (StreamWriter sw = new StreamWriter(privateXmlKeyPath))
                {
                    sw.Write(xmlString);
                }
            }
        }
Ejemplo n.º 19
0
        private static AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
        {
            var fileStream   = System.IO.File.OpenText(pemFilename);
            var pemReader    = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
            var KeyParameter = (AsymmetricKeyParameter)pemReader.ReadObject();

            return(KeyParameter);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Helper function for reading PEM encoding
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="pem"></param>
 /// <returns></returns>
 private T ParsePem <T>(string pem)
 {
     using (var tr = new StringReader(pem))
     {
         var pr = new bc.OpenSsl.PemReader(tr);
         return((T)pr.ReadObject());
     }
 }
Ejemplo n.º 21
0
 static AsymmetricCipherKeyPair ReadPem(string pem)
 {
     using (TextReader reader = new StringReader(pem))
     {
         var obj = new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
         return(obj as AsymmetricCipherKeyPair);
     }
 }
Ejemplo n.º 22
0
 // https://stackoverflow.com/questions/11346200/reading-pem-rsa-public-key-only-using-bouncy-castle
 // Reads only public key
 public Org.BouncyCastle.Crypto.AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFilename)
 {
     using (System.IO.StreamReader fileStream = System.IO.File.OpenText(pemFilename))
     {
         Org.BouncyCastle.OpenSsl.PemReader             pemReader    = new Org.BouncyCastle.OpenSsl.PemReader(fileStream);
         Org.BouncyCastle.Crypto.AsymmetricKeyParameter KeyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
         return(KeyParameter);
     }
 }
 private X509Certificate TextToCert(string certText)
 {
     if (!string.IsNullOrWhiteSpace(certText))
     {
         var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(certText));
         return(pemReader.ReadObject() as Org.BouncyCastle.X509.X509Certificate);
     }
     return(null);
 }
Ejemplo n.º 24
0
        public static RSAParameters ToRSAParameters(this string privateKey)
        {
            var reader = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(privateKey));
            AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)reader.ReadObject();

            RSAParameters rsa = DotNetUtilities.ToRSAParameters((RsaPrivateCrtKeyParameters)KeyPair.Private);

            return(rsa);
        }
Ejemplo n.º 25
0
        public static AsymmetricKeyParameter GetPrivateKey()
        {
            // Erstatt sp_key i resource mappen med din egen sp_key.
            Stream     stream               = new MemoryStream(ForsendelseClientSample.Properties.Resources.sp_key);
            TextReader textReader           = new StreamReader(stream);
            PemReader  pemReader            = new PemReader(textReader);
            AsymmetricCipherKeyPair keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair;

            return(keyPair.Private);
        }
Ejemplo n.º 26
0
        public static string ConvertPrikToHexString(string privateKey)
        {
            TextReader ptr = new StringReader(privateKey);

            Org.BouncyCastle.OpenSsl.PemReader pem = new Org.BouncyCastle.OpenSsl.PemReader(ptr);
            Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters ecdsaPrivateKey = (Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters)pem.ReadObject();
            var Db = ByteArrayToHexString(ecdsaPrivateKey.D.ToByteArrayUnsigned());

            return(Db);
        }
Ejemplo n.º 27
0
        internal static Object ReadPemObject(string fileName)
        {
            var stream = new StreamReader(fileName);

            Org.BouncyCastle.OpenSsl.PemReader reader = new Org.BouncyCastle.OpenSsl.PemReader(stream);
            var o = reader.ReadObject();

            stream.Close();
            return(o);
        }
Ejemplo n.º 28
0
        public IActionResult SendKey(Guid id, [FromBody] PublicKeyModel publicKey)
        {
            TextReader textReader = new StringReader(publicKey.PublicKey);

            Org.BouncyCastle.OpenSsl.PemReader pemReader      = new Org.BouncyCastle.OpenSsl.PemReader(textReader);
            AsymmetricKeyParameter             publicKeyParam = (AsymmetricKeyParameter)pemReader.ReadObject();

            streamQueueManager.Streams[id.ToString()].PublicKey    = publicKeyParam;
            streamQueueManager.Streams[id.ToString()].StreamerName = publicKey.StreamerName;
            return(Ok());
        }
Ejemplo n.º 29
0
        private static bool KeyIsVulnerable(StringReader pem_stream)
        {
            var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(pem_stream);
            RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)pemReader.ReadObject();

            if (rsaKeyParameters == null)
            {
                throw new InvalidOperationException("Incorrect PEM data processed");
            }
            return(RocaCmTest.IsVulnerable(rsaKeyParameters));
        }
        /// <summary>
        /// Convert RSA pem files to <see cref="AsymmetricKeyParameter"/>
        /// </summary>
        /// <param name="pemFile">The content of the file. (NOT THE FILE NAME)</param>
        /// <returns>The key to use in bouncy castle</returns>
        public static AsymmetricKeyParameter ReadAsymmetricKeyParameter(string pemFile)
        {
            using (StringReader reader = new StringReader(pemFile))
            {
                Org.BouncyCastle.OpenSsl.PemReader pr =
                    new Org.BouncyCastle.OpenSsl.PemReader(reader);
                Org.BouncyCastle.Utilities.IO.Pem.PemObject po = pr.ReadPemObject();

                return(PublicKeyFactory.CreateKey(po.Content));
            }
        }
Ejemplo n.º 31
0
            /// <summary>
            /// base64密钥转xml密钥
            /// </summary>
            /// <param name="pemKey"></param>
            /// <param name="isPrivateKey"></param>
            /// <returns></returns>
            public static string ConvertPemToXmlKey(string pemKey, bool isPrivateKey)
            {
                if (string.IsNullOrEmpty(pemKey))
                {
                    return(null);
                }

                string        rsaKey    = string.Empty;
                object        pemObject = null;
                RSAParameters rsaPara   = new RSAParameters();

                using (StringReader sReader = new StringReader(pemKey))
                {
                    var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sReader);
                    pemObject = pemReader.ReadObject();
                }
                //RSA私钥
                if (isPrivateKey)
                {
                    //RsaPrivateCrtKeyParameters key = (RsaPrivateCrtKeyParameters)(((AsymmetricCipherKeyPair)pemObject).Private);
                    RsaPrivateCrtKeyParameters key = (RsaPrivateCrtKeyParameters)pemObject;
                    rsaPara = new RSAParameters
                    {
                        Modulus  = key.Modulus.ToByteArrayUnsigned(),
                        Exponent = key.PublicExponent.ToByteArrayUnsigned(),
                        D        = key.Exponent.ToByteArrayUnsigned(),
                        P        = key.P.ToByteArrayUnsigned(),
                        Q        = key.Q.ToByteArrayUnsigned(),
                        DP       = key.DP.ToByteArrayUnsigned(),
                        DQ       = key.DQ.ToByteArrayUnsigned(),
                        InverseQ = key.QInv.ToByteArrayUnsigned(),
                    };
                }
                //RSA公钥
                else
                {
                    RsaKeyParameters key = (RsaKeyParameters)pemObject;
                    rsaPara = new RSAParameters
                    {
                        Modulus  = key.Modulus.ToByteArrayUnsigned(),
                        Exponent = key.Exponent.ToByteArrayUnsigned(),
                    };
                }
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                rsa.ImportParameters(rsaPara);
                using (StringWriter sw = new StringWriter())
                {
                    sw.Write(rsa.ToXmlString(isPrivateKey ? true : false));
                    rsaKey = sw.ToString();
                }
                return(rsaKey);
            }
        /// <summary>
        /// Called by TLS server to create his ephemeral keys.
        /// TODO: get information about which ECC curve should be used
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        public override byte[] GetServerKeys(ProtocolVersion version, CertificatePrivateKey certPrivateKey)
        {
            var ms = new MemoryStream(certPrivateKey.KeyValue);
            var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StreamReader(ms));
            var keyParam = pemReader.ReadObject();
            var key = keyParam as AsymmetricCipherKeyPair;
            var pk = key.Public as ECPublicKeyParameters;
            var certCurve = pk.Q.Curve;

            string curveName = string.Empty;
            for (int i = 0; i < knownCurveNames.Length; i++)
            {
                var curveParams = SecNamedCurves.GetByName(knownCurveNames[i]);
                if (certCurve.GetHashCode() == curveParams.Curve.GetHashCode())
                {
                    curveName = knownCurveNames[i];
                    break;
                }
            }

            if (curveName == string.Empty)
            {
                throw new InvalidOperationException("Could not find EC curve for server private key");
            }

            this.logger?.Debug("Getting server keys for curve '{0}'.", curveName);
            this.GenerateKeys(curveName);

            byte[] pubKeyBytes = this.publicKey.Q.GetEncoded();
            byte[] serverKeyBytes = new byte[4 + pubKeyBytes.Length];
            serverKeyBytes[0] = 3;
            if (curveName.Contains("192"))
            {
                serverKeyBytes[2] = (byte) EccNamedCurve.Secp192R1; // 19: Should match curve type > secp192r1
            }
            else
            {
                serverKeyBytes[2] = (byte)EccNamedCurve.Secp256R1; // 23: Should match curve type > secp256r1    
                if (curveName.StartsWith("brainpool"))
                {
                    serverKeyBytes[2] = (byte) EccNamedCurve.BrainpoolP256R1;
                }
            }
            
            serverKeyBytes[3] = (byte)pubKeyBytes.Length;
            Buffer.BlockCopy(pubKeyBytes, 0, serverKeyBytes, 4, pubKeyBytes.Length);

            return serverKeyBytes;
        }
Ejemplo n.º 33
0
        private static RsaKeyParameters GetPublicKey()
        {
            System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
            RsaKeyParameters keyParams = null;

            using (System.IO.StreamReader strm = new System.IO.StreamReader(assembly.GetManifestResourceStream("Processors.Cryptography.DKIM.Resources.publickey.txt")))
            {
                Org.BouncyCastle.OpenSsl.PemReader pemRdr = new Org.BouncyCastle.OpenSsl.PemReader(strm);
                keyParams = (RsaKeyParameters)pemRdr.ReadObject();
            }

            return keyParams;
        }
        /// <summary>
        /// 
        /// </summary>
        public static X509Certificate RetrieveAndVerifyCertificate(string certChainUrl) {
            // making requests to externally-supplied URLs is an open invitation to DoS
            // so restrict host to an Alexa controlled subdomain/path
            if (!Regex.IsMatch(certChainUrl, Sdk.SIGNATURE_CERT_URL_MASK_REGEX)) return null;

            var webClient = new WebClient();
            var content = webClient.DownloadString(certChainUrl);

            var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(content));
            var cert = (X509Certificate)pemReader.ReadObject();
            try {
                cert.CheckValidity();
                if (!CheckCertSubjectNames(cert)) return null;
            }
            catch (CertificateExpiredException) {
                return null;
            }
            catch (CertificateNotYetValidException) {
                return null;
            }

            return cert;
        }
        /// <summary>
        /// 
        /// </summary>
        public async static Task<X509Certificate> RetrieveAndVerifyCertificateAsync(string certChainUrl) {
            // making requests to externally-supplied URLs is an open invitation to DoS
            // so restrict host to an Alexa controlled subdomain/path
            if (!Regex.IsMatch(certChainUrl, Sdk.SIGNATURE_CERT_URL_MASK_REGEX)) return null;

            var httpClient = new HttpClient();
            var httpResponse = await httpClient.GetAsync(certChainUrl);
            var content = await httpResponse.Content.ReadAsStringAsync();
            if (String.IsNullOrEmpty(content)) return null;

            var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(content));
            var cert = (X509Certificate)pemReader.ReadObject();
            try {
                cert.CheckValidity(); 
                if (!CheckCertSubjectNames(cert)) return null;
            }
            catch (CertificateExpiredException) {
                return null;
            }
            catch (CertificateNotYetValidException) {
                return null;
            }

            return cert;
        }