91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

C#中字符串加密和解密技術怎么實現

c#
小億
118
2024-04-28 19:02:48
欄目: 編程語言

在C#中,可以使用一些加密算法來實現字符串加密和解密。常用的加密算法包括對稱加密算法(如AES、DES、RC4等)和非對稱加密算法(如RSA)。

下面是一個簡單示例,演示如何使用AES算法進行字符串加密和解密:

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

public class AesEncryption
{
    private static readonly byte[] key = Encoding.UTF8.GetBytes("encryptionkey123"); // 16 bytes key for AES
    private static readonly byte[] iv = Encoding.UTF8.GetBytes("encryptioniv456"); // 16 bytes IV for AES

    public static string EncryptString(string plainText)
    {
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = key;
            aesAlg.IV = iv;
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            byte[] encrypted;

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

    public static string DecryptString(string cipherText)
    {
        byte[] cipherBytes = Convert.FromBase64String(cipherText);

        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = key;
            aesAlg.IV = iv;
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

            string plaintext = null;

            using (var msDecrypt = new System.IO.MemoryStream(cipherBytes))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (var srDecrypt = new System.IO.StreamReader(csDecrypt))
                    {
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
            return plaintext;
        }
    }

    public static void Main()
    {
        string original = "Hello, world!";
        string encrypted = EncryptString(original);
        string decrypted = DecryptString(encrypted);

        Console.WriteLine("Original: {0}", original);
        Console.WriteLine("Encrypted: {0}", encrypted);
        Console.WriteLine("Decrypted: {0}", decrypted);
    }
}

在上面的示例中,我們使用了AES算法來加密和解密字符串。首先,我們需要定義一個16字節的密鑰和初始向量IV,然后使用這些參數創建一個Aes實例。接著,我們使用CreateEncryptor方法創建一個加密器,并使用CreateDecryptor方法創建一個解密器。最后,我們可以分別使用加密器和解密器來加密和解密字符串。

0
朝阳区| 永安市| 吕梁市| 定远县| 老河口市| 二连浩特市| 饶河县| 门源| 独山县| 渑池县| 类乌齐县| 修水县| 临西县| 宁都县| 兴文县| 城步| 肇源县| 明光市| 肥城市| 渭南市| 屏边| 酉阳| 迁安市| 汽车| 奇台县| 梓潼县| 禹州市| 醴陵市| 新邵县| 杭州市| 荃湾区| 金华市| 玉树县| 建宁县| 甘泉县| 仪征市| 阿克苏市| 新蔡县| 泾川县| 鄢陵县| 临洮县|