/// <summary>
        /// 功能描述:RUI的参数
        /// </summary>
        /// <param name="parameter">参数</param>
        /// <param name="key">加密字段</param>
        /// <returns></returns>
        public string ProcessingRUI(Dictionary <string, string> parameter, string key)
        {
            RulePayBehavior PayBehavior = new RulePayBehavior();

            //得到异步通知地址
            string async_url = parameter["async_notify_url"].ToString();

            parameter["amount"] = (decimal.Parse(parameter["amount"]) * 100).ToString("F0");

            //删除异步地址和同步地址 进行签名
            parameter.Remove("async_notify_url");
            parameter.Remove("notify_url");
            //得到一个字符串
            string ascdict = PayBehavior.GetParamsStr(parameter);

            //java 私钥转.net xml
            string xmlprivateKey = RSAExtensions.ConvertToXmlPrivateKey(key);

            //私钥加密
            string sign = RSAUtil.PrivateKeyEncrypt(xmlprivateKey, ascdict);

            //添加 同步地址 异步地址 签名

            parameter.Add("notify_url", async_url);
            parameter.Add("async_notify_url", async_url);

            parameter.Add("sign", Utils.UrlEncode(sign));
            string jsontext = PayBehavior.GetParamsStr(parameter);

            //string jsontext = JsonHelper.SerializeObject(parameter);

            return(jsontext);
        }
Beispiel #2
0
        public static void TestX509Certificate2()
        {
            Console.WriteLine("TestX509Certificate2");

            // Generated using:
            // openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout private.key -out certificate_pub.crt
            string certificateText = File.ReadAllText("certificate_pub.crt");
            string privateKeyText  = File.ReadAllText("private.key");

            ICertificateProvider provider    = new CertificateFromFileProvider(certificateText, privateKeyText);
            X509Certificate2     certificate = provider.Certificate;

            Console.WriteLine("X509Certificate2:");
            Console.WriteLine(certificate);
            Console.WriteLine();
            Console.WriteLine("PrivateKey:");
            RSACryptoServiceProvider cryptoServiceProvider = provider.PrivateKey;

            ShowRSAProperties(cryptoServiceProvider);

            var xml = XDocument.Parse(RSAExtensions.ToXmlString(cryptoServiceProvider, true));

            Console.WriteLine(xml.ToString());

            // Sign the data
            byte[] hello     = new UTF8Encoding().GetBytes("Hello World");
            byte[] hashValue = cryptoServiceProvider.Encrypt(hello, false);

            // var publicKey = provider.PublicKey;
            byte[] decrypted = cryptoServiceProvider.Decrypt(hashValue, false);
            Console.WriteLine("decrypted: {0}", Encoding.UTF8.GetString(decrypted));
        }
        /// <summary>
        /// 功能描述:赤的参数
        /// </summary>
        /// <param name="parameter">参数</param>
        /// <param name="key">加密字段</param>
        /// <returns></returns>
        public string ProcessingXF(Dictionary <string, string> parameter, string key)
        {
            RulePayBehavior PayBehavior = new RulePayBehavior();

            Dictionary <String, string> newpram = new Dictionary <string, string>();



            string ascdict = JsonHelper.SerializeObject(parameter);

            //////java 私钥转.net xml
            string xmlprivateKey = RSAExtensions.RSAPublicKeyJava2DotNet(key);

            //私钥加密
            string sign = RSAUtil.Encrypt(key, Encoding.UTF8.GetBytes(ascdict));

            //添加 同步地址 异步地址 签名

            newpram.Add("merchantNo", "9900000000000111");
            newpram.Add("keyType", "1");
            newpram.Add("agentNo", "10000034");
            newpram.Add("data", sign);


            //string jsontext = PayBehavior.GetParamsStr(newpram);
            string jsontext = JsonHelper.SerializeObject(newpram);

            return(jsontext);
        }
Beispiel #4
0
        public static byte[] Decrypt(string privateKeyFile, byte[] encrypted)
        {
            byte[] decrypted;
            using (var rsa = new RSACryptoServiceProvider((int)KeySizes.SIZE_2048))
            {
                rsa.PersistKeyInCsp = false;
                string privateKey = File.ReadAllText(privateKeyFile);
                RSAExtensions.FromXmlString(rsa, privateKey);
                decrypted = rsa.Decrypt(encrypted, true);
            }

            return(decrypted);
        }
        public void ImportPkcs1PrivateKeyFromPemFileTest()
        {
            var rsa = RSA.Create();

            rsa.ImportPrivateKeyFromPemFile("test.key");

            Assert.NotNull(rsa.ExportRSAPrivateKey());
            Assert.Equal(
                RSAExtensions.GetKeyBody(File.ReadAllText("test.key"))
                .Replace("\n", string.Empty)
                .Replace("\r", string.Empty),
                Convert.ToBase64String(rsa.ExportRSAPrivateKey()));
        }
