Ejemplo n.º 1
0
        public async Task <ClientResponse> CreateClient(string accessToken, List <string> grantTypes, List <string> redirectUris, string logoutUri, string[] allowedScopes, string organizationName, string organizationEnhId)
        {
            var clientRequest = new ClientRequest
            {
                ClientName = $"{organizationName} ({organizationEnhId})",
                Secrets    = new[]
                {
                    new Secret
                    {
                        Type  = SecretTypes.RsaPrivateKey,
                        Value = RSAKeyGenerator.CreateNewKey(false, organizationEnhId)
                    }
                },
                RequireClientSecret    = false,
                AlwaysSendClientClaims = true,
                GrantTypes             = grantTypes,
                RedirectUris           = redirectUris,
                LogoutUri     = logoutUri,
                AllowedScopes = allowedScopes,
                AllowAccessTokensViaBrowser      = true,
                AlwaysIncludeUserClaimsInIdToken = true,
                AllowOfflineAccess = true
            };

            client.SetBearerToken(accessToken);
            return(await client.StoreClient(clientRequest));
        }
Ejemplo n.º 2
0
 private void CreateNewKey()
 {
     RsaKey = new RSAKey();
     if (!RsaKey.ReadConfig("config.rsa"))
     {
         RsaKey = RSAKeyGenerator.GenerateKeyPair(1024);
     }
     ReadKeysFromFile();
 }
Ejemplo n.º 3
0
        public static ClientAssertion CreateWithRsaKeys(string clientId, string tokenEndpointUrl)
        {
            var rsa         = RSAKeyGenerator.GetRsaParameters();
            var securityKey = new RsaSecurityKey(rsa);
            var assertion   = JwtGenerator.Generate(clientId, tokenEndpointUrl, JwtGenerator.SigningMethod.RsaSecurityKey, securityKey, SecurityAlgorithms.RsaSha512);

            return(new ClientAssertion {
                client_assertion = assertion
            });
        }
Ejemplo n.º 4
0
        public void RSASimpleTest()
        {
            var data = new BigInteger(123456).ToByteArray();

            var(publicKey, privateKey) = RSAKeyGenerator.Generate();
            var sign          = RSA.Crypt(data, privateKey);
            var decryptedData = RSA.Crypt(sign, publicKey);

            data.Should().BeEquivalentTo(decryptedData, options => options.WithStrictOrdering());
        }
Ejemplo n.º 5
0
        public void CanGenerateValidKey()
        {
            var keyGen = new RSAKeyGenerator();

            var key = keyGen.Generate(512);

            var plainText       = new BigInteger(123456789);
            var cipherText      = BigInteger.ModPow(plainText, key.E, key.N);
            var actualPlainText = BigInteger.ModPow(cipherText, key.D, key.N);

            Assert.AreEqual(plainText, actualPlainText);
        }
Ejemplo n.º 6
0
        public void RSAFunctionalTest()
        {
            var data = new byte[123456];

            new Random().NextBytes(data);
            var hash = SHA512.GetHash(data);

            var(publicKey, privateKey) = RSAKeyGenerator.Generate();
            var sign          = RSA.Crypt(hash, privateKey);
            var decryptedHash = RSA.Crypt(sign, publicKey);

            hash.Should().BeEquivalentTo(decryptedHash, options => options.WithStrictOrdering());
        }
