public CertificateSigningService(SecurityConfiguration configuration)
        {
            using var streamReader = File.OpenText(configuration.PrivateKeyPath);
            var pemReader = new PemReader(streamReader);
            var @object   = pemReader.ReadObject();
            var asymmetricCipherKeyPair = @object as AsymmetricCipherKeyPair;

            if (asymmetricCipherKeyPair != null)
            {
                @object = asymmetricCipherKeyPair.Private;
            }
            try
            {
                _privateKey = (RsaPrivateCrtKeyParameters)@object;
            }
            catch (InvalidCastException)
            {
                throw new Exception($"Invalid RSA private key (Path='{configuration.PrivateKeyPath}').");
            }
        }
Esempio n. 2
0
        public static RSA GetTestUserPlatformRsaProvider()
        {
            using (var stringReader = new StringReader(TestUserRsaPrivKey))
            {
                var pemReader        = new PemReader(stringReader);
                var rsaPrivKeyParams = pemReader.ReadObject() as RsaPrivateCrtKeyParameters;

                RSAParameters rsaParams = new RSAParameters();
                rsaParams.D        = rsaPrivKeyParams.Exponent.ToByteArrayUnsigned();
                rsaParams.DP       = rsaPrivKeyParams.DP.ToByteArrayUnsigned();
                rsaParams.DQ       = rsaPrivKeyParams.DQ.ToByteArrayUnsigned();
                rsaParams.Exponent = rsaPrivKeyParams.PublicExponent.ToByteArrayUnsigned();
                rsaParams.InverseQ = rsaPrivKeyParams.QInv.ToByteArrayUnsigned();
                rsaParams.Modulus  = rsaPrivKeyParams.Modulus.ToByteArrayUnsigned();
                rsaParams.P        = rsaPrivKeyParams.P.ToByteArrayUnsigned();
                rsaParams.Q        = rsaPrivKeyParams.Q.ToByteArrayUnsigned();

                return(RSA.Create(rsaParams));
            }
        }
        public string GetSHA1withRSAKey(string pemTxtFilePath, string sData)
        {
            try
            {
                if (!File.Exists(pemTxtFilePath))
                {
                    throw new Exception("PEM (txt) file not found.");
                }

                using (var reader = File.OpenText(pemTxtFilePath))
                {
                    var pemReader           = new PemReader(reader);
                    var bouncyRsaParameters = (RsaPrivateCrtKeyParameters)pemReader.ReadObject();

                    var rsaParameters = new RSAParameters();
                    rsaParameters.Modulus  = bouncyRsaParameters.Modulus.ToByteArrayUnsigned();
                    rsaParameters.P        = bouncyRsaParameters.P.ToByteArrayUnsigned();
                    rsaParameters.Q        = bouncyRsaParameters.Q.ToByteArrayUnsigned();
                    rsaParameters.DP       = bouncyRsaParameters.DP.ToByteArrayUnsigned();
                    rsaParameters.DQ       = bouncyRsaParameters.DQ.ToByteArrayUnsigned();
                    rsaParameters.InverseQ = bouncyRsaParameters.QInv.ToByteArrayUnsigned();
                    rsaParameters.D        = bouncyRsaParameters.Exponent.ToByteArrayUnsigned();
                    rsaParameters.Exponent = bouncyRsaParameters.PublicExponent.ToByteArrayUnsigned();

                    var privateKey = new RSACryptoServiceProvider();
                    privateKey.ImportParameters(rsaParameters);

                    var sha = new SHA1Managed();

                    UTF8Encoding str        = new UTF8Encoding(true);
                    byte[]       signedData = privateKey.SignData(str.GetBytes(sData), sha);
                    var          result     = Convert.ToBase64String(signedData);

                    return(result);
                }
            }
            catch (Exception)
            {
                throw new Exception("Signing SHA1 with RSA failed.");
            }
        }