Beispiel #6
0
        public static byte[] Encrypt(string publicKeyFile, byte[] plain)
        {
            byte[] encrypted;
            using (var rsa = new RSACryptoServiceProvider((int)KeySizes.SIZE_2048))
            {
                rsa.PersistKeyInCsp = false;
                string publicKey = File.ReadAllText(publicKeyFile);

                RSAExtensions.FromXmlString(rsa, publicKey);
                encrypted = rsa.Encrypt(plain, true);
            }

            return(encrypted);
        }
Beispiel #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="strSalt"></param>
        /// <param name="password">the encrypted base64string password</param>
        /// <returns></returns>
        public static string GetPasswordHash(string strSalt, string password)
        {
            RSA rsa            = RSAExtensions.CreateRsaFromPrivateKey(RSAConstants.PrivateKey);
            var cipherBytes    = System.Convert.FromBase64String(password);
            var plainTextBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
            //var planText = Encoding.UTF8.GetString(plainTextBytes);
            var hashedTextBytes = Encoding.UTF8.GetBytes(strSalt).Concat(plainTextBytes).ToArray();

            MD5 md5        = MD5.Create();
            var byteMd5Pwd = md5.ComputeHash(hashedTextBytes);
            var strMd5Pwd  = BitConverter.ToString(byteMd5Pwd).Replace("-", "");

            return(strMd5Pwd);
        }
Beispiel #8
0
 private SigningCredentials InitializeRsaKey()
 {
     try
     {
         RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(2048);
         var rsaParametersPrivate             = RSAExtensions.RSAParametersFromXmlFile("private-rsa-key.xml");
         rsaProvider.ImportParameters(rsaParametersPrivate);
         var securityKey = new RsaSecurityKey(rsaProvider);
         return(new SigningCredentials(securityKey, SecurityAlgorithms.RsaSha256));
     }
     catch (Exception ex)
     {
         throw new Exception("Identity Server RSA Key initialization failed. " + ex.ToString());
     }
 }
Beispiel #9
0
        public static void GenerateKeys(string publicKeyFile, string privateKeyFile)
        {
            using (var rsa = new RSACryptoServiceProvider((int)KeySizes.SIZE_2048))
            {
                rsa.PersistKeyInCsp = false;

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

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

                string publicKey = RSAExtensions.ToXmlString(rsa, false);
                File.WriteAllText(publicKeyFile, publicKey);
                string privateKey = RSAExtensions.ToXmlString(rsa, true);
                File.WriteAllText(privateKeyFile, privateKey);
            }
        }
Beispiel #10
0
 internal void SetServerPublicKey(ServerPublicKey serverPublicKey)
 {
     ServerPublicKey = RSAExtensions.FromPublicKeyPemString(serverPublicKey.Value);
 }
Beispiel #11
0
 public void SetServerPublicKey(ServerPublicKey serverPublicKey)
 {
     _serverPublicKey = RSAExtensions.FromPemString(serverPublicKey.Value);
 }