Ejemplo n.º 7
0
        public MainWindow()
        {
            InitializeComponent();

            try
            {
                var rsaPublicKey = RSAKeyGenerator.GetPublicKeyAsXml();
                RsaPublicKey = rsaPublicKey;
            }
            catch (Exception)
            {
                RsaPublicKey = "No RSA public key available";
            }
        }
 public bool Check(bool throwException = true)
 {
     try
     {
         if (string.IsNullOrEmpty(Authority))
         {
             throw new ArgumentNullException("Authority");
         }
         if (string.IsNullOrEmpty(ClientId))
         {
             throw new ArgumentNullException("ClientId");
         }
         if (SigningMethod == SigningMethod.None && string.IsNullOrEmpty(ClientSecret))
         {
             throw new ArgumentNullException("ClientSecret");
         }
         if (SigningMethod == SigningMethod.X509EnterpriseSecurityKey && string.IsNullOrEmpty(CertificateThumbprint))
         {
             throw new ArgumentNullException("CertificateThumprint");
         }
         if (SigningMethod == SigningMethod.RsaSecurityKey && !RSAKeyGenerator.KeyExists())
         {
             throw new ArgumentNullException("No RSA key found");
         }
         if (string.IsNullOrEmpty(RedirectUri))
         {
             throw new ArgumentNullException("RedirectUri");
         }
         // Not true if all we want to do is call for a refresh token..
         //if (string.IsNullOrEmpty(Scope))
         //{
         //    throw new ArgumentNullException("Scope");
         //}
         //if (!Scope.Contains("openid"))
         //{
         //    throw new ArgumentException("Scope must include openid", nameof(Scope));
         //}
     }
     catch
     {
         if (throwException)
         {
             throw;
         }
         return(false);
     }
     return(true);
 }
Ejemplo n.º 9
0
        /// <summary>
        ///     Runs a quick check to see it the options are correctly setup. Note that this is only a shallow check and the
        ///     options can still be invalid.
        /// </summary>
        /// <param name="throwException">Specifies if the check should throw an exception if the check fails or just return false.</param>
        /// <returns></returns>
        public bool Check(bool throwException = true)
        {
            try
            {
                if (string.IsNullOrEmpty(Authority))
                {
                    throw new NullReferenceException("Authority");
                }

                if (string.IsNullOrEmpty(ClientId))
                {
                    throw new NullReferenceException("ClientId");
                }

                if (SigningMethod == SigningMethod.None && string.IsNullOrEmpty(ClientSecret))
                {
                    throw new NullReferenceException("ClientSecret");
                }

                if (SigningMethod == SigningMethod.X509EnterpriseSecurityKey &&
                    string.IsNullOrEmpty(CertificateThumbprint))
                {
                    throw new NullReferenceException("CertificateThumprint");
                }

                if (SigningMethod == SigningMethod.RsaSecurityKey && !RSAKeyGenerator.KeyExists(ClientId))
                {
                    throw new NullReferenceException("No RSA key found");
                }

                if (string.IsNullOrEmpty(RedirectUri))
                {
                    throw new NullReferenceException("RedirectUri");
                }
            }
            catch
            {
                if (throwException)
                {
                    throw;
                }
                return(false);
            }

            return(true);
        }
Ejemplo n.º 10
0
Archivo: RSATests.cs Proyecto: dmka/rsa
        public void CanEncryptDecryptMessage()
        {
            var keyGen = new RSAKeyGenerator();
            var key    = keyGen.Generate(512);

            var plainText = "the quick brown fox jumped over the lazy dog";
            var data      = new BigInteger(Encoding.UTF8.GetBytes(plainText)).ToByteArray();

            var rsa = new RSA(key);

            var cipherText     = rsa.Encrypt(data);
            var plainTextBytes = rsa.Decrypt(cipherText);

            var actualPlainText = Encoding.UTF8.GetString(plainTextBytes);

            Assert.AreEqual(plainText, actualPlainText);
        }