Esempio n. 4
0
 public SoftToken(string name, string certPath, string keyPath)
 {
     Name = name;
     SharpOCSP.log.Debug("Configuring token: " + name);
     SharpOCSP.log.Debug("Certificate path: " + certPath);
     //Read OCSP signer certificate
     try{
         var ocspCertReader = new PemReader(new StreamReader(certPath));
         _ocspCertificate = (X509Certificate)ocspCertReader.ReadObject();
     }catch (System.UnauthorizedAccessException e) {
         throw new OcspFilesystemException("Error reading ocsp certificate: " + keyPath, e);
     }catch (FileNotFoundException e) {
         throw new OcspFilesystemException("Error reading ocsp certificate: " + keyPath, e);
     }
     SharpOCSP.log.Debug("Certificate key path: " + keyPath);
     //Read private key
     try{
         var keyReader    = new PemReader(new StreamReader(keyPath));
         var key_from_pem = keyReader.ReadObject();
         RsaPrivateCrtKeyParameters private_key      = key_from_pem as RsaPrivateCrtKeyParameters;
         AsymmetricCipherKeyPair    private_key_pair = key_from_pem as AsymmetricCipherKeyPair;
         if (private_key != null)
         {
             _privateKey = private_key;
         }
         else if (private_key_pair != null)
         {
             _privateKey = (RsaPrivateCrtKeyParameters)private_key_pair.Private;
         }
         else
         {
             throw new OcspFilesystemException("Error reading private key: " + keyPath);
         }
     }catch (System.UnauthorizedAccessException e) {
         throw new OcspFilesystemException("Can't access private key path: " + keyPath, e);
     }catch (FileNotFoundException e) {
         throw new OcspFilesystemException("PEM file doesn't exist: " + keyPath, e);
     }catch (InvalidCastException e) {
         throw new OcspFilesystemException("Is it PEM really?: " + keyPath, e);
     }
 }
Esempio n. 5
0
        public static string GenerateToken(IConfiguration config)
        {
            // retrieve appID and privateKey from configuration
            var    appId          = config["Authentication:appId"];
            var    priavteKeyPath = config["Authentication:privateKey"];
            string privateKey     = "";

            using (var reader = File.OpenText(priavteKeyPath)) // file containing RSA PKCS1 private key
                privateKey = reader.ReadToEnd();

            //generate claims list
            const int SECONDS_EXPIRY = 3600;
            var       t              = DateTime.UtcNow - new DateTime(1970, 1, 1);
            var       iat            = new Claim("iat", ((Int32)t.TotalSeconds).ToString(), ClaimValueTypes.Integer32);                    // Unix Timestamp for right now
            var       application_id = new Claim("application_id", appId);                                                                 // Current app ID
            var       exp            = new Claim("exp", ((Int32)(t.TotalSeconds + SECONDS_EXPIRY)).ToString(), ClaimValueTypes.Integer32); // Unix timestamp for when the token expires
            var       jti            = new Claim("jti", Guid.NewGuid().ToString());                                                        // Unique Token ID
            var       claims         = new List <Claim>()
            {
                iat, application_id, exp, jti
            };

            //create rsa parameters
            RSAParameters rsaParams;

            using (var tr = new StringReader(privateKey))
            {
                var pemReader        = new PemReader(tr);
                var kp               = pemReader.ReadObject();
                var privateRsaParams = kp as RsaPrivateCrtKeyParameters;
                rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams);
            }

            //generate and return JWT
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParams);
                Dictionary <string, object> payload = claims.ToDictionary(k => k.Type, v => (object)v.Value);
                return(Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256));
            }
        }
