当前位置: 首页 > article >正文

C# AES

1.带初始化向量
public class AesEncryption
{
    private readonly byte[] aesKey = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55 };
    private readonly string key = "0123456789abcdef"; // 必须是16, 24, 或 32 个字符
    private readonly string iv = "0000000000000000";  // 必须是16个字符
    public string Encrypt(string plainText)
    {
        using (Aes aesAlg = Aes.Create())
        {
            //aesAlg.Key = aesKey;
            aesAlg.Key = Encoding.UTF8.GetBytes(key);
            aesAlg.IV = Encoding.UTF8.GetBytes(iv);

            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                {
                    swEncrypt.Write(plainText);
                }
                byte[] encrypted = msEncrypt.ToArray();
                return Convert.ToBase64String(encrypted);
            }
        }
    }

    public string Decrypt(string cipherText)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Encoding.UTF8.GetBytes(key);
            aesAlg.IV = Encoding.UTF8.GetBytes(iv);

            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            using (StreamReader srDecrypt = new StreamReader(csDecrypt))
            {
                return srDecrypt.ReadToEnd();
            }
        }
    }
}
private void test_aes()
{
    string original = "This is the data to be encrypted.";

    //using (AesEncryption aes = new AesEncryption())
    AesEncryption aes = new AesEncryption();
    {
        string encrypted = aes.Encrypt(original);
        Console.WriteLine($"Encrypted:   {encrypted}");

        string decrypted = aes.Decrypt(encrypted);
        Console.WriteLine($"Decrypted:   {decrypted}");
    }
}
2.不带初始化向量, ECB, 128bit, base64
public class AESNoIVExample
{
     public byte[] GenerateRandomSalt()
     {
         byte[] salt = new byte[16];
         using (var rng = new RNGCryptoServiceProvider())
         {
             rng.GetBytes(salt);
         }
         // 注意:在实际应用中,你应该存储并重用这个盐值,而不是每次都生成一个新的。
         // 但在这个例子中,为了简化,我们每次都生成一个新的盐值。
         // 这意味着每次运行程序时,即使密码相同,生成的密钥也会不同。
         // 这只是为了演示目的,不应该在实际加密场景中使用。
         return salt;
     }

     public byte[] Encrypt(string plainText, byte[] Key)
     {
         if (plainText == null || plainText.Length <= 0)
             throw new ArgumentNullException(nameof(plainText));
         if (Key == null || Key.Length <= 0)
             throw new ArgumentNullException(nameof(Key));
         byte[] encrypted;

         using (Aes aesAlg = Aes.Create())
         {
             aesAlg.Key = Key;
             // 不设置IV(不推荐)
             // aesAlg.IV = ...; // 不使用IV

             aesAlg.Mode = CipherMode.ECB; // 使用ECB模式(不推荐,因为它不安全)
             aesAlg.Padding = PaddingMode.PKCS7;

             ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, null); // 传入null作为IV

             using (MemoryStream msEncrypt = new MemoryStream())
             {
                 using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                 using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                 {
                     swEncrypt.Write(plainText);
                 }
                 encrypted = msEncrypt.ToArray();
             }
         }

         return encrypted;
     }

     public string Decrypt(byte[] cipherText, byte[] Key)
     {
         if (cipherText == null || cipherText.Length <= 0)
             throw new ArgumentNullException(nameof(cipherText));
         if (Key == null || Key.Length <= 0)
             throw new ArgumentNullException(nameof(Key));

         string plaintext = null;

         using (Aes aesAlg = Aes.Create())
         {
             aesAlg.Key = Key;
             // 不设置IV(不推荐)
             // aesAlg.IV = ...; // 不使用IV

             aesAlg.Mode = CipherMode.ECB; // 使用ECB模式(不推荐,因为它不安全)
             aesAlg.Padding = PaddingMode.PKCS7;

             ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, null); // 传入null作为IV

             using (MemoryStream msDecrypt = new MemoryStream(cipherText))
             {
                 using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                 using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                 {
                     plaintext = srDecrypt.ReadToEnd();
                 }
             }
         }

         return plaintext;
     }
 }
private void test_aes()
{

    //2. AES NoIV
    string plaintext = "This is the data to be encrypted.";
    string password = "0123456789abcdef"; // 用于生成密钥的密码

    AESNoIVExample ase2 = new AESNoIVExample();
    // 生成密钥
    byte[] key = Encoding.UTF8.GetBytes(password);

    // 加密
    byte[] encrypted2 = ase2.Encrypt(plaintext, key);
    string base64Encrypted = Convert.ToBase64String(encrypted2);
    Console.WriteLine("Encrypted (Base64): " + base64Encrypted);

    // 解密
    byte[] decryptedBytes = Convert.FromBase64String(base64Encrypted);
    string decrypted2 = ase2.Decrypt(decryptedBytes, key);
    Console.WriteLine("Decrypted: " + decrypted2);
}

http://www.kler.cn/a/429042.html

相关文章:

  • 探索与创作:2024年CSDN平台上的成长与突破
  • MySQL、HBase、ES的特点和区别
  • CIA-Access V2.5_9_2_10G EPON技术原理_关键技术
  • VS Code--常用的插件
  • Web渗透测试之伪协议与SSRF服务器请求伪装结合? 能产生更多的效果
  • springboot如何解析 Map 的泛型信息来确定要注入哪些 Bean?
  • spring中的@Bean和@Component有什么区别?
  • CentOS 9 Stream上安装SQL Server 2022
  • OceanBase数据库使用 INSERT 语句违反唯一约束冲突解决办法及两者差异分析
  • python+docker实现分布式存储的demo
  • git commit -m “Add user login feature“
  • Winform(C#)实现下拉列表显示表格(利用自定义组件)
  • Vector软件CANdb++的信号起始位Bug
  • Bellman-Ford 算法详解及应用
  • c语言学生管理系统(内置数据库版本)
  • KVM 虚拟化
  • 深度学习中的数据并行
  • Qt学习笔记第51到60讲
  • 深入探索 Compose 渲染流程:从 UI 树到 Skia 绘制的实现解析
  • 关于csgo游戏搬砖作弊与封禁
  • 沪合共融 “汽”势如虹 | 昂辉科技参加合肥上海新能源汽车产业融合对接会
  • git 拉取代码时报错 gitignore Please move or remove them before you merge.
  • 21 网络编程:Go 语言如何玩转 RESTful API 服务
  • 数据分析: 基于CSDN博客排行榜TOP100的博客创作分析和建议
  • .vscode文件中各个脚本需要修改的地方
  • uni-app登录界面样式