更新记录
转载请注明出处:
2022年10月1日 发布。
2022年9月29日 从笔记迁移到博客。
常用加密算法
Encryption and decryption(加密和解密)
说明
使用Key进行加密和解密
Key可以是对称的(symmetric)、也可以是非对称的(asymmetric)
一般情况下,对称加密的效率高于非对称加密
一般情况下,非对称加密的安全性高于对称加密
现实情况下,一般使用非对称加密Key,使用对称加密数据,比如:SSL
Hashes(哈希加密)
常用Hash加密算法
Signatures(签名)
Authentication(身份认证)
Authorization(授权)
具体加密操作
命名空间
System
System.Reflection
System.Reflection.Emit
实例
简单加密解密
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleApp8
{
/// <summary>
/// 加密解密工具类
/// </summary>
class Protector
{
// salt size must be at least 8 bytes, we will use 16 bytes
private static readonly byte[] salt =
Encoding.Unicode.GetBytes("7BANANAS");
// iterations must be at least 1000, we will use 2000
private static readonly int iterations = 2000;
public static string Encrypt(string plainText, string password)
{
byte[] encryptedBytes;
byte[] plainBytes = Encoding.Unicode
.GetBytes(plainText);
var aes = Aes.Create();
var pbkdf2 = new Rfc2898DeriveBytes(
password, salt, iterations);
aes.Key = pbkdf2.GetBytes(32); // set a 256-bit key
aes.IV = pbkdf2.GetBytes(16); // set a 128-bit IV
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(
ms, aes.CreateEncryptor(),
CryptoStreamMode.Write))
{
cs.Write(plainBytes, 0, plainBytes.Length);
}
encryptedBytes = ms.ToArray();
}
return Convert.ToBase64String(encryptedBytes);
}
public static string Decrypt(string cryptoText, string password)
{
byte[] plainBytes;
byte[] cryptoBytes = Convert.FromBase64String(cryptoText);
var aes = Aes.Create();
var pbkdf2 = new Rfc2898DeriveBytes(
password, salt, iterations);
aes.Key = pbkdf2.GetBytes(32);
aes.IV = pbkdf2.GetBytes(16);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(
ms, aes.CreateDecryptor(),
CryptoStreamMode.Write))
{
cs.Write(cryptoBytes, 0, cryptoBytes.Length);
}
plainBytes = ms.ToArray();
}
return Encoding.Unicode.GetString(plainBytes);
}
}
class Program
{
static void Main(string[] args)
{
try{
string panda = "www.panda666.com";
string password = "Panda";
string result = Protector.Encrypt(panda, password);
Console.WriteLine(result);
//B/11aH3HRVvrJjX6NUepZtuzeLG1x6gcvjWHJvI8ZHQNs6WeyplqMV77ADig04HJ
string origin = Protector.Decrypt(result, password);
Console.WriteLine(origin);
//www.panda666.com
}
catch (CryptographicException ex)
{
Console.WriteLine(ex.Message);
}
//wait
Console.ReadKey();
}
}
}
SymmetricAlgorithm
说明
用于处理加密的字符
所在命名空间
using System.Security.Cryptography;
标签:Decryption,aes,加密,string,Encryption,System,var,using,NET
From: https://www.cnblogs.com/cqpanda/p/16740986.html