Esempio n. 6
0
        public void ValidateToken_V1_S_2()
        {
            const string token = "v1.public.eyJkYXRhIjoidGhpcyBpcyBhIHNpZ25lZCBtZXNzYWdlIiw" +
                                 "iZXhwIjoiMjAxOS0wMS0wMVQwMDowMDowMCswMDowMCJ9sBTIb0J_4mis" +
                                 "AuYc4-6P5iR1rQighzktpXhJ8gtrrp2MqSSDkbb8q5WZh3FhUYuW_rg2X" +
                                 "8aflDlTWKAqJkM3otjYwtmfwfOhRyykxRL2AfmIika_A-_MaLp9F0iw4S" +
                                 "1JetQQDV8GUHjosd87TZ20lT2JQLhxKjBNJSwWue8ucGhTgJcpOhXcthq" +
                                 "az7a2yudGyd0layzeWziBhdQpoBR6ryTdtIQX54hP59k3XCIxuYbB9qJM" +
                                 "pixiPAEKBcjHT74sA-uukug9VgKO7heWHwJL4Rl9ad21xyNwaxAnwAJ7C" +
                                 "0fN5oGv8Rl0dF11b3tRmsmbDoIokIM0Dba29x_T3YzOyg.eyJraWQiOiJ" +
                                 "kWWtJU3lseFFlZWNFY0hFTGZ6Rjg4VVpyd2JMb2xOaUNkcHpVSEd3OVVx" +
                                 "biJ9";
            const string pem = "-----BEGIN PUBLIC KEY-----\n" +
                               "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyaTgTt53ph3p\n" +
                               "5GHgwoGWwz5hRfWXSQA08NCOwe0FEgALWos9GCjNFCd723nCHxBtN1qd\n" +
                               "74MSh/uN88JPIbwxKheDp4kxo4YMN5trPaF0e9G6Bj1N02HnanxFLW+g\n" +
                               "mLbgYO/SZYfWF/M8yLBcu5Y1Ot0ZxDDDXS9wIQTtBE0ne3YbxgZJAZTU\n" +
                               "5XqyQ1DxdzYyC5lF6yBaR5UQtCYTnXAApVRuUI2Sd6L1E2vl9bSBumZ5\n" +
                               "IpNxkRnAwIMjeTJB/0AIELh0mE5vwdihOCbdV6alUyhKC1+1w/FW6HWc\n" +
                               "p/JG1kKC8DPIidZ78Bbqv9YFzkAbNni5eSBOsXVBKG78Zsc8owIDAQAB\n" +
                               "-----END PUBLIC KEY-----";
            // {"data":"this is a signed message", "exp":"2019-01-01T00:00:00+00:00"}
            // footer = {"kid":"dYkISylxQeecEcHELfzF88UZrwbLolNiCdpzUHGw9Uqn"}

            var reader    = new PemReader(new StringReader(pem));
            var pemObject = (RsaKeyParameters)reader.ReadObject();

            var rsaKey = RSA.Create(DotNetUtilities.ToRSAParameters(pemObject));

            var handler = new PasetoTokenHandler();
            var result  = handler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuer   = false,
                ValidateAudience = false,
                ValidateLifetime = false,

                IssuerSigningKey = new RsaSecurityKey(rsaKey)
            });

            result.IsValid.Should().BeTrue();
        }
Esempio n. 7
0
        public TimeBasedService(
            IV2RayCollectService v2ray,
            IAsymmetric asymmetric,
            ISymmetric symmetric,
            IHttpClientFactory factory,
            IConfiguration configuration)
        {
            this.v2rayService = v2ray;
            this.http         = factory.CreateClient();
            this.asymmetric   = asymmetric;
            this.symmetric    = symmetric;
            string path = configuration.GetValue <string>("PublicKey");

            using (TextReader reader = File.OpenText(path))
            {
                PemReader pem       = new PemReader(reader);
                var       pemObject = pem.ReadObject();
                this.parameter = pemObject as AsymmetricKeyParameter;
            }
            http.BaseAddress = new Uri(configuration.GetConnectionString("DataServer"));
        }
Esempio n. 8
0
        /// <summary>
        /// Create an RSA parameter based on XML format public key
        /// </summary>
        /// <param name="publicKey"></param>
        /// <returns>RSAParameters</returns>
        protected sealed override RSAParameters CreateRsapFromPublicKey(string publicKey)
        {
            publicKey = RsaPemFormatHelper.PublicKeyFormat(publicKey);

            PemReader pr = new PemReader(new StringReader(publicKey));

            object obj = pr.ReadObject();

            if (!(obj is RsaKeyParameters rsaKey))
            {
                throw new Exception("Public key format is incorrect");
            }

            RSAParameters rsap = new RSAParameters();

            rsap.Modulus = rsaKey.Modulus.ToByteArrayUnsigned();

            rsap.Exponent = rsaKey.Exponent.ToByteArrayUnsigned();

            return(rsap);
        }
        private string CreateToken(Dictionary <string, object> payload)
        {
            RSAParameters rsaParams;

            using (var tr = new StringReader(this.PrivateKey))
            {
                var pemReader = new PemReader(tr);
                var keyPair   = pemReader.ReadObject() as AsymmetricCipherKeyPair;
                if (keyPair == null)
                {
                    throw new ArgumentException("Could not read RSA PrivateKey, please check your keys.\n See how generate a valid key: https://gist.github.com/ThiagoBarradas/e58ac282665306977777ffa3f32df376");
                }
                var privateRsaParams = keyPair.Private as RsaPrivateCrtKeyParameters;
                rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams);
            }
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParams);
                return(Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256));
            }
        }
