C#中如何实现AES算法加密

发布时间:2023-02-27 09:25:13 作者:iii
来源:亿速云 阅读:123

C#中如何实现AES算法加密

目录

  1. 引言
  2. AES算法简介
  3. C#中的加密库
  4. AES加密的基本步骤
  5. AES加密的完整示例
  6. AES加密的高级应用
  7. AES加密的安全性考虑
  8. AES加密的性能优化
  9. AES加密的常见问题与解决方案
  10. 总结

引言

在现代计算机科学中,数据安全是一个至关重要的话题。随着互联网的普及和信息技术的发展,数据加密技术成为了保护信息安全的重要手段之一。AES(Advanced Encryption Standard)算法作为一种广泛使用的对称加密算法,因其高效性和安全性而被广泛应用于各种场景中。本文将详细介绍如何在C#中实现AES算法加密,并通过多个示例展示其应用。

AES算法简介

2.1 AES算法的历史

AES算法是由美国国家标准与技术研究院(NIST)于2001年发布的一种对称加密算法。它取代了之前广泛使用的DES(Data Encryption Standard)算法,成为新的加密标准。AES算法的设计目标是提供更高的安全性和更快的加密速度。

2.2 AES算法的基本原理

AES算法是一种分组加密算法,它将明文数据分成固定长度的块(128位),然后通过多轮加密操作将其转换为密文。AES算法的加密过程包括四个主要步骤:字节替换(SubBytes)、行移位(ShiftRows)、列混淆(MixColumns)和轮密钥加(AddRoundKey)。这些步骤在多轮加密中重复进行,最终生成密文。

2.3 AES算法的密钥长度

AES算法支持三种密钥长度:128位、192位和256位。密钥长度越长,加密的安全性越高,但加密速度也会相应降低。在实际应用中,通常根据安全需求和性能要求选择合适的密钥长度。

C#中的加密库

3.1 System.Security.Cryptography命名空间

在C#中,加密操作主要通过System.Security.Cryptography命名空间中的类来实现。该命名空间提供了多种加密算法,包括对称加密算法(如AES、DES)、非对称加密算法(如RSA)和哈希算法(如SHA)。

3.2 常用的加密类

System.Security.Cryptography命名空间中,常用的加密类包括:

AES加密的基本步骤

4.1 生成密钥和初始化向量

在AES加密中,密钥和初始化向量(IV)是加密和解密的关键。密钥用于加密数据,而IV用于确保相同的明文在不同加密操作中生成不同的密文。密钥和IV通常通过随机数生成器生成。

4.2 创建AES加密器

在C#中,可以使用Aes类创建AES加密器。通过设置KeyIV属性,可以指定加密所需的密钥和初始化向量。然后,使用CreateEncryptor方法创建加密器对象。

4.3 加密数据

加密数据的过程通常包括以下步骤:

  1. 将明文数据转换为字节数组。
  2. 使用加密器对象对字节数组进行加密。
  3. 将加密后的字节数组转换为密文。

4.4 解密数据

解密数据的过程与加密过程类似,但使用解密器对象。具体步骤包括:

  1. 将密文转换为字节数组。
  2. 使用解密器对象对字节数组进行解密。
  3. 将解密后的字节数组转换为明文。

AES加密的完整示例

5.1 生成密钥和IV

using System;
using System.Security.Cryptography;

class Program
{
    static void Main()
    {
        using (Aes aes = Aes.Create())
        {
            aes.GenerateKey();
            aes.GenerateIV();

            Console.WriteLine("Key: " + Convert.ToBase64String(aes.Key));
            Console.WriteLine("IV: " + Convert.ToBase64String(aes.IV));
        }
    }
}

5.2 加密字符串

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

class Program
{
    static void Main()
    {
        string original = "Hello, World!";
        using (Aes aes = Aes.Create())
        {
            aes.GenerateKey();
            aes.GenerateIV();

            byte[] encrypted = EncryptStringToBytes_Aes(original, aes.Key, aes.IV);
            Console.WriteLine("Encrypted: " + Convert.ToBase64String(encrypted));
        }
    }

    static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        byte[] encrypted;

        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.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;
    }
}

5.3 解密字符串

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