Ejemplo n.º 11
0
        private static void SHA256WithRSA_Sample()
        {
            var s = "hello sha256 with rsa";

            Console.WriteLine(s);

            var keyParameter = RSAKeyGenerator.Pkcs8(2048);

            Console.WriteLine("私钥:");
            Console.WriteLine(keyParameter.PrivateKey);
            Console.WriteLine("公钥:");
            Console.WriteLine(keyParameter.PublicKey);

            Console.WriteLine();

            Console.WriteLine("使用BouncyCastle:");

            var sign1 = SHA256WithRSA.GenerateSignature(s,
                                                        AsymmetricKeyUtilities.GetAsymmetricKeyParameterFormAsn1PrivateKey(keyParameter.PrivateKey));

            Console.WriteLine("sign1:");
            Console.WriteLine(sign1);

            var verified1 = SHA256WithRSA.VerifySignature(s, sign1,
                                                          AsymmetricKeyUtilities.GetAsymmetricKeyParameterFormPublicKey(keyParameter.PublicKey));

            Console.WriteLine("验证结果:");
            Console.WriteLine(verified1 ? "signature verified" : "signature not verified");
            Console.WriteLine();

            Console.WriteLine("不使用BouncyCastle:");

            var sign2 = SHA256WithRSA.GenerateSignature(s,
                                                        AsymmetricKeyUtilities.GetRsaParametersFormAsn1PrivateKey(keyParameter.PrivateKey));

            Console.WriteLine("sign2:");
            Console.WriteLine(sign2);

            var verified2 = SHA256WithRSA.VerifySignature(s, sign1,
                                                          AsymmetricKeyUtilities.GetAsymmetricKeyParameterFormPublicKey(keyParameter.PublicKey));

            Console.WriteLine("验证结果:");

            Console.WriteLine(verified2 ? "signature verified" : "signature not verified");
            Console.WriteLine();
        }
Ejemplo n.º 12
0
        public static void DecryptDataWithMicrosoft(string fileName, RSAKey key)
        {
            string[] temp         = fileName.Split('.');
            string   saveFileName = temp[0] + "_decryptedECB";

            if (temp.Length == 2)
            {
                saveFileName = temp[0] + "_decryptedECB." + temp[1];
            }

            FileStream readStream  = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            FileStream writeStream = new FileStream(saveFileName + "microsoft", FileMode.Create, FileAccess.Write);

            using (StreamWriter writer = new StreamWriter(writeStream))
            {
                using (StreamReader sr = new StreamReader(readStream))
                {
                    using (RSACryptoServiceProvider crypto = new RSACryptoServiceProvider())
                    {
                        RSAParameters rsaKey = new RSAParameters();
                        rsaKey.Modulus  = key.n.ToByteArray();
                        rsaKey.Exponent = key.e.ToByteArray();
                        rsaKey.D        = key.d.ToByteArray();
                        rsaKey.P        = key.p.ToByteArray();
                        rsaKey.Q        = key.q.ToByteArray();
                        rsaKey.DQ       = (key.d % (key.q - 1)).ToByteArray();
                        rsaKey.DP       = (key.d % (key.p - 1)).ToByteArray();
                        rsaKey.InverseQ = RSAKeyGenerator.ModularInverse(key.q, key.p).ToByteArray();
                        crypto.ImportParameters(rsaKey);

                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            byte[] bytes         = Encoding.UTF8.GetBytes(line);
                            string testowy       = Encoding.UTF8.GetString(bytes);
                            byte[] decryptedData = crypto.Decrypt(Convert.FromBase64String(testowy), RSAEncryptionPadding.Pkcs1);
                            writer.Write(Encoding.UTF8.GetString(decryptedData));
                        }
                    }
                }
            }
            readStream.Close();
            writeStream.Close();
        }
