c#

在C#中如何对token进行加密

小樊
91
2024-08-30 23:07:40
栏目: 编程语言

在C#中,对token进行加密通常使用的是对称加密算法,如AES(Advanced Encryption Standard)。以下是一个使用AES加密和解密token的示例:

首先,需要引入System.Security.Cryptography命名空间。

using System.Security.Cryptography;

接下来,创建一个加密和解密的方法:

public static class AesEncryption
{
    private const int KeySize = 256;
    private const int BlockSize = 128;

    public static string Encrypt(string plainText, string key)
    {
        using (var aes = new AesManaged())
        {
            aes.KeySize = KeySize;
            aes.BlockSize = BlockSize;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            var keyBytes = Encoding.UTF8.GetBytes(key);
            var iv = new byte[aes.BlockSize / 8];
            Array.Copy(keyBytes, iv, iv.Length);

            aes.Key = keyBytes;
            aes.IV = iv;

            using (var encryptor = aes.CreateEncryptor())
            {
                var inputData = Encoding.UTF8.GetBytes(plainText);
                var encryptedData = encryptor.TransformFinalBlock(inputData, 0, inputData.Length);
                return Convert.ToBase64String(encryptedData);
            }
        }
    }

    public static string Decrypt(string cipherText, string key)
    {
        using (var aes = new AesManaged())
        {
            aes.KeySize = KeySize;
            aes.BlockSize = BlockSize;
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.PKCS7;

            var keyBytes = Encoding.UTF8.GetBytes(key);
            var iv = new byte[aes.BlockSize / 8];
            Array.Copy(keyBytes, iv, iv.Length);

            aes.Key = keyBytes;
            aes.IV = iv;

            using (var decryptor = aes.CreateDecryptor())
            {
                var inputData = Convert.FromBase64String(cipherText);
                var decryptedData = decryptor.TransformFinalBlock(inputData, 0, inputData.Length);
                return Encoding.UTF8.GetString(decryptedData);
            }
        }
    }
}

现在,你可以使用这些方法对token进行加密和解密:

string token = "your_token_here";
string key = "your_key_here"; // 请确保密钥长度至少为16个字符

// 加密token
string encryptedToken = AesEncryption.Encrypt(token, key);
Console.WriteLine("Encrypted token: " + encryptedToken);

// 解密token
string decryptedToken = AesEncryption.Decrypt(encryptedToken, key);
Console.WriteLine("Decrypted token: " + decryptedToken);

请注意,密钥(key)应该是足够复杂且安全的,并且在加密和解密过程中保持不变。在实际应用中,密钥应该从安全的配置源获取,而不是硬编码在代码中。

0
看了该问题的人还看了