这些程序在密文接口中可能用到,常规的数据接口应该基本不用。
【计算MD5】
using System;
using System.Text;
using System.Security.Cryptography;
string MD5Encrypt32(string text)
{
string ciphertext = "";
MD5 md5 = MD5.Create();
byte[] h = md5.ComputeHash(Encoding.UTF8.GetBytes(text));
for (int i = 0; i < h.Length; i++)
{
ciphertext = ciphertext + h[i].ToString("x");
//ciphertext = ciphertext + h[i].ToString("x2");
}
return ciphertext;
}
如 MD5Encrypt32("1") 的值为 "c4ca4238a0b92382dcc509a6f75849b"。
最终是以小写字母输出,可以把字符串格式化参数更改为大写 “X” 以输出大写字母,使用时需注意字符编码集;
格外注意: x 指不补全的 16 进制数(如:A),x2 指补全的 16 进制数(如:0A),可能开源端更多采用补全的方式,而闭源端大多采用不补全的方式。(腾讯接口、拼多多接口踩坑记)
【计算SHA1】
private string SHA1(string str)
{
byte[] strRes = Encoding.Default.GetBytes(str);
HashAlgorithm iSha = new SHA1CryptoServiceProvider();
strRes = iSha.ComputeHash(strRes);
StringBuilder enText = new StringBuilder();
foreach (byte iByte in strRes)
{
enText.AppendFormat("{0:x2}", iByte);
}
return enText.ToString();
}
【转换为base64】
using System;
using System.Text;
string EncodeBase64(string code_type, string code)
{
string encode = "";
byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
try
{
encode = Convert.ToBase64String(bytes);
}
catch
{
encode = code;
}
return encode;
}
这个方法是可以指定编码集的,如 EncodeBase64("utf-8", "abc123");
相关环境:.NET Framework 4.0