C# 使用AES实现简单的加解密

加密:

// 使用SHA-256哈希函数处理秘钥
var hashedKey = GetSHA256Hash(publicKey);

// 加密
var encryptString = EncryptStringToBytes_Aes(strs, hashedKey);


static string GetSHA256Hash(string input)
{
    using (SHA256 sha256 = SHA256.Create())
    {
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        byte[] hashedBytes = sha256.ComputeHash(inputBytes);
        // 取前32字节作为AES算法的秘钥
        return Convert.ToBase64String(hashedBytes).Substring(0, 32);
    }
}

static string EncryptStringToBytes_Aes(string plainText, string Key)
{
    using (Aes aesAlg = Aes.Create())
    {
        aesAlg.Key = Encoding.UTF8.GetBytes(Key);
        aesAlg.IV = new byte[16];

        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, Encoding.UTF8))
                {
                    swEncrypt.Write(plainText);
                }
                return Convert.ToBase64String(msEncrypt.ToArray());
            }
        }
    }
}

解密:

// 使用SHA-256哈希函数处理秘钥
string hashedKey = GetSHA256Hash(publicKey);

var decryptString = DecryptStringFromBytes_Aes(strs, hashedKey);

static string GetSHA256Hash(string input)
{
    using (SHA256 sha256 = SHA256.Create())
    {
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        byte[] hashedBytes = sha256.ComputeHash(inputBytes);
        // 取前32字节作为AES算法的秘钥
        return Convert.ToBase64String(hashedBytes).Substring(0, 32);
    }
}

static string DecryptStringFromBytes_Aes(string cipherText, string Key)
{
    byte[] cipherBytes = Convert.FromBase64String(cipherText);

    using (Aes aesAlg = Aes.Create())
    {
        aesAlg.Key = Encoding.UTF8.GetBytes(Key);
        aesAlg.IV = new byte[16]; // IV应该与加密时生成的IV相同

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

        using (MemoryStream msDecrypt = new MemoryStream(cipherBytes))
        {
            using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
            {
                using (StreamReader srDecrypt = new StreamReader(csDecrypt, Encoding.UTF8))
                {
                    return srDecrypt.ReadToEnd();
                }
            }
        }
    }
}

 

posted @ 2023-12-10 11:32  log9527  阅读(816)  评论(0编辑  收藏  举报