.Net加密算法主要分为对称算法、非对称算法、哈希算法、随机算法。每种算法都有自己的使用场景,例如 保护隐私(防止查看)、保护完整性(防止更改)、数字签名、生成秘钥、秘钥交换、生成随机数等。
按照不同场景,微软建议使用的算法如下
- 数据隐私Aes
- 数据完整性HMACSHA256、HMACSHA512
- 数字签名ECDsa、RSA
- 密钥交换ECDiffieHellman、RSA
- 随机数生成RandomNumberGenerator
- 从密码生成密钥Rfc2898DeriveBytes
一、私钥加密
私钥加密也称之为对称加密,因为使用的是相同的秘钥来加密、解密。对称加密是对流执行的,所以可以对大数据进行加密。对称加密速度比公钥加密速度快。对称算法要求创建秘钥和初始化向量(IV),秘钥必须保密、IV可以公开但应定期更改。常见的私钥加密有DES、AES、HMACSHA256、HMACSHA384、HMACSHA512等。
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
#region 秘钥长度
//16位密钥 = 128位
//24位密钥 = 192位
//32位密钥 = 256位
Aes aes = Aes.Create();
KeySizes[] ks = aes.LegalKeySizes;
foreach (KeySizes k in ks)
{
Console.WriteLine("tLegal min key size = " + k.MinSize);
Console.WriteLine("tLegal max key size = " + k.MaxSize);
Console.WriteLine("tLegal skipsize = " + k.SkipSize);
}
//This sample produces the folloing output:
// Legal min key size = 128
// Legal max key size = 256
// Legal skipsize = 64
#endregion
string original = "Here is some data to encrypt!";
// Create a ne instance of the Aes
// class. This generates a ne key and initialization
// vector (IV).
//using (Aes myAes = Aes.Create())
//{
// var strkey = Convert.ToBase64String(myAes.Key);
// var striv = Convert.ToBase64String(myAes.IV);
/