Home > Backend Development > C++ > How to Encrypt and Decrypt Strings in C# Using AES?

How to Encrypt and Decrypt Strings in C# Using AES?

Linda Hamilton
Release: 2025-02-02 16:51:10
Original
612 people have browsed it

Use C#and AES algorithms to encrypt and decrypt string

This article introduces how to encrypt and decrypt the string with the C#and Higher Encryption Standard (AES) algorithm. AES is a symmetrical encryption algorithm that provides strong security and is often used to protect sensitive data.

Rijndaelmanaged class

.NET framework provides RijndaelManaged class, which is the host implementation of a AES algorithm. It provides encryption and decryption methods. The method of use is as follows:

<code class="language-csharp">using System.Security.Cryptography;

public class EncryptionManager
{
    private static byte[] _salt = /* 请在此处插入自定义salt */;

    public static string EncryptStringAES(string plainText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(plainText) || string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException();

        using (var aesAlg = new RijndaelManaged())
        {
            // 使用共享密钥和salt生成密钥
            using (var key = new Rfc2898DeriveBytes(sharedSecret, _salt))
            {
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
            }

            // 创建加密器
            var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // 加密文本
            using (var msEncrypt = new MemoryStream())
            {
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (var swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(plainText);
                    }
                }

                // 将加密后的字节转换为base64字符串
                return Convert.ToBase64String(msEncrypt.ToArray());
            }
        }
    }

    public static string DecryptStringAES(string cipherText, string sharedSecret)
    {
        if (string.IsNullOrEmpty(cipherText) || string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException();

        using (var aesAlg = new RijndaelManaged())
        {
            // 使用共享密钥和salt生成密钥
            using (var key = new Rfc2898DeriveBytes(sharedSecret, _salt))
            {
                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);
            }

            var cipherBytes = Convert.FromBase64String(cipherText);
            using (var msDecrypt = new MemoryStream(cipherBytes))
            {
                aesAlg.IV = ReadByteArray(msDecrypt);

                // 创建解密器
                var decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // 解密文本
                using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (var srDecrypt = new StreamReader(csDecrypt))
                    {
                        return srDecrypt.ReadToEnd();
                    }
                }
            }
        }
    }

    private static byte[] ReadByteArray(Stream s)
    {
        byte[] rawLength = new byte[sizeof(int)];
        s.Read(rawLength, 0, rawLength.Length);

        byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
        s.Read(buffer, 0, buffer.Length);

        return buffer;
    }
}</code>
Copy after login

How to Encrypt and Decrypt Strings in C# Using AES?

This code shows how to use the

class to implement AES encryption and decryption. Please note that in the code needs to be replaced with a custom SALT value to enhance security. This example uses to derive the AES key from the shared key and SALT. The encrypted results are returned in the form of Base64 string, which is convenient for storage and transmission. The decryption process is reversed, converting the Base64 string into byte array, and then decrypting. RijndaelManaged The function is used to read IV (initialization vector) from the stream. Remember to deal with potential abnormalities. _salt

The above is the detailed content of How to Encrypt and Decrypt Strings in C# Using AES?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template