在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)應該是足夠復雜且安全的,并且在加密和解密過程中保持不變。在實際應用中,密鑰應該從安全的配置源獲取,而不是硬編碼在代碼中。