網站首頁 編程語言 正文
散列運算
mscorlib.dll下的System.Security.Cryptography下:
- 抽象類HashAlgorithm
- 抽象類MD5
- MD5CryptoServiceProvider
- SHA1
- SHA1CryptoServiceProvider密封類:調用Windows Crypto API
- SHA1Managed普通類:用托管代碼寫的
- SHA256
- SHA256CryptoServiceProvider
- SHA256Managed
- SHA384
- SHA512
- 抽象類MD5
對字節數組或流散列運算
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";
}
密匙散列運算
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);
}
對稱加密和解密
- SymmetricAlgorithm
- DES
- DESCryptoServiceProvider
- TripleDES
- TripleDESCryptoServiceProvider
- Rijndael
- RijindaelManaged
- RC2
- RC2CryptoServiceProvider
- DES
IV:Initialization vector初始化向量:
- 為了解決加密字符串加密后仍然有重復部分,引入IV,加密字符串即使有重復,也會被打亂。
- IV值可以隨意指定,但長度固定,通常為64位byte類型
- 密匙長度也是固定的,通常為128位或196位byte類型
使用Encoding類將字符串轉換為byte[]:
- 如果使用UTF8,會變長編碼
加密解密方法:
- 加密方法:CreateEncryptor(),返回ICryptoTransform接口類型
- 解密方法:CreateDecryptor(),返回ICrtyptoTransform接口類型
明文流和加密流的轉換:
public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
class Program
{
static void Main(string[] args)
{
#region 對稱加密和解密
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
}
}
//對稱加密幫助類
public class SymmetricCryptoHelper
{
private ICryptoTransform encryptor; //加密器對象
private ICryptoTransform decryptor; //解密器對象
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)
{
//創建明文流
byte[] clearBuffer = Encoding.UTF8.GetBytes(clearText);
//byte[] clearBuffer = Encoding.Default.GetBytes(clearText);
MemoryStream clearStream = new MemoryStream(clearBuffer);
//創建空的密文流
MemoryStream encryptedStream = new MemoryStream();
//明文流和密文流轉換流,準備寫到密文流中
CryptoStream cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write);
int bytesRead = 0;
byte[] buffer = new byte[BufferSize];
do
{
//讀取明文流到buffer中
bytesRead = clearStream.Read(buffer, 0, BufferSize);
//通過CryptoStream將buffer中的明文流字節數組寫到明文流中
cryptoStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
cryptoStream.FlushFinalBlock();
//獲取加密后的字節數組
buffer = encryptedStream.ToArray();
//將加密后的字節數組轉換成字符串
string encryptedText = Convert.ToBase64String(buffer);
return encryptedText;
}
//解密算法
public string Decrypt(string encryptedText)
{
//把加密字符串轉換為加密字節數組
byte[] encryptedBuffer = Convert.FromBase64String(encryptedText);
//創建密文流
Stream encryptedStream = new MemoryStream(encryptedBuffer);
//創建空的明文流
MemoryStream clearStream = new MemoryStream();
//創建明文流和密文流的轉化流,讀取密文流
CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read);
int bytesRead = 0;
byte[] buffer = new byte[BufferSize];
do
{
//通過CryptoStream讀取密文流到Buffer
bytesRead = cryptoStream.Read(buffer, 0, BufferSize);
//把Buffer中的密文流寫到明文流中
clearStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
//將明文流轉換成字節數組
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密匙固定長度為16個字節
//把密匙字符串轉換成字節數組
byte[] sourceData = Encoding.Default.GetBytes(key);
int copyBytes = 16;
if (sourceData.Length < 16)
{
copyBytes = sourceData.Length;
}
//把密匙數組復制到keyData字節數組中
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);
}
}
非對稱加密
- AsymmetricAlgorithm
- RSA
- RSACryptoServiceProvider
- DSA
- DSACryptoServiceProvider:只能進行認證模式,即數字簽名
- RSA
對稱加密中的密匙:
密匙為由開發者設定的字符串
非對稱加密中的密匙:
- 通常是自動生成,不同的算法有不同的密匙格式???
- 在創建RSACryptoServiceProvider實例時,會自動創建一個公/私密匙對。在實例上調用ToXmlString()方法獲得。
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
string publicPrivate = provider.ToXmlString(true);//獲得公/私匙對
//string publicOnly = provider.ToXmlString(false); //只獲得公匙
Console.Write(publicPrivate);
Console.ReadKey();
非對稱加密幫助類
//非對稱加密幫助類
public class RSACryptoHelper
{
//加密
public static string Encrypt(string publicKeyXml, string plainText)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(publicKeyXml); //使用公匙初始化對象
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;
}
}
數字簽名
RSACryptoServiceProvider或DSACryptoServiceProvider
SignData()對摘要進行簽名,并返回簽名后的摘要。
VerifyData()得出本地摘要,并解密傳遞進來的原始摘要,對比返回bool類型結果。
數字簽名幫助類
public class RSACryptoHelper
{
public static string SignData(string plainText, string privateKeyXml)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(privateKeyXml);
byte[] plainData = Encoding.Default.GetBytes(plainText);
//設置獲取摘要的算法
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
//獲取簽名過的摘要,是使用私匙加密過的摘要
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);
//設置獲取摘要的算法
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
//獲得原始摘要
byte[] digestData = sha1.ComputeHash(plainData);
//對元素摘要進行簽名
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
相關推薦
- 2023-01-09 python自動化測試中裝飾器@ddt與@data源碼深入解析_python
- 2023-01-05 TensorFlow?2.0之后動態分配顯存方式_python
- 2022-12-06 Python?if?判斷語句詳解_python
- 2022-04-10 python?tkinter實現簡單計算器功能_python
- 2022-05-08 ASP.NET?MVC視圖尋址_實用技巧
- 2022-09-25 Redis時單線程設計的,為什么還這么快
- 2023-05-22 Pytorch中TensorDataset,DataLoader的聯合使用方式_python
- 2022-06-28 C++詳解多線程中的線程同步與互斥量_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支