public async Task <ActionResult <ResponseModel> > Create(UserCreateViewModel model) { var response = ResponseModelFactory.CreateInstance; if (model.LoginName.Trim().Length <= 0) { response.SetFailed("请输入登录名称"); return(Ok(response)); } await using (_dbContext) { if (await _dbContext.DncUser.CountAsync(x => x.LoginName == model.LoginName) > 0) { response.SetFailed("登录名已存在"); return(Ok(response)); } //RSAHelper rSAHelper = new RSAHelper // (RSAType.RSA,Encoding.UTF8, CeyhConfiguration.TheRSASetting.Private,CeyhConfiguration.TheRSASetting.Public); var entity = _mapper.Map <UserCreateViewModel, DncUser>(model); entity.CreatedOn = DateTime.Now; entity.Password = _rSaHelper.Encrypt(model.Password); entity.Guid = Guid.NewGuid(); entity.Status = model.Status; await _dbContext.DncUser.AddAsync(entity); await _dbContext.SaveChangesAsync(); response.SetSuccess(); return(Ok(response)); } }
private void button3_Click(object sender, EventArgs e) { var jmRSA = new RSAHelper(rsaKey1.Text); var result = jmRSA.Encrypt(Encoding.Default.GetBytes(richTextBox2.Text)); richTextBox2.Text = Convert.ToBase64String(result); }
public static void RSATest() { string data = "123456"; //2048 公钥 string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoQh0wEqx/R2H1v00IU12Oc30fosRC/frhH89L6G+fzeaqI19MYQhEPMU13wpeqRONCUta+2iC1sgCNQ9qGGf19yGdZUfueaB1Nu9rdueQKXgVurGHJ+5N71UFm+OP1XcnFUCK4wT5d7ZIifXxuqLehP9Ts6sNjhVfa+yU+VjF5HoIe69OJEPo7OxRZcRTe17khc93Ic+PfyqswQJJlY/bgpcLJQnM+QuHmxNtF7/FpAx9YEQsShsGpVo7JaKgLo+s6AFoJ4QldQKir2vbN9vcKRbG3piElPilWDpjXQkOJZhUloh/jd7QrKFimZFldJ1r6Q59QYUyGKZARUe0KZpMQIDAQAB"; //2048 私钥 string privateKey = "MIIEpAIBAAKCAQEAoQh0wEqx/R2H1v00IU12Oc30fosRC/frhH89L6G+fzeaqI19MYQhEPMU13wpe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QVUinAEinTcAe5+LKXNPx4sbX3hcrJUbk0m+rSu4G0B/f5cyXBsi9wFCAzDdHgBduCepxSr04Sc9Hde1uQQi7kCgYB0U20HP0Vh+TG2RLuE2HtjVDD2L/CUeQEiXEHzjxXWnhvTg+MIAnggvpLwQwmMxkQ2ACr5sd/3YuCpB0bxV5o594nsqq9FWVYBaecFEjAGlWHSnqMoXWijwu/6X/VOTbP3VjH6G6ECT4GR4DKKpokIQrMgZ9DzaezvdOA9WesFdQKBgQCWfeOQTitRJ0NZACFUn3Fs3Rvgc9eN9YSWj4RtqkmGPMPvguWo+SKhlk3IbYjrRBc5WVOdoX8JXb2/+nAGhPCuUZckWVmZe5pMSr4EkNQdYeY8kOXGSjoTOUH34ZdKeS+e399BkBWIiXUejX/Srln0H4KoHnTWgxwNpTsBCgXu8Q=="; string encryptStr = RSAHelper.Encrypt(data, publicKey); Console.WriteLine($"encryptStr={encryptStr}"); Console.WriteLine(); string data2 = RSAHelper.Decrypt(encryptStr, privateKey); Console.WriteLine($"data2={data2}"); Console.WriteLine(); string signStr = RSAHelper.SignWithSHA256(data, privateKey); Console.WriteLine($"sign={signStr}"); Console.WriteLine(); bool verify = RSAHelper.VerifyWithSHA256(data, signStr, publicKey); Console.WriteLine($"verify={verify}"); Console.WriteLine(); }
/// <summary>密码式,验证账号密码,并返回令牌</summary> /// <param name="username">账号</param> /// <param name="password">密码</param> /// <returns></returns> public async Task <TokenInfo> GetToken(String username, String password) { var client = GetClient(); var key = SecurityKey; if (!key.IsNullOrEmpty()) { var name = ""; var p = key.IndexOf('$'); if (p >= 0) { name = key.Substring(0, p); key = key.Substring(p + 1); } // RSA公钥加密 var pass = RSAHelper.Encrypt(password.GetBytes(), key).ToBase64(); password = $"$rsa${name}${pass}"; } return(await client.GetAsync <TokenInfo>("sso/token", new { grant_type = "password", client_id = AppId, client_secret = Secret, username, password })); }
public static HttpResponseMessage GetResponse(dynamic request, IHeaderDictionary headers, HttpMethod httpMethod, PathString path) { ApiSafeData CriptoSafeData = new ApiSafeData() { Data = TripleDESHelper.Encrypt(JsonSerializer.Serialize(request), out string desParameters), Des = RSAHelper.Encrypt(desParameters, Env.RfiPublicKey), Signature = RSAHelper.Sign(desParameters, Env.PartnerPrivateKey) }; if (String.IsNullOrEmpty(Env.CertificateFilePath)) { using (var clientHandler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return(true); } }) { return(Resend(headers, httpMethod, clientHandler, CriptoSafeData, path)); } } else { using (var clientHandler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Manual, SslProtocols = SslProtocols.Tls12, ClientCertificates = { new X509Certificate2(Env.CertificateFilePath) } }) { return(Resend(headers, httpMethod, clientHandler, CriptoSafeData, path)); } } }
static public int Encrypt(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif RSAHelper self = (RSAHelper)checkSelf(l); System.String a1; checkType(l, 2, out a1); System.Boolean a2; checkType(l, 3, out a2); var ret = self.Encrypt(a1, a2); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif }
public JsonResult GetOTP(string number) { ArrayList arrUserDetails = new ArrayList(); try { Random generator = new Random(); string OTP = generator.Next(0, 999999).ToString("D6"); var rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, privateKey, publicKey); string Message = smsUrl + smsKey + "&senderid=" + senderId + "&route=" + route + "&number=" + number + "&message=" + message + OTP; bool isOTPSent = SendMessage.SendSMS(OTP, Message); //bool isOTPSent = true; if (isOTPSent == true) { arrUserDetails.Add(rsa.Encrypt(OTP)); } else { arrUserDetails.Add("SMS Not Sent"); } } catch (Exception ex) { objExceptionLoggingToSQL.LogAppException(ex.StackTrace); arrUserDetails.Add("ERROR"); } return(Json(arrUserDetails)); }
public static string EncryptToBase64(string public_key_xml, string raw, bool fOAEP) { RSAHelper rsa = new RSAHelper(); rsa.SetPublicKey(public_key_xml); return(rsa.Encrypt(raw, fOAEP)); }
/// <summary>编码密码,在传输中保护安全,一般使用RSA加密</summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> protected virtual String EncodePassword(String username, String password) { if (password.IsNullOrEmpty()) { return(password); } var key = SecurityKey; if (!key.IsNullOrEmpty()) { var name = ""; var p = key.IndexOf('$'); if (p >= 0) { name = key.Substring(0, p); key = key.Substring(p + 1); } // RSA公钥加密 var pass = RSAHelper.Encrypt(password.GetBytes(), key).ToBase64(); password = $"$rsa${name}${pass}"; } return(password); }
internal SafeData Encrypt_Data <DD>(DD decryted_data) where DD : class { TripleDESHelper des = new TripleDESHelper(); using (RSAHelper rsa_partner = new RSAHelper(RSAType.RSA2, Encoding.UTF8, Globals.key_private, apiUser.PublicKey)) { response = JsonConvert.SerializeObject(decryted_data); #if DEBUG Console.Out.WriteLine(response); #endif string encryptedStr = des.Encrypt(response); string desPrms = des.GetParameters(); string desEncrypted = rsa_partner.Encrypt(desPrms); string signStr = rsa_partner.Sign(desPrms); bool signVerify = false; using (RSAHelper rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, Globals.key_private, Globals.key_public)) { signVerify = rsa.Verify(desPrms, signStr); } using (SafeData sd = new SafeData()) { sd.Data = encryptedStr; sd.Signature = signStr; sd.Des = desEncrypted; chainLogger.Step(Tool.GetCurrentMethod()); return(sd); } } }
public void RSAHelper_Encrypt_By_Public_Decrypt_Success() { string input = "Hello, this is Shawn, I am learning about RSA by using BigInteger class"; var bytes = Encoding.UTF8.GetBytes(input); var resultBytes = RSAHelper.Encrypt(bytes, _rsaPublic); string result = Convert.ToBase64String(resultBytes); Debug.WriteLine("Encrypt by public key: "); Debug.WriteLine(result); EncDec ed = new EncDec(); string encryptedByED = ed.RSAEncrypt(_rsaPublicXml, input); Debug.WriteLine("WARNNING: Encrypt result are {0} equal between RSAHelper and EncDec class.", encryptedByED == result ? "" : " NOT ", ""); byte[] decryptBytes = RSAHelper.Decrypt(Convert.FromBase64String(result), _rsaPrivate); string resultDecrypted = Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); Debug.WriteLine("Decrypt by public key: "); Debug.WriteLine(resultDecrypted); string resultED = ed.RSADecrypt(_rsaPrivateXml, encryptedByED); Assert.AreEqual(input, resultDecrypted); Assert.AreEqual(input, resultED); }
public void EncryptTest() { RSAHelper rsa = new RSAHelper(PrivateKey, PublicKey); string value = rsa.Encrypt("{'abc':'def','qqq':'eee','aaa':'bbb'}"); //Assert.Fail(); }
private string get_pwa_rsa(string password) { RSAHelper rsaHelper = new RSAHelper(); rsaHelper.SetPublic(rsa_pub_baidu.Substring(0, rsa_pub_baidu.LastIndexOf('-') + 1)); return(rsaHelper.Encrypt(password)); }
public IHttpActionResult Log() { var token = RSAHelper.Encrypt("*****@*****.**"); //SetPrincipal(user); return(Json(new { Success = true, token = token })); }
/// <summary> /// Get RSA encrypted password. /// </summary> /// <param name="password"></param> /// <returns></returns> private string get_pwa_rsa(string password) { RSAHelper rsa = new RSAHelper(); rsa.SetPublic(weibo_rsa_n, "10001"); string data = servertime + "\t" + nonce + "\n" + password; return(rsa.Encrypt(data).ToLower()); }
public void EncryptDecrypt() { string data = "123456"; string encryptStr = RSAHelper.Encrypt(data, PUBLICKEY); string data2 = RSAHelper.Decrypt(encryptStr, PRIVATEKEY); Assert.Equal(data, data2); }
public string Protect(AuthenticationTicket data) { var userData = _serializer.Serialize(data); var protectedData = rsa.Encrypt(userData); var s1 = Base64UrlTextEncoder.Encode(protectedData); return(s1); }
public void EncryptTest() { var publicKey = @"<RSAKeyValue><Modulus>4cedf65bJcLZen/qnNUn1WXwzCJGp8x1nnKaBiBmYmNxCB6aIDwToqWLFonL/4FHMDItItw3PVkMWK3hMJ+5TZpB36H56iW06EYRtba4rviKb5KF/i+fbREqE4rADxBZIb/d1hP29ciA7D/JP6Cd6FreHWa42HaHXfeqsEHsjAE=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; var privateKey = @"<RSAKeyValue><Modulus>4cedf65bJcLZen/qnNUn1WXwzCJGp8x1nnKaBiBmYmNxCB6aIDwToqWLFonL/4FHMDItItw3PVkMWK3hMJ+5TZpB36H56iW06EYRtba4rviKb5KF/i+fbREqE4rADxBZIb/d1hP29ciA7D/JP6Cd6FreHWa42HaHXfeqsEHsjAE=</Modulus><Exponent>AQAB</Exponent><P>6aG9bMiBbgflnj9Rleng7vBQQPuWuuR7ETMw9XQnL1WLxEeZs8zn36Ph+ziSg6TDvOhBHlLC49lmHdvha0vJpw==</P><Q>92VsZInwwVfUVL/oyS87Ya4PR0FBRI9pZJyR6C4TTf7vTMCBC2XDV6uRC+m9RU/JypEuOsp8+WLgBVHlrCjiFw==</Q><DP>HvjCE9nAzsVdO01Jk4Ydu49AFF1F7iC779vJccCkMTI2BR840Q0o8AzZuGQXiDwfdruTZmGyVGJNl0e+6mpxoQ==</DP><DQ>R5wqBegPskdUBLwQC7wKOjoB3iQ7WjcQ0LipW0WK/PagGd1W/Q+VvZjBwWsFCD0SMfpYIVhfWGiQY7nS+0RSPQ==</DQ><InverseQ>MC5PTTSaiCRRGerW9CpWq6k+b1pBT5q3QO0TonmqPVoJ5dyprVgeHmLUPkmefKcqLQh8+5Bdw15fjJfI9g8iBg==</InverseQ><D>MOcemxA119j7aAga1ftpVFRvMpfd++xSMY6bA+aypm7phZuzQHYivqDinnAcSmxC8hJ8KkfOgzAtd2u6EeEWrmshZ04ZZ+doDc+aejLBcm+CtvqzW10loMIdbsoAYxGw+TV3P8sddRU7xQjbR6nLmcudzAFQiV3yoOe6Ynp7Wo0=</D></RSAKeyValue>"; var cipher = RSAHelper.Encrypt("cszfp.com", publicKey); var clear = RSAHelper.Decrypt(cipher, privateKey); Assert.AreEqual("cszfp.com", clear); }
public void RSAHelperSelfEncryptAndDecrypt() { RSAHelper helper1 = new RSAHelper(); string original = "This is test message"; byte[] encrypted = helper1.Encrypt(original); string decrypted = helper1.Decrypt(encrypted); Assert.Equal(original, decrypted); }
public ActionResult GetToken() { var tokenvalue = DateTime.Now.Ticks.ToString() + "," + Request.UserHostAddress; var token = RSAHelper.Encrypt(tokenvalue); var result = checkTokenValid(token, Request.UserHostAddress); return(Json(token, JsonRequestBehavior.AllowGet)); }
public void EncryptAndDecrypt() { var prvKey = @"-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAnzyis1ZjfNB0bBgKFMSvvkTtwlvBsaJq7S5wA+kzeVOVpVWw kWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHcaT92whREFpLv9cj5lTeJSibyr/Mr m/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIytvHWTxZYEcXLgAXFuUuaS3uF9gEi NQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0e+lf4s4OxQawWD79J9/5d3Ry0vbV 3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWbV6L11BWkpzGXSW4Hv43qa+GSYOD2 QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9MwIDAQABAoIBACiARq2wkltjtcjs kFvZ7w1JAORHbEufEO1Eu27zOIlqbgyAcAl7q+/1bip4Z/x1IVES84/yTaM8p0go amMhvgry/mS8vNi1BN2SAZEnb/7xSxbflb70bX9RHLJqKnp5GZe2jexw+wyXlwaM +bclUCrh9e1ltH7IvUrRrQnFJfh+is1fRon9Co9Li0GwoN0x0byrrngU8Ak3Y6D9 D8GjQA4Elm94ST3izJv8iCOLSDBmzsPsXfcCUZfmTfZ5DbUDMbMxRnSo3nQeoKGC 0Lj9FkWcfmLcpGlSXTO+Ww1L7EGq+PT3NtRae1FZPwjddQ1/4V905kyQFLamAA5Y lSpE2wkCgYEAy1OPLQcZt4NQnQzPz2SBJqQN2P5u3vXl+zNVKP8w4eBv0vWuJJF+ hkGNnSxXQrT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3uF9gEiNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0 e+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWb V6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9 MwIDAQAB -----END PUBLIC KEY-----"; // 最大只能214 var data = Rand.NextBytes(214); var buf = RSAHelper.Encrypt(data, pubKey); Assert.NotNull(buf); var rs = RSAHelper.Decrypt(buf, prvKey); Assert.Equal(data.ToBase64(), rs.ToBase64()); }
private void btnRSA_Click(Object sender, EventArgs e) { var buf = GetBytes(); var key = rtPass.Text; if (key.Length < 100) { key = RSAHelper.GenerateKey().First(); rtPass.Text = key; } buf = RSAHelper.Encrypt(buf, key); SetResult(buf); }
private void btnRSA_Click(Object sender, EventArgs e) { var buf = GetBytes(); var key = rtPass.Text; if (key.Length < 100) { key = RSAHelper.GenerateKey().First(); rtPass.Text = key; } buf = RSAHelper.Encrypt(buf, key); rtResult.Text = buf.ToHex() + Environment.NewLine + Environment.NewLine + buf.ToBase64(); }
public void RSAHelperCrossEncryptAndDecrypt() { RSAHelper receiver = new RSAHelper(); RSAHelper sender = new RSAHelper(); sender.SetPeerPublicKey(receiver.MyPublicKey); receiver.SetPeerPublicKey(sender.MyPublicKey); string original = "This is test message"; byte[] encrypted = sender.Encrypt(original); string decrypted = receiver.Decrypt(encrypted); Assert.Equal(original, decrypted); }
private void GenerateAndSendAESKey(byte[] inputData, TcpClient tcpClient) { string guid = System.Guid.NewGuid().ToString(); byte[] clientPublicKey = RSAHelper.Decrypt(inputData, this.RSAKey); AESKey key = AESKey.Generate(); this.AESKeyList.Add(guid, key); MessageBody message = new MessageBody() { Guid = guid, Content = RSAHelper.Encrypt(this.JsonSerialzation.Serialize(key), clientPublicKey), Flag = MessageFlag.SendAESKey }; this.SendMessage(message, tcpClient); }
public (List <byte> CipherBytes, RSAHelper.RSAKey Key, string Clear) Encrypt() { var key = GenerateKey(); string clear = "\0\0\0测试一级棒\0\0\0skfsdlkfklsjfliwu;" + "skjflksjf;s" + "sdfsdklfjsdlfjsl;ufeio" + "sdfjsldjfoieurpjzavna" + "skfjskfjsldfj"; var clearBytes = Encoding.Default.GetBytes(clear); //测试私钥加密 var cipherBytes = RSAHelper.Encrypt(clearBytes, key.PrivateKey); Assert.NotNull(cipherBytes); return(cipherBytes, key, clear); }
public JsonResult GetOTP() { ArrayList arrUserDetails = new ArrayList(); Random generator = new Random(); string OTP = generator.Next(0, 999999).ToString("D6"); var rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, privateKey, publicKey); bool isOTPSent = SendSMS(OTP); //bool isOTPSent = true; if (isOTPSent == true) { arrUserDetails.Add(rsa.Encrypt(OTP)); } else { arrUserDetails.Add("SMS Not Sent"); } return(Json(arrUserDetails)); }
public void RSAHelper_Encrypt_By_Private_Decrypt_Success() { string input = "Hello, this is Shawn, I am learning about RSA by using BigInteger class"; var bytes = Encoding.UTF8.GetBytes(input); var resultBytes = RSAHelper.Encrypt(bytes, _rsaPrivate); string result = Convert.ToBase64String(resultBytes); Debug.WriteLine("Encrypt by private key: "); Debug.WriteLine(result); byte[] decryptBytes = RSAHelper.Decrypt(Convert.FromBase64String(result), _rsaPublic); string resultDecrypted = Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); Debug.WriteLine("Decrypt by public key: "); Debug.WriteLine(resultDecrypted); Assert.AreEqual(input, resultDecrypted); }
public string Get(string str) { //2048 公钥 string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoKefXtIqc293nDjFpCkjUuyEL3bc15lVlocJJVdQovRLyTKXpzcD029U0MeVAd8Hq9huQtxWspV+/KSoXjN5BGc7XS/QZItG1irxtivIHlFmzra7Fk94r10F4/hR/mdq+H/WAIJJjGpw1Garncvh8AEJXJ2JBbiAyM0zNSqDNidTFFPuLoGQQ+EGsbCESMFy0mGeSBd8/b6ADwLiR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"; var rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, privateKey, publicKey, publicKeys, "asda"); // string str = "博客园 http://www.cnblogs.com/"; Console.WriteLine("原始字符串:" + str); //加密 string enStr = rsa.Encrypt(str); string enStrs = rsa.AppEncrypt(str); Console.WriteLine("加密字符串:" + enStr); //解密 string deStr = rsa.Decrypt(enStr); Console.WriteLine("解密字符串:" + deStr); //私钥签名 string signStr = rsa.Sign(str); Console.WriteLine("字符串签名:" + signStr); //公钥验证签名 bool signVerify = rsa.Verify(str, signStr); Console.WriteLine("验证签名:" + signVerify); return(deStr); // return RSAHelper.StringToBase64("abcsdeasdweixiao"); }
public async Task <IActionResult> SaveTest(string orderRequest) { var viettelPayApi = _configuration.GetValue <bool>("RequestPaymentLink:IsLive") ? _configuration.GetValue <string>("RequestPaymentLink:Live") : _configuration.GetValue <string>("RequestPaymentLink:Test"); var cmd = _configuration.GetValue <string>("RequestPaymentParam:cmdCheckOrderRequest"); var rsaPublicKey = _configuration.GetValue <string>("RSAKey:public"); var rsaPrivateKey = _configuration.GetValue <string>("RSAKey:private"); var rsaPublicKeyVTP = _configuration.GetValue <string>("RSAKey:VTPpublic"); var rsa = new RSAHelper(RSAType.RSA, Encoding.UTF8, "", rsaPublicKeyVTP); var passwordEncrypt = rsa.Encrypt(_configuration.GetValue <string>("RequestPaymentParam:password")); SoapDataCheckOrderRequest request = new SoapDataCheckOrderRequest() { username = _configuration.GetValue <string>("RequestPaymentParam:username"), password = passwordEncrypt, serviceCode = _configuration.GetValue <string>("RequestPaymentParam:serviceCode"), orderId = orderRequest }; var response = await _viettelPay.CheckOrderRequest(viettelPayApi, cmd, rsaPublicKey, rsaPrivateKey, rsaPublicKeyVTP, request); return(new OkObjectResult(response)); }