C# 关于加密技术以及应用(一)

在 开发过程中,加密是一个常见的需求,数字签名和验证、网络通信安全、数据加密解密、用于保护数据的安全性和隐私。如几种常用的加密技术AES、SSL/TLS、RSA、HMAC 、SHA等,都是我们开发过程中常用到的加密方式,只不过每一个加密方式都有自己的特长。
下面就逐个讲一下

1. AES (Advanced Encryption Standard)

AES 是一种对称加密算法,广泛用于数据加密和解密。在 C# 中,可以使用 System.Security.Cryptography.Aes 类来实现 AES 加密和解密。

示例代码

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public class AesEncryption
{
   
    public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] key, byte[] iv)
    {
   
    	//创建加密器 encryptor
        using (Aes aesAlg = Aes.Create())
        {
   
            aesAlg.Key = key;
            aesAlg.IV = iv;
			//创建加密器 encryptor
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
			//使用 MemoryStream 和 CryptoStream 进行加密操作。
            using (MemoryStream msEncrypt = new MemoryStream())
            {
   
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
   
                	//将明文写入 StreamWriter,并通过 CryptoStream 进行加密。
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
   
                        swEncrypt.Write(plainText);
                    }
                }
                return msEncrypt.ToArray();
            }
        }
    }
    
	///cipherText: 需要解密的密文字节数组。
	///key: 解密密钥。
	///iv: 初始化向量(IV)。
    public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] key, byte[] iv)
    {
   
    	//•	使用 Aes.Create() 创建一个 AES 对象。
        using (Aes aesAlg = Aes.Create())
        {
   
        	//设置 AES 对象的密钥和初始化向量
            aesAlg.Key = key;
            aesAlg.IV = iv;
			//创建解密器 decryptor。
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, a
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜空晚星灿烂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值