Esempio n. 10
0
    /// <summary>
    /// Public Key Convert pem->xml
    /// </summary>
    /// <param name="publicKey"></param>
    /// <returns></returns>
    public static string RSAPublicKeyPemToXml(string publicKey)
    {
        publicKey = RSAPublicKeyFormat(publicKey);

        PemReader        pr     = new PemReader(new StringReader(publicKey));
        RsaKeyParameters rsaKey = pr.ReadObject() as RsaKeyParameters;

        if (rsaKey == null)
        {
            throw new Exception("Public key format is incorrect");
        }
        XElement publicElement = new XElement("RSAKeyValue");
        //Modulus
        XElement pubmodulus = new XElement("Modulus", Convert.ToBase64String(rsaKey.Modulus.ToByteArrayUnsigned()));
        //Exponent
        XElement pubexponent = new XElement("Exponent", Convert.ToBase64String(rsaKey.Exponent.ToByteArrayUnsigned()));

        publicElement.Add(pubmodulus);
        publicElement.Add(pubexponent);
        return(publicElement.ToString());
    }
Esempio n. 11
0
        //private RSACryptoServiceProvider _RSAAlg;

        public RsaDecrypter(String pk)
        {
            //_RSAAlg = new RSACryptoServiceProvider();
            //RSAParameters rsap = new RSAParameters();
            using (TextReader tr = new StringReader(pk))
            {
                //byte[] bytes = new byte[pk.Length*sizeof (char)];
                //System.Buffer.BlockCopy(pk.ToCharArray(), 0, bytes, 0, bytes.Length);

                AsymmetricCipherKeyPair keyPair;
                var pemReader = new PemReader(tr);
                keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();

                this.PrivateKey = (RsaKeyParameters)keyPair.Private;

                //Console.WriteLine(_privateKey.ToString());

                this.Cipher = new RsaEngine();
                this.Cipher.Init(false, this.PrivateKey);
            }
        }
Esempio n. 12
0
        private static SecurityKey LoadPublicKey(this string publicKeyPem)
        {
            using (StringReader reader = new StringReader(publicKeyPem))
            {
                PemReader pem            = new PemReader(reader);
                AsymmetricKeyParameter o = (AsymmetricKeyParameter)pem.ReadObject();

                if (o is RsaKeyParameters rsaKeyParameters)
                {
                    return(new RsaSecurityKey(DotNetUtilities.ToRSA(rsaKeyParameters)));
                }

                if (o is ECPublicKeyParameters eCPublicKeyParameters)
                {
                    byte[] publicKey = eCPublicKeyParameters.Q.GetEncoded();
                    return(new ECDsaSecurityKey(LoadPublicKey(publicKey)));
                }

                return(null);
            }
        }
Esempio n. 13
0
        private static SecurityKey LoadPrivateKey(string privateKeyPem)
        {
            using (StringReader reader = new StringReader(privateKeyPem))
            {
                PemReader pem             = new PemReader(reader);
                AsymmetricCipherKeyPair o = (AsymmetricCipherKeyPair)pem.ReadObject();

                if (o.Private is RsaPrivateCrtKeyParameters rsaPrivateCrtKeyParameters)
                {
                    return(new RsaSecurityKey(DotNetUtilities.ToRSA(rsaPrivateCrtKeyParameters)));
                }

                if (o.Private is ECPrivateKeyParameters eCPrivateKeyParameters)
                {
                    byte[] privateKey = eCPrivateKeyParameters.D.ToByteArrayUnsigned();
                    return(new ECDsaSecurityKey(LoadPrivateKey(privateKey)));
                }

                return(null);
            }
        }
Esempio n. 14
0
        public string CreateToken(TToken data)
        {
            RSAParameters rsaParams;

            using (var tr = new StringReader(_keyProvider.Key))
            {
                var pemReader = new PemReader(tr, _passwordFinder);
                if (!(pemReader.ReadObject() is AsymmetricCipherKeyPair keyPair))
                {
                    throw new Exception("Could not read RSA private key");
                }
                var privateRsaParams = keyPair.Private as RsaPrivateCrtKeyParameters;
                rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams);
            }

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParams);
                return(JWT.Encode(data, rsa, JwsAlgorithm.RS256));
            }
        }
