WebService接口数据传输加密
Posted zisai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebService接口数据传输加密相关的知识,希望对你有一定的参考价值。
1.加密流程
客服端--->加密文本------>服务端接收到加密文本,通过固定加密密文进行解密,然后做相应处理------------>返回结果
2.固定密文创建
密文创建有很多种方式,在这篇文章使用的是从我出生那天到现在毫秒数,当然也可以使用其他。。。
3.实现
首先创建一个 类:SecretServer
public class SecretServer
/// <summary>
/// 加密
/// </summary>
/// <param name="encryptStr"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string TextEncrypt(string encryptStr, string key)
var bt = Encoding.Default.GetBytes(encryptStr);
var base64Str = Convert.ToBase64String(bt);
key = EncryptToMD5string(key);
byte[] keyArray = Encoding.UTF8.GetBytes(key);
byte[] toEncryptArray = Encoding.UTF8.GetBytes(base64Str);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.ECB;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
/// <summary>
/// 解密
/// </summary>
/// <param name="decryptStr"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string TextDecrypt(string decryptStr, string key)
key = EncryptToMD5string(key);
byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
byte[] toEncryptArray = Convert.FromBase64String(decryptStr);
RijndaelManaged rDel = new RijndaelManaged();
rDel.Key = keyArray;
rDel.Mode = CipherMode.ECB;
rDel.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = rDel.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
var td = UTF8Encoding.UTF8.GetString(resultArray);
var str = Convert.FromBase64String(td);
var sd = Encoding.Default.GetString(str);
return sd;
public static byte[] EncryptToMD5(string str)
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] str1 = System.Text.Encoding.UTF8.GetBytes(str);
byte[] str2 = md5.ComputeHash(str1, 0, str1.Length);
md5.Clear();
(md5 as IDisposable).Dispose();
return str2;
public static string EncryptToMD5string(string str)
byte[] bytHash = EncryptToMD5(str);
string sTemp = "";
for (int i = 0; i < bytHash.Length; i++)
sTemp += bytHash[i].ToString("X").PadLeft(2, ‘0‘);
return sTemp.ToLower();
以上是关于WebService接口数据传输加密的主要内容,如果未能解决你的问题,请参考以下文章