From 38ec2e4c2c1b66e0024c97f03b5f145b0832f952 Mon Sep 17 00:00:00 2001 From: Vitaliya Chumakova Date: Tue, 7 Sep 2021 13:47:05 +0300 Subject: [PATCH] Use read-only spans --- YandexKeyExtractor/Decryptor.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/YandexKeyExtractor/Decryptor.cs b/YandexKeyExtractor/Decryptor.cs index 95742d1..7807c0f 100644 --- a/YandexKeyExtractor/Decryptor.cs +++ b/YandexKeyExtractor/Decryptor.cs @@ -8,25 +8,26 @@ namespace YandexKeyExtractor { public static string? Decrypt(string encryptedText, string password) { string base64Text = NormalizeBase64(encryptedText); - Span textBytes = Convert.FromBase64String(base64Text).AsSpan(); + ReadOnlySpan textBytes = Convert.FromBase64String(base64Text).AsSpan(); const byte saltLength = 16; - Span textData = textBytes[..^saltLength]; - Span textSalt = textBytes[^saltLength..]; + ReadOnlySpan textData = textBytes[..^saltLength]; + ReadOnlySpan textSalt = textBytes[^saltLength..]; byte[]? generatedPassword = SCrypt.ComputeDerivedKey(Encoding.UTF8.GetBytes(password), textSalt.ToArray(), 32768, 20, 1, null, 32); using XSalsa20Poly1305 secureBox = new(generatedPassword); const byte nonceLength = 24; - Span nonce = textData[..nonceLength]; - Span dataWithMac = textData[nonceLength..]; + ReadOnlySpan nonce = textData[..nonceLength]; + ReadOnlySpan dataWithMac = textData[nonceLength..]; - Span message = stackalloc byte[dataWithMac.Length]; + + Span message = dataWithMac.Length <= 4096 ? stackalloc byte[dataWithMac.Length] : new byte[dataWithMac.Length]; const byte macLength = 16; - Span data = dataWithMac[macLength..]; - Span mac = dataWithMac[..macLength]; + ReadOnlySpan data = dataWithMac[macLength..]; + ReadOnlySpan mac = dataWithMac[..macLength]; return secureBox.TryDecrypt(message, data, mac, nonce) ? new string(Encoding.UTF8.GetString(message).TrimEnd('\0')) : null; }