Esempio n. 15
0
        public void WriterTest()
        {
            string dir = @"/tmp/";

            if (Directory.Exists(Path.Combine(dir, "certs")))
            {
                Directory.Delete(Path.Combine(dir, "certs"), true);
            }
            string chainIdStr       = "0xb84fe09f32ac58fccf8946c42d81532370621acb000554b0e15a0affc6b4502d";
            var    certificateStore = new CertificateStore(dir);
            var    keyPair          =
                certificateStore.WriteKeyAndCertificate(chainIdStr, "192.168.197.39");

            using (StreamReader streamReader = new StreamReader(Path.Combine(dir, "certs", chainIdStr + ".cert.pem")))
            {
                PemReader       pr          = new PemReader(streamReader);
                X509Certificate certificate = (X509Certificate)pr.ReadObject();
                Assert.Equal(keyPair.PublicKey, certificate.GetPublicKey());
            }
            Directory.Delete(Path.Combine(dir, "certs"), true);
        }
Esempio n. 16
0
        private void doWriteReadTest(
            AsymmetricKeyParameter akp,
            string algorithm)
        {
            StringWriter sw = new StringWriter();
            PemWriter    pw = new PemWriter(sw);

            pw.WriteObject(akp, algorithm, testPassword, random);
            pw.Writer.Close();

            string data = sw.ToString();

            PemReader pr = new PemReader(new StringReader(data), new Password(testPassword));

            AsymmetricCipherKeyPair kp = pr.ReadObject() as AsymmetricCipherKeyPair;

            if (kp == null || !kp.Private.Equals(akp))
            {
                Fail("Failed to read back test key encoded with: " + algorithm);
            }
        }
Esempio n. 17
0
        internal string CreateToken(Dictionary <string, object> payload)
        {
            RSAParameters rsaParams;

            using (var tr = new StringReader(privateKey))
            {
                var pemReader = new PemReader(tr);
                var keyPair   = pemReader.ReadObject() as AsymmetricCipherKeyPair;
                if (keyPair == null)
                {
                    throw new Exception("Could not read RSA private key");
                }
                var privateRsaParams = keyPair.Private as RsaPrivateCrtKeyParameters;
                rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams);
            }
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParams);
                return(Jose.JWT.Encode(payload, rsa, Jose.JwsAlgorithm.RS256));
            }
        }
        static void Main(string[] args)
        {
            string privateKeyText = File.ReadAllText(Environment.CurrentDirectory + @"\PEMKeys\app_private_key.pem");
            string publicKeyText  = File.ReadAllText(Environment.CurrentDirectory + @"\PEMKeys\app_public_key.pem");

            PemReader privateKeyPemReader         = new PemReader(new StringReader(privateKeyText));
            RsaPrivateCrtKeyParameters privateKey = (privateKeyPemReader.ReadObject() as AsymmetricCipherKeyPair).Private as RsaPrivateCrtKeyParameters;

            PemReader        publicKeyPemReader = new PemReader(new StringReader(publicKeyText));
            RsaKeyParameters publicKey          = publicKeyPemReader.ReadObject() as RsaKeyParameters;

            var privateKeyXmlString = DotNetUtilities.ToRSA(privateKey).ToXmlString(true);
            var publicKeyXmlString  = DotNetUtilities.ToRSA(publicKey).ToXmlString(false);

            var verified1 = Test_SHA1withRSA_Sign_Verify_With_DotNet(privateKeyXmlString, publicKeyXmlString);
            var verified2 = Test_SHA1withRSA_Sign_Verify_With_BouncyCastle(privateKey, publicKey);
            var verified3 = Test_SHA1withRSA_Sign_With_BouncyCastle_Then_Verify_With_DotNet(privateKey, publicKeyXmlString);
            var verified4 = Test_SHA1withRSA_Sign_With_DotNet_Then_Verify_With_BouncyCastle(privateKeyXmlString, publicKey);

            Console.WriteLine("{0}, {1}, {2}, {3}", verified1, verified2, verified3, verified4);
        }
Esempio n. 19
0
        private void EncryptedTest(AsymmetricKeyParameter 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()));

            AsymmetricKeyParameter rdKey = (AsymmetricKeyParameter)pRd.ReadObject();

            pRd.Reader.Close();

            Assert.AreEqual(privKey, rdKey);
        }