class Program
{
    static void Main()
    {
        string original = "Hello, World!";
        using (Aes aes = Aes.Create())
        {
            aes.GenerateKey();
            aes.GenerateIV();

            byte[] encrypted = EncryptStringToBytes_Aes(original, aes.Key, aes.IV);
            string decrypted = DecryptStringFromBytes_Aes(encrypted, aes.Key, aes.IV);

            Console.WriteLine("Original: " + original);
            Console.WriteLine("Decrypted: " + decrypted);
        }
    }

    static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        byte[] encrypted;

        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.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;
    }

    static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        string plaintext = null;

        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

            ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.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;
    }
}

AES加密的高级应用

6.1 使用AES加密文件

在实际应用中,AES加密不仅可以用于加密字符串,还可以用于加密文件。以下是一个使用AES加密文件的示例:

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

class Program
{
    static void Main()
    {
        string inputFile = "input.txt";
        string outputFile = "output.enc";
        string decryptedFile = "decrypted.txt";

        using (Aes aes = Aes.Create())
        {
            aes.GenerateKey();
            aes.GenerateIV();

            EncryptFile(inputFile, outputFile, aes.Key, aes.IV);
            DecryptFile(outputFile, decryptedFile, aes.Key, aes.IV);
        }
    }

    static void EncryptFile(string inputFile, string outputFile, byte[] Key, byte[] IV)
    {
        using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
        using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

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

            using (CryptoStream csEncrypt = new CryptoStream(fsOutput, encryptor, CryptoStreamMode.Write))
            {
                fsInput.CopyTo(csEncrypt);
            }
        }
    }

    static void DecryptFile(string inputFile, string outputFile, byte[] Key, byte[] IV)
    {
        using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
        using (FileStream fsOutput = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

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

            using (CryptoStream csDecrypt = new CryptoStream(fsInput, decryptor, CryptoStreamMode.Read))
            {
                csDecrypt.CopyTo(fsOutput);
            }
        }
    }
}

6.2 使用AES加密数据库字段

在数据库应用中,敏感数据(如用户密码、信用卡信息)通常需要加密存储。以下是一个使用AES加密数据库字段的示例:

using System;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionString";
        string original = "SensitiveData";

        using (Aes aes = Aes.Create())
        {
            aes.GenerateKey();
            aes.GenerateIV();

            byte[] encrypted = EncryptStringToBytes_Aes(original, aes.Key, aes.IV);

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                string query = "INSERT INTO SensitiveDataTable (EncryptedData) VALUES (@EncryptedData)";
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@EncryptedData", encrypted);
                    command.ExecuteNonQuery();
                }
            }
        }
    }

    static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        byte[] encrypted;

        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.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;
    }
}

6.3 使用AES加密网络通信

在网络通信中,数据的安全性至关重要。以下是一个使用AES加密网络通信的示例:

using System;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;

class Program
{
    static void Main()
    {
        string server = "127.0.0.1";
        int port = 12345;

        using (Aes aes = Aes.Create())
        {
            aes.GenerateKey();
            aes.GenerateIV();

            using (TcpClient client = new TcpClient(server, port))
            using (NetworkStream stream = client.GetStream())
            {
                string message = "Hello, Server!";
                byte[] encrypted = EncryptStringToBytes_Aes(message, aes.Key, aes.IV);

                stream.Write(encrypted, 0, encrypted.Length);

                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                byte[] decrypted = DecryptBytesFromBytes_Aes(buffer, aes.Key, aes.IV);

                Console.WriteLine("Received: " + Encoding.UTF8.GetString(decrypted));
            }
        }
    }

    static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
    {
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        byte[] encrypted;

        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

            ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.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;
    }

    static byte[] DecryptBytesFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV");

        byte[] decrypted;

        using (Aes aes = Aes.Create())
        {
            aes.Key = Key;
            aes.IV = IV;

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

            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (MemoryStream msOutput = new MemoryStream())
                    {
                        csDecrypt.CopyTo(msOutput);
                        decrypted = msOutput.ToArray();
                    }
                }
            }
        }

        return decrypted;
    }
}

AES加密的安全性考虑

7.1

推荐阅读:
  1. 使用cobbler 安装CentOS8
  2. JMS与ActiveMQ消息数据持久化

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

aes

上一篇:怎么使用C#最小二乘法拟合曲线成直线

下一篇:Java多线程之锁怎么使用

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》