最近在工作中有幸接触到一些加密解密和签名的工作,记录如下:
首先加密算法分为对称加密和非对称加密。本次开发接触到对称加密算法AES,加密速度快,一般对大量数据加密使用该算法
using var aes = Aes.Create();
using var ct = aes.CreateEncryptor();
byte[] byt = Encoding.UTF8.GetBytes(body);
using var ms = new MemoryStream();
using (var cs = new CryptoStream(ms, ct, CryptoStreamMode.Write))
{
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
}
var encryptedBody = Convert.ToBase64String(ms.ToArray());
return encryptedBody;
还有非对称加密算法RSA,加密速度慢,一般配合对称加密使用,用于加密对称加密的密钥,有很多版本,本次使用SHA256算法
? ? ? ? ? ? RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
? ? ? ? ? ? rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(PLATFORM_PUBLIC_KEY), out _);
? ? ? ? ? ? var temp = rsa.Encrypt(Encoding.UTF8.GetBytes(appSecret), true);
网传 Java?和dotnet 的 RSA密钥需要转换,需要引入OC.Core.Crypto 包
#region 转换处理
/// <summary>
///
/// </summary>
/// <param name="privateKey"></param>
/// <returns></returns>
public static string RSAPrivateKeyJava2DotNet(string privateKey)
{
RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey));
return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()),
Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned()));
}
/// <summary>
/// 加密的方法
/// </summary>
/// <param name="contentForSign"></param>
/// <param name="privateKey"></param>
/// <returns></returns>
public static string Sign(string contentForSign, string privateKey)
{
//转换成适用于.Net的秘钥
var netKey = RSAPrivateKeyJava2DotNet(privateKey);
var rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(netKey);
//创建一个空对象
var rsaClear = new RSACryptoServiceProvider();
var paras = rsa.ExportParameters(true);
rsaClear.ImportParameters(paras);
//签名返回
using (var sha256 = new SHA256CryptoServiceProvider())
{
var signData = rsa.SignData(Encoding.UTF8.GetBytes(contentForSign), sha256);
return BytesToHex(signData);
}
}
public static string BytesToHex(byte[] data)
{
StringBuilder sbRet = new StringBuilder(data.Length * 2);
for (int i = 0; i < data.Length; i++)
{
sbRet.Append(Convert.ToString(data[i], 16).PadLeft(2, '0'));
}
return sbRet.ToString();
}
#endregion