Esempio n. 20
0
        public static string DecodeToken(string token, string publicRsaKey)
        {
            RSAParameters rsaParams;

            using (var tr = new StringReader(publicRsaKey))
            {
                var pemReader       = new PemReader(tr);
                var publicKeyParams = pemReader.ReadObject() as RsaKeyParameters;
                if (publicKeyParams == null)
                {
                    throw new Exception("Could not read RSA public key");
                }
                rsaParams = DotNetUtilities.ToRSAParameters(publicKeyParams);
            }
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(rsaParams);
                // This will throw if the signature is invalid
                return(Jose.JWT.Decode(token, rsa, Jose.JwsAlgorithm.RS256));
            }
        }
        /// <summary>
        /// 签名方式1
        /// </summary>
        /// <param name="data">签名内容的json串格式</param>
        /// <param name="pemFile">私钥文件物理路径</param>
        /// <returns></returns>
        public static string CreateSignedToken(string data, string pemFile)
        {
            var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            //5分钟内有效
            var exp = ts.TotalMilliseconds + 30000;

            var payload = new Dictionary <string, object>
            {
                { "sub", "tester" },
                { "exp", exp },
                { "datas", GetMd5(data) }
            };

            using (StreamReader reader = File.OpenText(pemFile))
            {
                PemReader pemReader             = new PemReader(reader);
                AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
                RSA privateKey = DotNetUtilities.ToRSA((RsaPrivateCrtKeyParameters)keyPair.Private);
                return(JWT.Encode(payload, privateKey, JwsAlgorithm.PS256));
            }
        }
Esempio n. 22
0
        public static string GetPublicKeyPEMfromCert(string certPem)
        {
            // 証明書の読み込み
            var pemReader  = new PemReader(new StringReader(certPem));
            var readedCert = (Org.BouncyCastle.X509.X509Certificate)pemReader.ReadObject();

            // Get
            var publicKey = readedCert.GetPublicKey();

            // ToPem
            var mem = new MemoryStream();

            using (var writer = new StreamWriter(mem, Encoding.ASCII)) {
                var pemWriter = new PemWriter(writer);
                pemWriter.WriteObject(publicKey);
                pemWriter.Writer.Flush();
            }
            var pem = Encoding.UTF8.GetString(mem.ToArray());

            return(pem);
        }
