流程:
第一步:返回publicKey前端,用来对password等敏感字段的加密。
第二步:前端进行password敏感字段的加密。
第三步:post数据给后端。
第四步:用privateKey进行解密。
一、相关JS包和引用BIN文件,下载链接:
https://download.csdn.net/download/u012949335/20389382
二、前端如下:
<div class="from">
<div class="from-group">
<input type="text" class="inputtext width280" id="UserId" name="UserId" placeholder="请输入用户名" />
</div>
<div class="from-group">
<input type="password" class="inputtext width280" id="Password" name="Password" placeholder="请输入密码" />
</div>
<div class="from-group">
<input type="text" class="inputtext width160" id="VeriCode" name="VeriCode" placeholder="请输入验证码" />
<img id="imgVerifi" title="单击换一张验证码" class="inputimage" src="verificationcode" onclick="changecode()" />
</div>
<div class="from-group">
<button id="btnlogin" class="btn" onclick="loginform(); return false">登 录</button>
</div>
<input id="pubkey" type="hidden" value='@ViewBag.pubkey' />
</div>
<script type="text/javascript">
function loginform() {
var info = new Object();
info.UserId = $("#UserId").val();
var EncryptPwd = $("#Password").val();
var rsa = new JSEncrypt();
var pubkey = $("#pubkey").val();
rsa.setPublicKey(pubkey);
var rsa_p = rsa.encrypt(EncryptPwd);
info.Password = rsa_p;
info.VeriCode = $("#VeriCode").val();
var jsonObject = JSON.stringify(info);
$.ajax({
type: 'post',
url: "Login",
dataType: "json", //返回json格式的数据
data: { 'json': jsonObject },
cache: false,
success: function (data) {
if (data.jg == "1") {
}
else {
}
},
error: function (e) {
var msg = responseTextTitle(e.responseText);
$.messager.alert("提示", msg, "error");
}
});
}
</script>
三、后端如下:
[AllowAnonymous]
public ActionResult Login()
{
List<string> keys = Common.Common.CreateKeyPair();
ViewBag.pubkey = keys[0];
Session["publickey"] = keys[0];
Session["privatekey"] = keys[1];
return View();
}
/// <summary>
/// 登陆
/// </summary>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public ActionResult Login(string json)
{
LoginModel model = new LoginModel();
model = JsonUtility.Json2Info<LoginModel>(json);
Dictionary<String, Object> jsonMap = new Dictionary<String, Object>();
string rejson = string.Empty;
var privatekey = Session["privatekey"].ToString();
var Password = Common.Common.Decrypt(privatekey, model.Password);
model.Password = Password;
model.UserId = model.UserId.Trim();
string msg = "";
BLL.sys_user dal = new BLL.sys_user();
if (dal.DoLogin(model, out msg))
{
jsonMap.Add("jg", "1");
rejson = JsonUtility.Info2Json(jsonMap);
return Content(rejson);
}
else
{
jsonMap.Add("jg", "0");
jsonMap.Add("msg", msg);
rejson = JsonUtility.Info2Json(jsonMap);
return Content(rejson);
}
}
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
namespace YidiKy.Common
{
public class Common{
#region 公钥和私钥加解密
/// <summary>
/// 随机获取公钥和私钥的字符
/// </summary>
/// <param name="strength">长度</param>
/// <returns></returns>
public static List<string> CreateKeyPair(int strength = 1024)
{
RsaKeyPairGenerator r = new RsaKeyPairGenerator();
r.Init(new KeyGenerationParameters(new SecureRandom(), strength));
AsymmetricCipherKeyPair keys = r.GenerateKeyPair();
TextWriter privateTextWriter = new StringWriter();
PemWriter privatePemWriter = new PemWriter(privateTextWriter);
privatePemWriter.WriteObject(keys.Private);
privatePemWriter.Writer.Flush();
TextWriter publicTextWriter = new StringWriter();
PemWriter publicPemWriter = new PemWriter(publicTextWriter);
publicPemWriter.WriteObject(keys.Public);
publicPemWriter.Writer.Flush();
List<string> revalue = new List<string>();
revalue.Add(publicTextWriter.ToString());
revalue.Add(privateTextWriter.ToString());
return revalue;
}
/// <summary>
/// RSA加密 将公钥导入到RSA对象中,准备加密
/// </summary>
/// <param name="PublicKey">公钥</param>
/// <param name="encryptstring">待加密的字符串</param>
public static string RSAEncrypt(string PublicKey, string encryptstring)
{
using (TextReader reader = new StringReader(PublicKey))
{
dynamic key = new PemReader(reader).ReadObject();
var rsaDecrypt = new Pkcs1Encoding(new RsaEngine());
if (key is AsymmetricKeyParameter)
{
key = (AsymmetricKeyParameter)key;
}
else if (key is AsymmetricCipherKeyPair)
{
key = ((AsymmetricCipherKeyPair)key).Private;
}
rsaDecrypt.Init(true, key); //这里加密是true;解密是false
byte[] DataToEncrypt = Encoding.UTF8.GetBytes(encryptstring);
byte[] outBytes = rsaDecrypt.ProcessBlock(DataToEncrypt, 0, DataToEncrypt.Length);//加密
string strBase64 = Convert.ToBase64String(outBytes);
return strBase64;
}
}
/// <summary>
/// RSA加密 将私钥导入到RSA对象中,准备解密
/// </summary>
/// <param name="privateKey">私钥</param>
/// <param name="decryptstring">待解密的字符串</param>
/// <returns></returns>
public static string Decrypt(string privateKey, string decryptstring)
{
using (TextReader reader = new StringReader(privateKey))
{
dynamic key = new PemReader(reader).ReadObject();
var rsaDecrypt = new Pkcs1Encoding(new RsaEngine());
if (key is AsymmetricKeyParameter)
{
key = (AsymmetricKeyParameter)key;
}
else if (key is AsymmetricCipherKeyPair)
{
key = ((AsymmetricCipherKeyPair)key).Private;
}
rsaDecrypt.Init(false, key); //这里加密是true;解密是false
byte[] entData = Convert.FromBase64String(decryptstring);
entData = rsaDecrypt.ProcessBlock(entData, 0, entData.Length);
return Encoding.UTF8.GetString(entData);
}
}
#endregion
}
}