我想将 RSA 加密应用于我的项目,但遇到了一些麻烦:
- 首先,我从 http://www.ohdave.com/rsa/下载了 JavaScripts 库,并添加了对我的项目的引用;
其次,我已经定义了 RSA 对象和代码来初始化它:
internal RSACryptoServiceProvider Rsa { get { if (HttpContext.Cache["Rsa"] != null) { RSACryptoServiceProvider encryptKeys = (RSACryptoServiceProvider)HttpContext.Cache["Rsa"]; return encryptKeys; } else { return new RSACryptoServiceProvider(1024); } } set { HttpContext.Cache.Remove("Rsa"); HttpContext.Cache.Insert("Rsa", value); } } public ActionResult SignUp() { this.Rsa = Security.GetRsa(); RSAParameters param= this.Rsa.ExportParameters(true); //this will bind to view TempData["exponent"] = Util.BytesToHexString(param.Exponent); TempData["key"] = Util.BytesToHexString(param.Modulus);
UserInfo user = new UserInfo(); user.Birthday = DateTime.Now.Date; return View(user); } private RSACryptoServiceProvider GetRsa() { RSACryptoServiceProvider Rsa = new RSACryptoServiceProvider(1024); return Rsa; }
3.然后,在 JavaScript 端,我有代码,它加密用户输入的密码并绑定它控制:
var hash = document.getElementById("Pwd").value;
var exponent = document.getElementById("exponent").innerHTML;
var rsa_n = document.getElementById("key").innerHTML;
setMaxDigits(131);
var key = new RSAKeyPair(exponent, "", rsa_n);
hash = encryptedString(key, "111");
document.getElementById("Pwd").value = hash;
document.getElementById("Pwd2").value = hash;
document.getElementById("error").innerHTML = "";
document.getElementById("submit").click();
4.当用户单击提交时,我的 C# 代码获取加密的密码字符串并尝试解密它但失败并出现异常:错误数据:
[HttpPost]
public ActionResult SignUp(UserInfo user)
{
user.UserId = user.UserId.ToLower(); //ignore case
user.UserGUID = Guid.NewGuid();
user.CreatedDate = DateTime.Now;
user.IsEnabled = false;
user.Pwd = Convert.ToBase64String(Rsa.Decrypt(Util.HexStringToBytes(user.Pwd), false));//Exception:Rsa.Decrypt throw bad data exception
谁知道如何解决?先感谢您。