Esempio n. 23
0
        public static bool ECVerify(string signedData, string signature, string publicKey)
        {
            try
            {
                byte[] r = Convert.FromBase64String(signature);
                byte[] s = Encoding.UTF8.GetBytes(signedData);

                PemReader pemReader                = new PemReader(new StringReader(publicKey));
                AsymmetricKeyParameter pKey        = (AsymmetricKeyParameter)pemReader.ReadObject();
                ECKeyParameters        publicECKey = (ECKeyParameters)pKey;

                ISigner sig = SignerUtilities.GetSigner("Sha512WithECDSA");
                sig.Init(false, publicECKey);
                sig.BlockUpdate(s, 0, s.Length);
                return(sig.VerifySignature(r));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 24
0
        private static X509Certificate2 LoadFromPem(string certPath, string keyPath)
        {
            try
            {
                using (var certWithoutPrivateKey = new X509Certificate2(certPath))
                    using (var keyFile = File.OpenText(keyPath))
                    {
                        // Workaround https://github.com/dotnet/corefx/issues/20414
                        var pemReader = new PemReader(keyFile);

                        var pemObj = pemReader.ReadObject();
                        switch (pemObj)
                        {
                        case RsaPrivateCrtKeyParameters rsaParams:
                        {
                            var rsa = CreateRSA(rsaParams);
                            // See https://github.com/dotnet/corefx/issues/24454#issuecomment-388231655
                            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                            {
                                using (var certWithKey = certWithoutPrivateKey.CopyWithPrivateKey(rsa))
                                {
                                    return(new X509Certificate2(certWithKey.Export(X509ContentType.Pkcs12)));
                                }
                            }
                            else
                            {
                                // Only works on Linux/macOS
                                return(certWithoutPrivateKey.CopyWithPrivateKey(rsa));
                            }
                        }
                        }

                        throw new InvalidOperationException($"Failed to read private key from '{keyPath}'. Unexpected format: " + pemObj.GetType().Name);
                    }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Failed to load certificate file from '{certPath}' and '{keyPath}'", ex);
            }
        }
Esempio n. 25
0
        public void loadKey(String filein, String privateKeyFile)
        {
            byte[] cipherTextBytes = File.ReadAllBytes(filein);

            PemReader pr = new PemReader(
                (StreamReader)File.OpenText(privateKeyFile)
                ); //"./private.pem"
            AsymmetricCipherKeyPair keys = (AsymmetricCipherKeyPair)pr.ReadObject();

            OaepEncoding eng = new OaepEncoding(new RsaEngine());

            eng.Init(false, keys.Private);

            int         length         = cipherTextBytes.Length;
            int         blockSize      = eng.GetInputBlockSize();
            List <byte> plainTextBytes = new List <byte>();

            for (int chunkPosition = 0;
                 chunkPosition < length;
                 chunkPosition += blockSize)
            {
                int chunkSize = Math.Min(blockSize, length - chunkPosition);
                plainTextBytes.AddRange(eng.ProcessBlock(
                                            cipherTextBytes, chunkPosition, chunkSize
                                            ));
            }

            //Inicializar encryptor
            var aes = new AesCryptoServiceProvider();

            //aes.GenerateKey();
            byte[] clave = plainTextBytes.ToArray();
            byte[] iv    = Convert.FromBase64String("Enf3G3rTMC7lwBJmtVcRvQ==");

            aes       = new AesCryptoServiceProvider();
            encryptor = aes.CreateEncryptor(clave, iv);
            decryptor = aes.CreateDecryptor(clave, iv);

            AESKey = Convert.ToBase64String(plainTextBytes.ToArray());
        }
Esempio n. 26
0
        public static string loadsslx509(string password)
        {
            UnicodeEncoding ByteConverter = new UnicodeEncoding();

            string certificate = @"E:\Safcomcert\certg.cer";

            //load cert to a X509
            //X509Certificate cert = X509Certificate.CreateFromCertFile(certificate);

            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048))
            {
                /**get an instance of RSAParameters from ExportParameters function
                 * RSAParameters rsakeyinfo = RSA.ExportParameters(false);
                 * rsakeyinfo.Modulus = cert.GetPublicKey();
                 * var kj =Convert.ToBase64String(cert.GetPublicKey());
                 * //Import key parameters into RSA.
                 * RSA.ImportParameters(rsakeyinfo);
                 * return Convert.ToBase64String(RSA.Encrypt(Encoding.UTF8.GetBytes(password), RSAEncryptionPadding.Pkcs1));
                 **/
                var             plainTextBytes = Encoding.UTF8.GetBytes(password);
                PemReader       pr             = new PemReader(File.OpenText(certificate));
                X509Certificate cert           = (X509Certificate)pr.ReadObject();
                //PKCS1 v1.5 paddings
                Pkcs1Encoding eng = new Pkcs1Encoding(new RsaEngine());
                eng.Init(true, cert.GetPublicKey());
                int         length          = plainTextBytes.Length;
                int         blockSize       = eng.GetInputBlockSize();
                List <byte> cipherTextBytes = new List <byte>();
                for (int chunkPosition = 0;
                     chunkPosition < length;
                     chunkPosition += blockSize)
                {
                    int chunkSize = Math.Min(blockSize, length - chunkPosition);
                    cipherTextBytes.AddRange(eng.ProcessBlock(
                                                 plainTextBytes, chunkPosition, chunkSize
                                                 ));
                }
                return(Convert.ToBase64String(cipherTextBytes.ToArray()));
            }
        }
