Пожалуйста, помогите мне. Я хочу зашифровать код C# с использованием алгоритма AES-GCM.
Вот мой код, однако он не может расшифровать. Я хочу сохранить код расшифровки.
Как решить эту проблему? Пожалуйста, помогите мне.
// 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);
byte[] combinedBuffer = new byte[salt.Length + iv.Length + encrypted.Length];
Buffer.BlockCopy(salt, 0, combinedBuffer, 0, salt.Length); // Fix 1: consider salt
Buffer.BlockCopy(iv, 0, combinedBuffer, salt.Length, iv.Length);
Buffer.BlockCopy(encrypted, 0, combinedBuffer, salt.Length + iv.Length, encrypted.Length);
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);
Ошибка:
Указанный аргумент находится вне диапазона допустимых значений
< /blockquote>
Я попробовал изменить все регистры, изменив код, и поискал, но никто не написал подобного кода.
Пожалуйста, помогите мне. Я хочу зашифровать код C# с использованием алгоритма AES-GCM. Вот мой код, однако он не может расшифровать. Я хочу сохранить код расшифровки. Как решить эту проблему? Пожалуйста, помогите мне. [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); }
Указанный аргумент находится вне диапазона допустимых значений < /blockquote> Я попробовал изменить все регистры, изменив код, и поискал, но никто не написал подобного кода.
Пожалуйста, помогите мне. Я хочу зашифровать с использованием алгоритма AES-GCM в коде c Sharp, ниже приведен мой код.
Однако он не может расшифровать. Я хочу сохранить код расшифровки.
Как решить эту проблему? Пожалуйста, помогите мне.
//...
To follow the new Peppol requirements for banking in Norway I have to use asymmetric encryption. The file I need to send is a pkcs#7 file and the encryption of the key needs to be aes-256-gcm.
Note that I am working on a Windows machine and am...
У меня есть строка, представляющая симметричный ключ, полученный с помощью Hashicorp Vault (на самом деле это может быть не важно). Мне нужен этот ключ для шифрования больших файлов, поэтому я не могу отправить файл напрямую в Vault с просьбой...
Я конвертирую существующий/рабочий код, который используется с AES/CTR/NoPadding, из SunJCE в AES/GCM/NoPadding — SunJCE.
Шифрование используется с используемым выходным потоком для создания ObjectOutputStream.
Для запуска ObjectOutputStreams...
Я пытался изучить AES GCM ( Хотя сайт отлично справляется с объединением кода в один. Я пытался сломать его и сделать функцией (GCM Encrypt и GCM Decrypt). Кажется, я разобрался с частью шифрования, но совершенно потерялся в части расшифровки. Будем...