예제 #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;
        }
예제 #2
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);
        }
예제 #3
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);
        }
예제 #4
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));
                }
            }
        /// <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);
        }
예제 #6
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);
        }
예제 #7
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);
        }
        } // 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
예제 #9
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));
        }
예제 #10
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());
        }
예제 #11
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;
        }
예제 #12
0
파일: SHA1.cs 프로젝트: 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));
        }
예제 #13
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
예제 #14
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));
        }
예제 #15
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);
                }
            }
        }
예제 #16
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());
     }
 }
예제 #17
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);
        }
예제 #18
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);
        }
 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);
 }
예제 #20
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);
        }
예제 #21
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);
        }
예제 #22
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));
        }
        } // End Function ImportKeyPair

        //public static void ReadPrivateKeyFile(string privateKeyFileName)
        //{
        //    Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters key = null;

        //    using (System.IO.StreamReader streamReader = System.IO.File.OpenText(privateKeyFileName))
        //    {
        //        Org.BouncyCastle.OpenSsl.PemReader pemReader =
        //            new Org.BouncyCastle.OpenSsl.PemReader(streamReader);
        //        key = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters) pemReader.ReadObject();
        //    } // End Using streamReader

        //    // Note:
        //    // cipher.Init(false, key);
        //    // !!!
        //} // End Function ReadPrivateKey


        public Org.BouncyCastle.Crypto.AsymmetricKeyParameter ReadPublicKeyFile(string pemFilename)
        {
            Org.BouncyCastle.Crypto.AsymmetricKeyParameter keyParameter = null;

            using (System.IO.StreamReader streamReader = System.IO.File.OpenText(pemFilename))
            {
                Org.BouncyCastle.OpenSsl.PemReader pemReader = new Org.BouncyCastle.OpenSsl.PemReader(streamReader);
                keyParameter = (Org.BouncyCastle.Crypto.AsymmetricKeyParameter)pemReader.ReadObject();
            } // End Using fileStream

            return(keyParameter);
        } // End Function ReadPublicKey
예제 #24
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);
            }
예제 #25
0
        public static List <string> PEMCertificateListToPEMs(string pemList)
        {
            List <string> pems = new List <string>();

            if (string.IsNullOrEmpty(pemList))
            {
                throw new CryptoException("private key cannot be null");
            }
            AsymmetricKeyParameter privkey = null;
            X509Certificate        cert    = null;

            using (StringReader ms = new StringReader(pemList))
            {
                PemReader pemReader = new PemReader(ms);
                object    o;
                while ((o = pemReader.ReadObject()) != null)
                {
                    if (o is AsymmetricKeyParameter)
                    {
                        AsymmetricKeyParameter par = (AsymmetricKeyParameter)o;
                        if (par.IsPrivate)
                        {
                            privkey = par;
                        }
                    }

                    if (o is AsymmetricCipherKeyPair)
                    {
                        privkey = ((AsymmetricCipherKeyPair)o).Private;
                    }

                    if (o is X509Certificate)
                    {
                        if (cert != null)
                        {
                            pems.Add(DumpOnePEM(cert, privkey));
                            privkey = null;
                        }

                        X509Certificate cc = (X509Certificate)o;
                        cert = cc;
                    }
                }

                if (cert != null)
                {
                    pems.Add(DumpOnePEM(cert, privkey));
                }
            }

            return(pems);
        }
예제 #26
0
        static PasswordEncrypter()
        {
            if (publicKey == null)
            {
                using (var sr = new StringReader(SiteConfig.EncryptKey))
                {
                    var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                    publicKey = (RsaKeyParameters)pemReader.ReadObject();
                }

                cipher.Init(true, publicKey);
            }
        }
예제 #27
0
        public static object FromPem(string cert)
        {
            object result;

            using (var _sr = new StringReader(cert))
            {
                var pRd = new PemReader(_sr);
                result = pRd.ReadObject();
                pRd.Reader.Close();
            }

            return(result);
        }
예제 #28
0
 protected override bool CreateCertificate(byte[] certbytes)
 {
     try
     {
         var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(ASCIIEncoding.ASCII.GetString(certbytes)));
         Cert = (X509Certificate)pemReader.ReadObject();
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
        public string EncodeToken()
        {
            var getName = User.Identity.Name;
            var idStore = 0;

            if (getName != "")
            {
                Guid Checksite = (Guid)Membership.GetUser(getName).ProviderUserKey;
                idStore = db.tb_mapping_store.Where(w => w.account_guid == Checksite).Select(s => s.site_id).FirstOrDefault();
            }

            if ((User.IsInRole("admin") || idStore != 0))
            {
                var uid = "TsWxiKGYrpSoLyOPXtBsccWkTwz2";

                var claims = new Dictionary <string, object> {
                    { "is_admin", User.IsInRole("admin") ? true : false },
                    { "site_id", idStore.ToString() }
                };

                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));
            }
            else
            {
                return("");
            }
        }
예제 #30
0
        /// <summary>
        /// Reads the signing certificate from a location.
        /// Supported locations: Blob storage, File, Local, KeyVault.
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="location"></param>
        /// <param name="log"></param>
        /// <returns>x509 certificate without private key</returns>
        private static X509Certificate ReadCertificate(string certificate, Location location, ILogger log)
        {
            log.LogInformation($"Reading certificate from {location}...");

            X509Certificate x509 = null;

            try
            {
                if (location == Location.File)
                {
                    x509 = DotNetUtilities.FromX509Certificate(
                        System.Security.Cryptography.X509Certificates.X509Certificate.CreateFromCertFile(certificate));
                }

                if (location == Location.Local)
                {
                    using (TextReader reader = new StringReader(certificate))
                    {
                        Org.BouncyCastle.OpenSsl.PemReader pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);
                        x509 = (X509Certificate)pemReader.ReadObject();
                    };
                }

                if (location == Location.Blob)
                {
                    blobClient = new BlobClient(blobConnectionString, blobContainerName, certificate);
                    BlobDownloadInfo download = blobClient.Download();
                    using (TextReader reader = new StreamReader(download.Content))
                    {
                        Org.BouncyCastle.OpenSsl.PemReader pemReader = new Org.BouncyCastle.OpenSsl.PemReader(reader);
                        x509 = (X509Certificate)pemReader.ReadObject();
                    };
                }

                if (location == Location.KeyVault)
                {
                    var client = new CertificateClient(new Uri($"https://{keyVaultName}.vault.azure.net"), new DefaultAzureCredential());
                    keyVaultCertificate = client.GetCertificate(certificate);
                    x509 = new Org.BouncyCastle.X509.X509CertificateParser().ReadCertificate(keyVaultCertificate.Cer);
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex.Message);
            }

            log.LogInformation($"Finished reading certificate {x509.SubjectDN} from {location}.");

            return(x509);
        }
        /// <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;
        }
예제 #32
0
        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="publicKeyCSharp"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string EncryptCSharp(string data, string encoding = "UTF-8")
        {
            RsaKeyParameters pubkey;

            using (var sr = new StreamReader(System.AppDomain.CurrentDomain.BaseDirectory + WxPayConfig.RSACERT_PATH)) {
                var pemReader = new Org.BouncyCastle.OpenSsl.PemReader(sr);
                pubkey = (RsaKeyParameters)pemReader.ReadObject();
            }
            var cipher = (BufferedAsymmetricBlockCipher)CipherUtilities.GetCipher("RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING");

            cipher.Init(true, pubkey);
            var message = Encoding.UTF8.GetBytes(data);
            var output  = Encrypt(message, cipher);

            return(Convert.ToBase64String(output));
        }
예제 #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;
        }