Ejemplo n.º 13
0
        public void SaveConfig()
        {
            FileStream stream = new FileStream("config.rsa", FileMode.OpenOrCreate);

            using (StreamWriter sw = new StreamWriter(stream))
            {
                sw.WriteLine("asn1 = SEQUENCE:rsa_key");
                sw.WriteLine("");
                sw.WriteLine("[rsa_key]");
                sw.WriteLine("version=INTEGER:0");
                sw.WriteLine($"modulus=INTEGER:{n}");
                sw.WriteLine($"pubExp=INTEGER:{e}");
                sw.WriteLine($"privExp=INTEGER:{d}");
                sw.WriteLine($"p=INTEGER:{p}");
                sw.WriteLine($"q=INTEGER:{q}");
                sw.WriteLine($"e1=INTEGER:{d % (p - 1)}");
                sw.WriteLine($"e2=INTEGER:{d % (q - 1)}");
                sw.WriteLine($"coeff=INTEGER:{RSAKeyGenerator.ModularInverse(q, p)}");
            }
            string cmdText = $"/C openssl asn1parse -genconf config.rsa -out newkey.der";

            Process.Start("CMD.exe", cmdText);
            Process proc = new Process();

            proc.StartInfo.UseShellExecute        = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.RedirectStandardError  = true;
            proc.StartInfo.FileName  = "CMD.exe";
            proc.StartInfo.Arguments = "/C openssl rsa -in newkey.der -inform der -text -check";
            proc.EnableRaisingEvents = true;
            proc.OutputDataReceived += Proc_OutputDataReceived;
            proc.Start();
            proc.BeginOutputReadLine();
            proc.WaitForExit();
            cmdText = $"/C openssl rsa -in newkey.der -inform DER -outform PEM -out id_rsa";
            proc    = Process.Start("CMD.exe", cmdText);
            proc.WaitForExit();
            cmdText = $"/C openssl rsa -in id_rsa -pubout > id_rsa.pub";
            Process.Start("CMD.exe", cmdText);
        }
Ejemplo n.º 14
0
        public async Task <ClientResponse> CreateClient(string accessToken, List <string> grantTypes, List <string> redirectUris, string logoutUri, string[] allowedScopes)
        {
            var clientRequest = new ClientRequest
            {
                ClientName = "Dcr created client" + Guid.NewGuid(),
                Secrets    = new[] {
                    new Secret {
                        Type  = SecretTypes.RsaPrivateKey,
                        Value = RSAKeyGenerator.CreateNewKey(false)
                    }
                },
                RequireClientSecret    = true,
                AlwaysSendClientClaims = true,
                GrantTypes             = grantTypes,
                RedirectUris           = redirectUris,
                LogoutUri     = logoutUri,
                AllowedScopes = allowedScopes
            };

            _client.SetBearerToken(accessToken);
            return(await _client.StoreClient(clientRequest));
        }
Ejemplo n.º 15
0
        public static SecurityToken ValidateToken(string token, string validIssuer, string validAudience)
        {
            var publicKey = RSAKeyGenerator.GetPublicKeyAsXml();

            var test = RSA.Create();

            test.FromXmlString(publicKey);

            var securityKey = new RsaSecurityKey(test.ExportParameters(false));

            var handler          = new JwtSecurityTokenHandler();
            var validationParams = new TokenValidationParameters
            {
                RequireSignedTokens = true,
                IssuerSigningKey    = securityKey,
                ValidAudience       = validAudience,
                ValidIssuer         = validIssuer
            };

            var claimsPrincipal = handler.ValidateToken(token, validationParams, out var validatedToken);

            return(validatedToken);
        }
Ejemplo n.º 16
0
        public MainWindow()
        {
            InitializeComponent();
            try
            {
                BrowserManager.Initialize();
                ShowApiLoadingDialog = false;

                try
                {
                    var rsaPublicKey = RSAKeyGenerator.GetPublicKeyAsXml();
                    RsaPublicKey = rsaPublicKey;
                }
                catch (Exception)
                {
                    RsaPublicKey = "No RSA public key available";
                }
            }
            catch (Exception)
            {
                MessageBox.Show(
                    @"The application does not have sufficient priveleges to write to the registry. Try starting again in administrator modus if you would like the applicastion to do the neccessary configurations.");
            }
        }
Ejemplo n.º 17
0
        private static BitArray GenerateInitializationVector(uint bytesCount)
        {
            BitArray arr = new BitArray(RSAKeyGenerator.GenerateRandomBigInteger(bytesCount));

            return(arr);
        }
Ejemplo n.º 18
0
 private void GenerateKey_Handler(object sender, System.Windows.RoutedEventArgs e)
 {
     RsaKey = RSAKeyGenerator.GenerateKeyPair(keyLengths[KeyLengthBox.SelectedIndex]);
     ReadKeysFromFile();
 }
Ejemplo n.º 19
0
        private void GetRsaPublicKeyButton_Click(object sender, RoutedEventArgs e)
        {
            var rsaPublicKey = RSAKeyGenerator.CreateNewKey(false);

            RsaPublicKey = rsaPublicKey;
        }
