Пожалуйста, помогите мне. Я хочу зашифровать с использованием алгоритма AES-GCM в коде c Sharp, ниже приведен мой код.
Однако он не может расшифровать. Я хочу сохранить код расшифровки.
Как решить эту проблему? Пожалуйста, помогите мне.
Пожалуйста, помогите мне. Я хочу зашифровать с использованием алгоритма AES-GCM в коде c Sharp, ниже приведен мой код. Однако он не может расшифровать. Я хочу сохранить код расшифровки. Как решить эту проблему? Пожалуйста, помогите мне. [code]// Encryption code. private static byte[] salt = new byte[16]; // Fix 1: consider salt private static byte[] iv = new byte[12]; private const int iterations = 100000; // Fix 2: apply the same iteration count public string Encrypt(string key, string data) { byte[] tag = new byte[16]; using (var rng = RandomNumberGenerator.Create()) { rng.GetBytes(salt); rng.GetBytes(iv); } byte[] dataBytes = Encoding.UTF8.GetBytes(data); byte[] privateKey = DeriveKey(key);
using (AesGcm aes = new AesGcm(privateKey, tag.Length)) { byte[] encrypted = new byte[dataBytes.Length]; aes.Encrypt(iv, dataBytes, encrypted, tag);
string base64Buff = BuffToBase64(combinedBuffer); return base64Buff; } } public static byte[] DeriveKey(string password) { byte[] passwordBytes = Encoding.UTF8.GetBytes(password); using (var pbkdf2 = new Rfc2898DeriveBytes(passwordBytes, salt, iterations, HashAlgorithmName.SHA256)) { byte[] key = pbkdf2.GetBytes(32); // Fix 3: use the same key size (256 bits) return key; } }
public static string BuffToBase64(byte[] buff) { return Convert.ToBase64String(buff); }
public static byte[] Base64ToBuff(string b64) { return Convert.FromBase64String(b64); }
// Decryption code.
public string Decrypt(string password, string encryptedString) {
Span encryptedData = Convert.FromBase64String(encryptedString).AsSpan(); Span salt = encryptedData[..16]; Span nonce = encryptedData[16..(16 + 12)]; Span data = encryptedData[(16 + 12)..^16]; Span tag = encryptedData[^16..]; using Rfc2898DeriveBytes pbkdf2 = new(Encoding.UTF8.GetBytes(password), salt.ToArray(), 100000, HashAlgorithmName.SHA256); using AesGcm aes = new(pbkdf2.GetBytes(32), tag.Length); Span result = new byte[data.Length]; aes.Decrypt(nonce, data, tag, result); return Encoding.UTF8.GetString(result);
} //Run the program. var r = new AesGcmEncryption().Encrypt("my passphrase", "abcd"); var r2 = new AesGcmEncryption().Decrypt("my passphrase", r); Console.WriteLine(r); Console.WriteLine(r2);
//Error: 'Specified argument was out of the range of valid values' [/code] Я попробовал изменить все регистры, изменив код, и поискал, но никто не написал подобного кода.