散列法
1.Encoding.UTF8.GetBytes将一个字符串变成字节数组
2.Encoding.UTF8.GetString将一个字节数组转变成字符串
3.Convert.ToBase64String将一个字节数组以Base64编码的方式展现成字符串,本质上是字节数组
4.FromBase64String将一个Base64编码的字符串转成字节数组,本质上是字节数组
5.MD5.Create().ComputeHash(s),散列加密
6.SHA256.Create().ComputeHash(s),散列加密
7.MD5和SHA1不安全,尽量使用SHA256
对称加密
1.使用AES类
2.使用16字节,24字节,32字节的秘钥和初始化向量
byte[] key = Encoding.UTF8.GetBytes("Hello World!6789");
byte[] vi = Encoding.UTF8.GetBytes("Conversition1234");
byte[] data = { 1, 2, 3, 4, 5 };
using (SymmetricAlgorithm algorithm = Aes.Create())
{
using (ICryptoTransform transform = algorithm.CreateEncryptor(key,vi))
{
using (Stream f = File.Create("encryted.bin"))
{
using (Stream c = new CryptoStream(f, transform, CryptoStreamMode.Write))
{
c.Write(data, 0, data.Length);
}
}
}
}
3.使用RandomNumberGenerator获取随机秘钥和初始化向量
byte[] key = new byte[16];
RandomNumberGenerator rand = RandomNumberGenerator.Create();
rand.GetBytes(key);
4.使用MemoryStream
using (SymmetricAlgorithm algorithm = Aes.Create())
{
using (ICryptoTransform transform = algorithm.CreateEncryptor(key, vi))
{
MemoryStream stream = new MemoryStream();
using (Stream c = new CryptoStream(stream, transform, CryptoStreamMode.Write))
{
c.Write(data, 0, data.Length);
}
}
}
公钥加密和签名
1.系统自动指定公私钥
byte[] data = { 1, 2, 3, 4, 5 };
using (var rsa = new RSACryptoServiceProvider())
{
byte[] en = rsa.Encrypt(data, true);
byte[] de = rsa.Decrypt(en, true);
}
2.将公私钥保存到文件
using (var rsa = new RSACryptoServiceProvider())
{
File.WriteAllText("PublicKeyOnly.xml", rsa.ToXmlString(false));
File.WriteAllText("PublicPrivate.xml", rsa.ToXmlString(true));
string publicOnly = Convert.ToBase64String(rsa.ExportCspBlob(false));
string publicPrivate = Convert.ToBase64String(rsa.ExportCspBlob(true));
Console.WriteLine(publicOnly);
Console.WriteLine(publicPrivate);
}
3.数字签名要先散列,在用私钥加密