文献种类:专题技术总结文献;
开发工具与关键技术:VisualStudio2017、C#
作者:高俊杰 ;年级:1703;撰写时间:2019年2月14日
加密代码如下:
/// <summary>
/// DES数据解密
/// </summary>
/// <param name="targetValue"></param>
/// <param name="key"></param>
/// <returns></returns>
public ActionResult Decrypt(string targetValue, string key)
{
// 定义DES加密对象
try
{
var des = new DESCryptoServiceProvider();
int len = targetValue.Length / 2;
var inputByteArray = new byte[len];
int x, i;
for (x = 0; x < len; x++)
{
i = Convert.ToInt32(targetValue.Substring(x * 2, 2), 16);
inputByteArray[x] = (byte)i;
}
// 通过两次哈希密码设置对称算法的初始化向量
#pragma warning disable CS0618 // 类型或成员已过时
des.Key = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8), "sha1").Substring(0, 8));
#pragma warning restore CS0618 // 类型或成员已过时
// 通过两次哈希密码设置算法的机密密钥
#pragma warning disable CS0618 // 类型或成员已过时
des.IV = Encoding.ASCII.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(FormsAuthentication.HashPasswordForStoringInConfigFile(key, "md5").Substring(0, 8),"md5").Substring(0, 8));
#pragma warning restore CS0618 // 类型或成员已过时
// 定义内存流
var ms = new MemoryStream();
// 定义加密流
var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
var ss = Encoding.Default.GetString(ms.ToArray());
return Json(ss, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json("failed", JsonRequestBehavior.AllowGet);
}
}
解密效果如下:
页面代码如下:
<div>
<label>DES数据解密</label>
<div>
<labe>DES密钥:</label>
<div>
<input id="DESEMMY">
</div>
</div>
<div>
<label>解密前:</label>
<div>
<input id="DESEMQ">
</div>
</div>
<div>
<label>解密后:</label>
<div>
<input id="DESEMH">
</div>
</div>
<button id="DESEMQR" >确认</button>
</div>
JavaScript代码如下:
<script>
$("#DESEMQR").click(function () {
var targetValue = $("#DESEMQ").val().trim();
var key = $("#DESEMMY").val().trim();
if (targetValue != "" && key != "") {
$.post("/MD5JM/Decrypt", {
targetValue, targetValue,
key: key
}
, function (data) {
if (data == "failed") {
layer.alert("请输入正确的加密字段和密钥!", { icon: 2, title: "提示", offset: "100px" });
} else {
$("#DESEMH").val(data);
if (targetValue == "") {
$("#DESEMH").val("");
}
}
});
} else {
layer.alert("请填写完整!", { icon: 0, title: "提示", offset: "100px" });
}
});</script>