Esempio n. 27
0
        // dsa public pem 转 xml
        private static void DSAPublicPEM2XML()
        {
            DSA dsa;

            using (var rdr = new StreamReader("D:\\dsapub.pem"))
            {
                var pr  = new PemReader(rdr);
                var o   = pr.ReadObject() as DsaPublicKeyParameters;
                var prm = new CspParameters(13);
                prm.Flags = CspProviderFlags.UseMachineKeyStore;

                dsa = new DSACryptoServiceProvider(prm);
                var dp = new DSAParameters
                {
                    G = o.Parameters.G.ToByteArrayUnsigned(),
                    P = o.Parameters.P.ToByteArrayUnsigned(),
                    Q = o.Parameters.Q.ToByteArrayUnsigned(),
                    Y = o.Y.ToByteArrayUnsigned()
                };

                if (o.Parameters.ValidationParameters != null)
                {
                    dp.Counter = o.Parameters.ValidationParameters.Counter;
                    dp.Seed    = o.Parameters.ValidationParameters.GetSeed();
                }

                dsa.ImportParameters(dp);
            }

            // 写入xml文件
            using (var fs = new FileStream("D:\\xtoken.pubkey", FileMode.Create, FileAccess.Write))
            {
                var sw = new StreamWriter(fs);

                var xml = dsa.ToXmlString(false);
                sw.Write(xml);
                sw.Flush();
                sw.Dispose();
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.Cryptography.DkimSigner"/> class.
        /// </summary>
        /// <remarks>
        /// Creates a new <see cref="DkimSigner"/>.
        /// </remarks>
        /// <param name="fileName">The file containing the private key.</param>
        /// <param name="domain">The domain that the signer represents.</param>
        /// <param name="selector">The selector subdividing the domain.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="fileName"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="domain"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="selector"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// <paramref name="fileName"/> is a zero-length string, contains only white space, or
        /// contains one or more invalid characters as defined by
        /// <see cref="System.IO.Path.InvalidPathChars"/>.
        /// </exception>
        /// <exception cref="System.FormatException">
        /// The file did not contain a private key.
        /// </exception>
        /// <exception cref="System.IO.DirectoryNotFoundException">
        /// <paramref name="fileName"/> is an invalid file path.
        /// </exception>
        /// <exception cref="System.IO.FileNotFoundException">
        /// The specified file path could not be found.
        /// </exception>
        /// <exception cref="System.UnauthorizedAccessException">
        /// The user does not have access to read the specified file.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public DkimSigner(string fileName, string domain, string selector)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            if (fileName.Length == 0)
            {
                throw new ArgumentException("The file name cannot be empty.", "fileName");
            }

            if (domain == null)
            {
                throw new ArgumentNullException("domain");
            }

            if (selector == null)
            {
                throw new ArgumentNullException("selector");
            }

            AsymmetricCipherKeyPair key;

            using (var stream = new StreamReader(fileName)) {
                var reader = new PemReader(stream);

                key = reader.ReadObject() as AsymmetricCipherKeyPair;
            }

            if (key == null)
            {
                throw new FormatException("Private key not found.");
            }

            SignatureAlgorithm = DkimSignatureAlgorithm.RsaSha256;
            PrivateKey         = key.Private;
            Selector           = selector;
            Domain             = domain;
        }
Esempio n. 29
0
    /// <summary>
    /// 采用标准RSA算法
    /// </summary>
    /// <param name="EncryptString"></param>
    /// <returns></returns>
    public async static Task <string> RSAEncrypt(string EncryptString)
    {
        // var pempath = $"{Environment.CurrentDirectory}/{ConfigHelper.Configuration["WeChatPay:RsaPublicKey"]}";
        if (!File.Exists(WxPayConfig.pempath))
        {
            var PublicKey = await WxPayApi.Getpublickey();

            if (!string.IsNullOrWhiteSpace(PublicKey))
            {
                File.WriteAllText(WxPayConfig.pempath, PublicKey);
            }
            else
            {
                return("获取公钥失败!");
            }
        }

        string R;
        // 加载公钥
        RsaKeyParameters pubkey;

        using (var sr = new StreamReader(WxPayConfig.pempath))
        {
            var pemReader = new PemReader(sr);
            pubkey = (RsaKeyParameters)pemReader.ReadObject();
        }

        // 初始化cipher
        var cipher =
            (BufferedAsymmetricBlockCipher)CipherUtilities.GetCipher("RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING");

        cipher.Init(true, pubkey);

        // 加密message
        var message = Encoding.UTF8.GetBytes(EncryptString);
        var output  = EncryptUtil.Encrypt(message, cipher);

        R = Convert.ToBase64String(output);
        return(R);
    }
Esempio n. 30
0
            public static string PublicKeyPemPkcs8ToXml(string publicKey)
            {
                var pemReader = new PemReader(new StringReader(publicKey.AppendPkcs8PublicKeyFormat()));

                if (pemReader.ReadObject() is not RsaKeyParameters rsaKey)
                {
                    throw new Exception("Public key format is incorrect");
                }

                var publicElement = new XElement("RSAKeyValue");

                //Modulus
                var publicModulus = new XElement("Modulus", Convert.ToBase64String(rsaKey.Modulus.ToByteArrayUnsigned()));

                //Exponent
                var publicExponent = new XElement("Exponent", Convert.ToBase64String(rsaKey.Exponent.ToByteArrayUnsigned()));

                publicElement.Add(publicModulus);
                publicElement.Add(publicExponent);

                return(publicElement.ToString());
            }
        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");
                }
            }
        }
        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);
            }
        }
        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);
        }
        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);
        }