Ejemplo n.º 20
0
        private static void Certificate_Sample()
        {
            var algorithm = "RSA";
            var keySize   = 2048;

            //颁发者DN
            var issuer = new X509Name(new ArrayList
            {
                X509Name.C,
                X509Name.O,
                X509Name.OU,
                X509Name.L,
                X509Name.ST
            }, new Hashtable
            {
                [X509Name.C]  = "CN",
                [X509Name.O]  = "Fulu Newwork",
                [X509Name.OU] = "Fulu RSA CA 2020",
                [X509Name.L]  = "Wuhan",
                [X509Name.ST] = "Hubei",
            });
            //使用者DN
            var subject = new X509Name(new ArrayList
            {
                X509Name.C,
                X509Name.O,
                X509Name.CN
            }, new Hashtable
            {
                [X509Name.C]  = "CN",
                [X509Name.O]  = "ICH",
                [X509Name.CN] = "*.fulu.com"
            });

            var password           = "******";        //证书密码
            var signatureAlgorithm = "SHA256WITHRSA"; //签名算法

            var keyP = RSAKeyGenerator.Pkcs1();

            var pK = AsymmetricKeyUtilities.GetAsymmetricKeyParameterFormPrivateKey(keyP.PrivateKey);

            CertificateGenerator.GenerateSelfSignedCertificate(issuer, subject, pK);

            //生成证书
            // CertificateGenerator.X509V3(algorithm, keySize, password, signatureAlgorithm, DateTime.Now.AddDays(-1),DateTime.Now.AddDays(2), issuer, subject, "mycert.cert", "mypfx.pfx");

            var pfx = new X509Certificate2("mypfx.pfx", password, X509KeyStorageFlags.Exportable);



            var keyPair2 = DotNetUtilities.GetKeyPair(pfx.PrivateKey);
            var a        = pfx.GetRawCertDataString();

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

            var privateKey = Base64.ToBase64String(privateKeyInfo.ParsePrivateKey().GetEncoded());
            var publicKey  = Base64.ToBase64String(subjectPublicKeyInfo.GetEncoded());

            var cert = new X509Certificate2("mycert.cert", string.Empty, X509KeyStorageFlags.Exportable);

            var publicKey2 = Base64.ToBase64String(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(DotNetUtilities.FromX509Certificate(cert).GetPublicKey()).GetEncoded());

            Console.ForegroundColor = ConsoleColor.DarkYellow;

            Console.WriteLine("Pfx证书私钥:");
            Console.WriteLine(privateKey);

            Console.WriteLine("Pfx证书公钥:");
            Console.WriteLine(publicKey);

            Console.WriteLine("Cert证书公钥:");
            Console.WriteLine(publicKey2);

            var data = "hello rsa";

            Console.WriteLine($"加密原文:{data}");

            var pkcs1data = RSA.EncryptToBase64(data, AsymmetricKeyUtilities.GetAsymmetricKeyParameterFormPublicKey(publicKey), Algorithms.RSA_ECB_PKCS1Padding);

            Console.WriteLine("加密结果:");
            Console.WriteLine(pkcs1data);

            //pkcs1data =
            //    "KGbgP3Ns6kFyjJ7tbepdZ3X8zssoHKWyVzVesghWg8fFP0ZMVumf+iXJ93LBu3xqKWE/5JTr1qFc5u0Cm3BUPnusMjBTgMrQk3zopVOELpChFbkeTR2YHsdDZdBzaJVN4SQQwHMkp2w8Pyb9x1NjsFoHHQEskBUNnOEuGkEFZdg=";

            Console.WriteLine("解密结果:");
            var datares = RSA.DecryptFromBase64(pkcs1data,
                                                AsymmetricKeyUtilities.GetAsymmetricKeyParameterFormPrivateKey(privateKey), Algorithms.RSA_ECB_PKCS1Padding);

            Console.WriteLine(datares);
        }