網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
散列運(yùn)算
mscorlib.dll下的System.Security.Cryptography下:
- 抽象類(lèi)HashAlgorithm
- 抽象類(lèi)MD5
- MD5CryptoServiceProvider
- SHA1
- SHA1CryptoServiceProvider密封類(lèi):調(diào)用Windows Crypto API
- SHA1Managed普通類(lèi):用托管代碼寫(xiě)的
- SHA256
- SHA256CryptoServiceProvider
- SHA256Managed
- SHA384
- SHA512
- 抽象類(lèi)MD5
對(duì)字節(jié)數(shù)組或流散列運(yùn)算
class Program
{
static void Main(string[] args)
{
string str = "Hello World";
HashAlgorithm hashAlgorithm = HashAlgorithm.Create(HashAlgorithmType.SHA1);
byte[] data = Encoding.Default.GetBytes(str);
byte[] digest = hashAlgorithm.ComputeHash(data);
foreach (byte b in digest)
{
Console.Write("{0:X}",b);
}
Console.ReadKey();
}
}
public class HashAlgorithmType
{
public const string SHA1 = "SHA1";
public const string SHA256 = "SHA256";
public const string SHA384 = "SHA384";
public const string SHA512 = "SHA512";
public const string MD5 = "MD5";
}
密匙散列運(yùn)算
string key = "secret key";
byte[] data = Encoding.Default.GetBytes(key);
KeyedHashAlgorithm kha = new HMACSHA1();
byte[] digest = kha.ComputeHash(data);
foreach (byte b in digest)
{
Console.Write("{0:x}",b);
}
對(duì)稱(chēng)加密和解密
- SymmetricAlgorithm
- DES
- DESCryptoServiceProvider
- TripleDES
- TripleDESCryptoServiceProvider
- Rijndael
- RijindaelManaged
- RC2
- RC2CryptoServiceProvider
- DES
IV:Initialization vector初始化向量:
- 為了解決加密字符串加密后仍然有重復(fù)部分,引入IV,加密字符串即使有重復(fù),也會(huì)被打亂。
- IV值可以隨意指定,但長(zhǎng)度固定,通常為64位byte類(lèi)型
- 密匙長(zhǎng)度也是固定的,通常為128位或196位byte類(lèi)型
使用Encoding類(lèi)將字符串轉(zhuǎn)換為byte[]:
- 如果使用UTF8,會(huì)變長(zhǎng)編碼
加密解密方法:
- 加密方法:CreateEncryptor(),返回ICryptoTransform接口類(lèi)型
- 解密方法:CreateDecryptor(),返回ICrtyptoTransform接口類(lèi)型
明文流和加密流的轉(zhuǎn)換:
public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
class Program
{
static void Main(string[] args)
{
#region 對(duì)稱(chēng)加密和解密
string key = "secret key";
string str = "Hello World";
//加密
string encryptedText = SymmetricCryptoHelper.Encrypt(str, key);
Console.WriteLine(encryptedText);
//解密
string clearText = SymmetricCryptoHelper.Decrypt(encryptedText, key);
Console.WriteLine(clearText);
Console.ReadKey();
#endregion
}
}
//對(duì)稱(chēng)加密幫助類(lèi)
public class SymmetricCryptoHelper
{
private ICryptoTransform encryptor; //加密器對(duì)象
private ICryptoTransform decryptor; //解密器對(duì)象
private const int BufferSize = 1024;
public SymmetricCryptoHelper(string algorithmName, byte[] key)
{
SymmetricAlgorithm provider = SymmetricAlgorithm.Create(algorithmName);
provider.Key = key;
provider.IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
encryptor = provider.CreateEncryptor();
decryptor = provider.CreateDecryptor();
}
public SymmetricCryptoHelper(byte[] key) : this("TripleDES", key){}
//加密算法
public string Encrypt(string clearText)
{
//創(chuàng)建明文流
byte[] clearBuffer = Encoding.UTF8.GetBytes(clearText);
//byte[] clearBuffer = Encoding.Default.GetBytes(clearText);
MemoryStream clearStream = new MemoryStream(clearBuffer);
//創(chuàng)建空的密文流
MemoryStream encryptedStream = new MemoryStream();
//明文流和密文流轉(zhuǎn)換流,準(zhǔn)備寫(xiě)到密文流中
CryptoStream cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write);
int bytesRead = 0;
byte[] buffer = new byte[BufferSize];
do
{
//讀取明文流到buffer中
bytesRead = clearStream.Read(buffer, 0, BufferSize);
//通過(guò)CryptoStream將buffer中的明文流字節(jié)數(shù)組寫(xiě)到明文流中
cryptoStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
cryptoStream.FlushFinalBlock();
//獲取加密后的字節(jié)數(shù)組
buffer = encryptedStream.ToArray();
//將加密后的字節(jié)數(shù)組轉(zhuǎn)換成字符串
string encryptedText = Convert.ToBase64String(buffer);
return encryptedText;
}
//解密算法
public string Decrypt(string encryptedText)
{
//把加密字符串轉(zhuǎn)換為加密字節(jié)數(shù)組
byte[] encryptedBuffer = Convert.FromBase64String(encryptedText);
//創(chuàng)建密文流
Stream encryptedStream = new MemoryStream(encryptedBuffer);
//創(chuàng)建空的明文流
MemoryStream clearStream = new MemoryStream();
//創(chuàng)建明文流和密文流的轉(zhuǎn)化流,讀取密文流
CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read);
int bytesRead = 0;
byte[] buffer = new byte[BufferSize];
do
{
//通過(guò)CryptoStream讀取密文流到Buffer
bytesRead = cryptoStream.Read(buffer, 0, BufferSize);
//把Buffer中的密文流寫(xiě)到明文流中
clearStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
//將明文流轉(zhuǎn)換成字節(jié)數(shù)組
buffer = clearStream.GetBuffer();
string clearText = Encoding.UTF8.GetString(buffer, 0, (int)clearStream.Length);
//string clearText = Encoding.Default.GetString(buffer, 0, (int)clearStream.Length);
return clearText;
}
//密匙加密
public static string Encrypt(string clearText, string key)
{
byte[] keyData = new byte[16]; //TripleDES密匙固定長(zhǎng)度為16個(gè)字節(jié)
//把密匙字符串轉(zhuǎn)換成字節(jié)數(shù)組
byte[] sourceData = Encoding.Default.GetBytes(key);
int copyBytes = 16;
if (sourceData.Length < 16)
{
copyBytes = sourceData.Length;
}
//把密匙數(shù)組復(fù)制到keyData字節(jié)數(shù)組中
Array.Copy(sourceData,keyData,copyBytes);
SymmetricCryptoHelper helper = new SymmetricCryptoHelper(keyData);
return helper.Encrypt(clearText);
}
//密匙解密
public static string Decrypt(string encryptedText, string key)
{
byte[] keyData = new byte[16];
byte[] sourceData = Encoding.Default.GetBytes(key);
int copyBytes = 16;
if (sourceData.Length < 16)
{
copyBytes = sourceData.Length;
}
Array.Copy(sourceData,keyData,copyBytes);
SymmetricCryptoHelper helper = new SymmetricCryptoHelper(keyData);
return helper.Decrypt(encryptedText);
}
}
非對(duì)稱(chēng)加密
- AsymmetricAlgorithm
- RSA
- RSACryptoServiceProvider
- DSA
- DSACryptoServiceProvider:只能進(jìn)行認(rèn)證模式,即數(shù)字簽名
- RSA
對(duì)稱(chēng)加密中的密匙:
密匙為由開(kāi)發(fā)者設(shè)定的字符串
非對(duì)稱(chēng)加密中的密匙:
- 通常是自動(dòng)生成,不同的算法有不同的密匙格式???
- 在創(chuàng)建RSACryptoServiceProvider實(shí)例時(shí),會(huì)自動(dòng)創(chuàng)建一個(gè)公/私密匙對(duì)。在實(shí)例上調(diào)用ToXmlString()方法獲得。
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
string publicPrivate = provider.ToXmlString(true);//獲得公/私匙對(duì)
//string publicOnly = provider.ToXmlString(false); //只獲得公匙
Console.Write(publicPrivate);
Console.ReadKey();
非對(duì)稱(chēng)加密幫助類(lèi)
//非對(duì)稱(chēng)加密幫助類(lèi)
public class RSACryptoHelper
{
//加密
public static string Encrypt(string publicKeyXml, string plainText)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(publicKeyXml); //使用公匙初始化對(duì)象
byte[] plainData = Encoding.Default.GetBytes(plainText);
byte[] encryptedData = provider.Encrypt(plainData, true);
return Convert.ToBase64String(encryptedData);
}
//解密
public static string Decrypt(string privateKeyXml, string encryptedText)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(privateKeyXml);
byte[] encryptedData = Convert.FromBase64String(encryptedText);
byte[] plainData = provider.Decrypt(encryptedData, true);
string plainText = Encoding.Default.GetString(plainData);
return plainText;
}
}
數(shù)字簽名
RSACryptoServiceProvider或DSACryptoServiceProvider
SignData()對(duì)摘要進(jìn)行簽名,并返回簽名后的摘要。
VerifyData()得出本地摘要,并解密傳遞進(jìn)來(lái)的原始摘要,對(duì)比返回bool類(lèi)型結(jié)果。
數(shù)字簽名幫助類(lèi)
public class RSACryptoHelper
{
public static string SignData(string plainText, string privateKeyXml)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(privateKeyXml);
byte[] plainData = Encoding.Default.GetBytes(plainText);
//設(shè)置獲取摘要的算法
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
//獲取簽名過(guò)的摘要,是使用私匙加密過(guò)的摘要
byte[] signedDigest = provider.SignData(plainData, sha1);
return Convert.ToBase64String(signedDigest);
}
public static bool VerifyData(string plainText, string signature, string publicKeyXml)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(publicKeyXml);
byte[] plainData = Encoding.Default.GetBytes(plainText);
byte[] signedDigest = Convert.FromBase64String(signature);
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
bool isDataIntact = provider.VerifyData(plainData, sha1, signedDigest);
return isDataIntact;
}
//使用SingnHash
public static string SignData2(string plainText, string privateKeyXml)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(privateKeyXml);
byte[] plainData = Encoding.Default.GetBytes(plainText);
//設(shè)置獲取摘要的算法
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
//獲得原始摘要
byte[] digestData = sha1.ComputeHash(plainData);
//對(duì)元素摘要進(jìn)行簽名
byte[] signedDigest = provider.SignHash(digestData, "SHA1");
return Convert.ToBase64String(signedDigest);
}
//使用VerifyHash
public static bool VerifyData2(string plainText, string signedDigest, string publicKeyXml)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(publicKeyXml);
byte[] plainData = Encoding.Default.GetBytes("SHA1");
byte[] signedDigestData = Convert.FromBase64String(signedDigest);
//獲得本地摘要
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
byte[] digest = sha1.ComputeHash(plainData);
//解密簽名
bool isDataIntact = provider.VerifyHash(digest, "SHA1", signedDigestData);
return isDataIntact;
}
}
原文鏈接:https://www.cnblogs.com/darrenji/p/3677458.html
相關(guān)推薦
- 2022-04-18 使用numpy對(duì)數(shù)組求平均時(shí)如何忽略nan值_python
- 2023-04-06 C語(yǔ)言中的多行輸入問(wèn)題及說(shuō)明_C 語(yǔ)言
- 2022-04-07 C#異步編程async/await用法詳解_C#教程
- 2022-11-23 Python中列表的基本操作匯總_python
- 2022-11-03 PyCharm利用pydevd-pycharm實(shí)現(xiàn)Python遠(yuǎn)程調(diào)試的詳細(xì)過(guò)程_python
- 2022-03-14 sql 排序order by重復(fù)數(shù)據(jù)問(wèn)題
- 2022-09-06 python?留一交叉驗(yàn)證的實(shí)例_python
- 2022-11-03 C#如何給新建的winform程序添加資源文件夾Resources_C#教程
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支