Beispiel #12
0
        public static void Main(string[] args)
        {
            const int    rsaKeySize = 728; //Smaller key sizes are easier to generate while testing
            var          prsa       = new PowerRSA(rsaKeySize, PowerRSA.PHashAlgorithm.SHA256);
            const string p          = "this is n";
            var          c          = prsa.EncryptStringWithPublicKey(p);

            Console.WriteLine(c);
            var d = prsa.DecryptStringWithPrivateKey(c);

            Console.WriteLine(d);
            var x = prsa.PublicKey;

            Console.WriteLine("RSAProvider Data: " + prsa.PrivateKey);
            Console.WriteLine("Exporting Private key to PKCS format:");
            var priPemKey = RSAExtensions.ConvertPrivateKeyToPKCS(prsa);

            Console.WriteLine(priPemKey);
            Console.Write("PKCS Signing...");
            const string signData  = "Hello, World!";
            var          signature = RSAExtensions.SignWithPKCSPrivateKey(signData, prsa);

            Console.WriteLine(signature);
            Console.Write("Verifying...");
            var verification = RSAExtensions.VerifyWithPKCSPublicKey(signData, signature, prsa);

            Console.WriteLine(verification);

            prsa.Dispose();

            var pub = new PowerRSA(x, rsaKeySize, PowerRSA.PHashAlgorithm.SHA256);
            var e   = pub.EncryptStringWithPublicKey(p);
            var d2  = prsa.DecryptStringWithPrivateKey(e);

            Console.WriteLine(d2);
            pub.Dispose();
            Console.WriteLine(e);
            const string k  = "1234";
            var          a1 = PowerAES.Encrypt(p, k);

            Console.WriteLine(a1);
            var d1 = PowerAES.Decrypt(a1, k);

            Console.WriteLine(d1);
            Console.WriteLine(PowerAES.SHA512Hash(p));

            Console.WriteLine("Testing AES encryption on strings...");
            var plaintextString = "Hi i like pie";
            var password        = "******";
            var encryptedString = PowerAES.Encrypt(plaintextString, password);
            var decryptedString = PowerAES.Decrypt(encryptedString, password);

            Debug.Assert(decryptedString == plaintextString);

            Console.WriteLine("Testing AES encryption directly on bytes...");
            var aesProvider    = new AESProvider();
            var salt           = aesProvider.GenerateRandomBytes(24);
            var key            = aesProvider.DeriveKeyFromPassphrase("monkey", salt);
            var iv             = aesProvider.GenerateRandomBytes(16); //128-bit IV
            var plaintextBytes = Encoding.UTF8.GetBytes("Hi I am a monkey");
            var encryptedBytes = aesProvider.EncryptBytes(plaintextBytes, key, iv);
            var decryptedBytes = aesProvider.DecryptBytes(iv, salt, encryptedBytes, key);

            Debug.Assert(decryptedBytes.SequenceEqual(plaintextBytes));
            Console.WriteLine("Hash Test");
            var hash = HashUtils.SHA512(k);

            Console.WriteLine(hash);
            Console.WriteLine("Demo completed");
            Console.ReadKey();
        }
Beispiel #13
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            this.ReturnUrl = returnUrl;
            if (!ModelState.IsValid)
            {
                this.ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(Page());
            }
            //This doesn't count login failures towards account lockout
            //To enable password failures to trigger account lockout, set lockoutOnFailure: true
            string strSql  = "SELECT * FROM accounts WHERE Email = @Email;";
            var    account = await this.db.AccountDb.QueryFirstOrDefaultAsync <Models.Account>(strSql, new { Input.Email });

            if (account == null)
            {
                this.ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(Page());
            }

            RSA rsa             = RSAExtensions.CreateRsaFromPrivateKey(RSAConstants.PrivateKey);
            var cipherBytes     = System.Convert.FromBase64String(Input.Password);
            var plainTextBytes  = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
            var hashedTextBytes = Encoding.UTF8.GetBytes(account.Salt).Concat(plainTextBytes).ToArray();
            MD5 md5             = MD5.Create();
            var byteMd5Pwd      = md5.ComputeHash(hashedTextBytes);
            var strMd5Pwd       = BitConverter.ToString(byteMd5Pwd).Replace("-", "");

            if (account.PasswordHash != strMd5Pwd)
            {
                this.ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return(Page());
            }
            strSql = @"
SELECT * FROM Users WHERE ID = @UserID;
SELECT UserID, UserRoles.RoleID, Name AS RoleName FROM UserRoles INNER JOIN Roles ON UserRoles.RoleID = Roles.RoleID WHERE UserID = @UserID;";
            var multiResult = await this.db.AccountDb.QueryMultipleAsync(strSql, new { account.UserID });

            var user = await multiResult.ReadFirstOrDefaultAsync <Models.User>();

            var listUserRoles = await multiResult.ReadAsync <Models.UserRole>();

            if (user == null)
            {
                this.ModelState.AddModelError(string.Empty, "the account of user not found, please contact administrator.");
                return(Page());
            }

            //_logger.LogInformation("User Logged in.");
            var id = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypesConstants.Name, ClaimTypesConstants.Role);

            id.AddClaim(new Claim(ClaimTypesConstants.NameIdentifier, user.ID.ToString()));
            id.AddClaim(new Claim(ClaimTypesConstants.Name, user.NickName));
            id.AddClaim(new Claim(ClaimTypesConstants.AuthenticationMethod, "Email"));
            //get roles of this type
            foreach (var userRole in listUserRoles)
            {
                id.AddClaim(new Claim(ClaimTypesConstants.Role, userRole.RoleName));
            }
            var userPrincipal = new ClaimsPrincipal(id);

            await this.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                               userPrincipal, new AuthenticationProperties()
            {
                IsPersistent = Input.RememberMe
            });

            return(LocalRedirect(Url.GetLocalUrl(returnUrl)));

            //if (result.IsLockedOut)
            //{
            //    _logger.LogWarning("User account locket out.");
            //    return RedirectToPage("./Lockout");
            //}
            //if we got this far, something failed, redisplay form
        }