public void Encrypt_Decrypt_Test() { string source = "admin"; RsaHelper rsa = new RsaHelper(); //byte[] byte[] sourceBytes = source.ToBytes(); byte[] enBytes = rsa.Encrypt(sourceBytes); rsa.Decrypt(enBytes).ShouldBe(sourceBytes); //string string enstr = rsa.Encrypt(source); rsa.Decrypt(enstr).ShouldBe(source); }
/// <summary> /// 解密接收到的加密数据并验证完整性,如果验证通过返回明文 /// </summary> /// <param name="data">接收到的加密数据</param> /// <returns>解密并验证成功后,返回明文</returns> public string DecryptAndVerifyData(string data) { data.CheckNotNullOrEmpty("data"); string separator = GetSeparator(); if (!data.Contains(separator)) { return(data); } string[] separators = { separator }; //0为AES密钥密文,1为 正文+摘要 的密文 string[] datas = data.Split(separators, StringSplitOptions.None); //用接收端私钥RSA解密获取AES密钥 byte[] keyBytes = RsaHelper.Decrypt(Convert.FromBase64String(datas[0]), _ownPrivateKey); string key = keyBytes.ToString2(); //AES解密获取 正文+摘要 的明文 data = new AesHelper(key, true).Decrypt(datas[1]); //0为正文明文,1为摘要 datas = data.Split(separators, StringSplitOptions.None); data = datas[0]; if (RsaHelper.VerifyData(data, datas[1], _facePublicKey)) { return(data); } throw new CryptographicException("加密数据在进行解密时校验失败"); }
public IHttpActionResult Login([Required] AccountLoginDto dto) { logger.InfoFormat("{0:D3}.{1}", ++numberIndex, MethodBase.GetCurrentMethod().Name); var result = new CommonResponse(); var user = userApplicationService.GetByLoginname(dto.Loginname); if (user == null) { result.Code = (int)AccountLoginErrorCode.LoginnameNotExist; result.Description = AccountLoginErrorCode.LoginnameNotExist.Description(); return(Ok(result)); } var password = RsaHelper.Decrypt(dto.Password, RsaKeyManager.XmlPrivateKey); if (!user.Password.Equals(password)) { result.Code = (int)AccountLoginErrorCode.LoginnameAndPasswordNotMatch; result.Description = AccountLoginErrorCode.LoginnameAndPasswordNotMatch.Description(); return(Ok(result)); } else if (user.Status == (int)UserStatus.Disabled) { result.Code = (int)AccountLoginErrorCode.AccountIsDisabled; result.Description = AccountLoginErrorCode.AccountIsDisabled.Description(); return(Ok(result)); } result.Code = (int)CommonErrorCode.Success; result.Description = CommonErrorCode.Success.Description(); result.Data = user; return(Ok(result)); }
public void Test_RsaHelper_Decrypt_CertNotFound() { byte[] bb = Guid.NewGuid().ToByteArray(); string error = ExceptionHelper.ExecuteActionReturnErrorMessage(() => { RsaHelper.Decrypt(bb, "abc"); }); Assert.AreEqual($"加密证书abc不存在。", error); }
public void TestRsaEncryptAndDecrypt() { string _data = "I am union guy." , _dataEncrypted = "" , _dataDecrypted = ""; RsaKeyPair _rsaKeyPair = new RsaKeyPair(); RsaKeyFormat _rsaKeyFormat = RsaKeyFormat.PEM; _dataEncrypted = RsaHelper.Encrypt(_rsaKeyFormat, _rsaKeyPair.PublicKey_PEM, _data); _dataDecrypted = RsaHelper.Decrypt(_rsaKeyFormat, _rsaKeyPair.PrivateKey_PEM, _dataEncrypted); Assert.AreEqual(_data, _dataDecrypted, string.Format("Data = {0}, DataEncrypted = {1}, DataDecrypted = {2}", _data, _dataEncrypted, _dataDecrypted)); }
public void Test_RsaHelper_Encrypt_Decrypt() { string s = @"已评估过类似方案,上海和融25版本做过类似改动,但需求有差异。 和融做此需求时改动量比较大,且与252版本跨系列了,参考价值降低。"; byte[] bb = Encoding.UTF8.GetBytes(s); byte[] b1 = RsaHelper.Encrypt(bb, s_certName); byte[] b2 = RsaHelper.Decrypt(b1, s_certName); string s2 = Encoding.UTF8.GetString(b2); Assert.AreEqual(s, s2); }
static void Main(string[] args) { //私钥 var privateKey = @"<RSAKeyValue><Modulus>2l3VY7cAyC6V/nI/5/ysy/vays9y4EumCRDF6+0u7px5Er10n05JAaWJB4f1dPzzSjZfLFENj8cnYHkR0+3EWOZzhegWgvL9ADDuTX0mqFTUnZnEzfPOAy65mpFf9VDkPu62jjA0gsrcjWxlvZTgwnglIEjefuPnM3pCu1pJMFc=</Modulus><Exponent>AQAB</Exponent><P>/gNvoe30rY5/T6YChUyj+eV5kIjfwMZoYPDrxsG9WVk5qYXCXA19dOF13qlfEdUflIz0aFI+jU0Tc+qNqKFOTw==</P><Q>3BMHQa/ulOZ2OQy4r7waGPlyCdQWVX8CKdu7oEeDY4SKXBoX7bYD5/mKrDbwKxZ7AIB4woTyZKJYfSejdgvDeQ==</Q><DP>mVxZudqBL4gpNV11iCWNmwMBMlJxRWKFAoJy172BJMDKH5+yiQFcDYVSNOztiUazmmy/43xEZ+txIzsp6/X34Q==</DP><DQ>JVgxRgtFsAy/iQTInkGMKCrEGDjeJVntEw9Pcm5QNGX8WI6w+syFMyscRgb4kEc7TiV+2HtY6ozF+U7tpQ1v+Q==</DQ><InverseQ>8XZBDYGcQQ3z84Da0o7+cUWIieCA+GFDB7hpH8PW8UGbOmFrLxkC+WKkZEjlvLR5EDggkKfSoQ1v0oWlN7N/bQ==</InverseQ><D> BR3lGH9lnaCMfo2Ey9XS4rtrEWIyXz5xNzh/usXbBK0BSpwf4HUVfDFkeEW0+GHOUvMv4GT3JrhURuFvYSzqyIi59tZ0USGc08saDOpzBlXiAPgVdyxyEp7nYtH00tRpISDXGa4RAHyTErmyG7d56iOwdCUEUiI/sRruL+myVdE=</D></RSAKeyValue>"; //公钥 var publicKey = @"<RSAKeyValue><Modulus>sbZLsASOp6LzeiCqD9wFHu70J0/tzamMtEiahk3+LubFrio+o8KbwUn9ew6ARgFz1X80I7Zd8Tcpp//O3O6sw86JZQR9XVwHYOaJcKdLQFFRFgyrgoGhRo7Kp602MU7zqk39SdPJiEH9054JMNVrjQXQA1IgbE5YKTvZPn3yC+M=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; Console.WriteLine("请输入要加密的字符串:"); var sourceText = Console.ReadLine(); // var cipherText = RsaHelper.Encrypt(sourceText, privateKey); var cipherText = "Ss5X3eGlimQ5ZIPSYo1wNQQ2gUIkLnM+OrFcpf0+Pa+f7xshGdTQtjNPWvKuu6bkteaBuHEPVjHe9hKi5/7RTS2+9UCqxJrcw4xX3TNDaDqa9DjRhOqdL72Scgc+iASCwC7YEBtDEm2YieIOVCur5UItUB4IwFNIsdCSO/v4Las="; cipherText = Encoding.ASCII.GetString(Convert.FromBase64String(cipherText)); Console.WriteLine("加密后的字符串是:{0}", cipherText); Console.WriteLine(Environment.NewLine); Console.WriteLine("解密之后的字符串是:{0}", RsaHelper.Decrypt(cipherText, publicKey)); Console.ReadKey(); }
/// <summary> /// 通过加密密文获取原文 /// </summary> /// <param name="cipper">格式为md5(username){密文}{今天日期}</param> /// <param name="username"></param> /// <param name="cipperServices">获取密钥</param> /// <returns></returns> public static string FromCipperToString(this string cipper, string username, ICipperServices cipperServices) { try { string md5Str = username.ToMd5(); var rsa = new RsaHelper(RSAType.RSA2, Encoding.UTF8, cipperServices.PrivateKey, cipperServices.PublicKey); var decryptStr = rsa.Decrypt(cipper); if (decryptStr == null || decryptStr.Length <= md5Str.Length || DateTime.Now.ToString("yyyyMMdd") != decryptStr.Substring(0, 8) || decryptStr.Substring(decryptStr.Length - md5Str.Length, md5Str.Length) != md5Str) { return(null); } return(decryptStr.Substring(8, decryptStr.Length - 8 - md5Str.Length)); } catch (Exception) { throw new ActionStatusMessageException(ActionStatusMessage.Account.Auth.Invalid.CipperInvalid); } }
/// <summary> /// Rsa2 解密 /// </summary> /// <param name="value">明文</param> /// <param name="privateKey">私钥</param> /// <param name="type">加密类型</param> /// <returns></returns> private static string RsaDecrypt(string value, string privateKey, RSAType type) { var rsa = new RsaHelper(type, Encoding.UTF8, privateKey: privateKey); return(rsa.Decrypt(value)); }