有一个关键类:
public class EncryptKey
{
public EncryptKey (byte[] key) => Key = key;
public EncryptKey (string key) => FromString(key);
public byte[] Key { get; set; }
public void FromString (string s)
{
using SymmetricAlgorithm sa = Aes.Create();
using Rfc2898DeriveBytes hasher = new(s, sa.IV, 5000, HashAlgorithmName.SHA512);
Key = hasher.GetBytes(32);
}
public override string ToString() => Convert.ToBase64String(Key);
}
加密实现如下所示:
public static string Encrypt (string text, IEncryptKey key)
{
string textToEncode = text.Replace("/", "%SL%").Replace("+", "%PL%");
using Aes aes = Aes.Create();
aes.Key = key.Key;
using MemoryStream ms = new();
ms.Write(aes.IV);
using (CryptoStream cs = new(ms, aes.CreateEncryptor(), CryptoStreamMode.Write, true))
cs.Write(Encoding.UTF8.GetBytes(textToEncode));
return Convert.ToBase64String(ms.ToArray());
}
public static string Decrypt (string text, IEncryptKey key)
{
string textToDecode = text.Replace("%SL%", "/").Replace("%PL%", "+");
using MemoryStream ms = new(Convert.FromBase64String(textToDecode));
byte[] iv = new byte[16];
_ = ms.Read(iv);
using Aes aes = Aes.Create();
aes.Key = key.Key;
aes.IV = iv;
using CryptoStream cs = new(ms, aes.CreateDecryptor(), CryptoStreamMode.Read, true);
using MemoryStream output = new();
cs.CopyTo(output);
return Encoding.UTF8.GetString(output.ToArray());
}
我这样称呼:
var encText = Encrypt(Guid.NewGuid().ToString, new("123"));
var decText = Decrypt(encText, new("123"));
结果,出现错误:
FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters