Skip to content

Commit 87f5735

Browse files
committed
Refactor AesEncryptionHelper and check for sting length when using < net8
1 parent eeac910 commit 87f5735

File tree

1 file changed

+16
-23
lines changed

1 file changed

+16
-23
lines changed

src/UglyToad.PdfPig/Encryption/AesEncryptionHelper.cs

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
namespace UglyToad.PdfPig.Encryption
22
{
33
using System;
4-
using System.IO;
54
using System.Security.Cryptography;
65

76
internal static class AesEncryptionHelper
87
{
98
public static byte[] Encrypt256()
109
{
10+
// See https://stackoverflow.com/questions/73779169/cryptographicexception-bad-pkcs7-padding-invalid-length-0-cannot-decrypt-sa
1111
throw new NotImplementedException();
1212
}
1313

@@ -27,35 +27,28 @@ public static byte[] Decrypt(byte[] data, byte[] finalKey)
2727
aes.IV = iv;
2828

2929
#if NET8_0_OR_GREATER
30-
var encryptedData = data.AsSpan(iv.Length);
31-
if (encryptedData.IsEmpty)
30+
if (data.Length <= iv.Length)
3231
{
32+
aes.Clear();
3333
return [];
3434
}
35-
return aes.DecryptCbc(encryptedData, iv, PaddingMode.PKCS7);
35+
36+
var encryptedData = data.AsSpan(iv.Length);
37+
var output = aes.DecryptCbc(encryptedData, iv, PaddingMode.PKCS7);
38+
aes.Clear();
39+
return output;
3640
#else
37-
var buffer = new byte[256];
41+
if (data.Length <= iv.Length)
42+
{
43+
aes.Clear();
44+
return [];
45+
}
3846

3947
using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
40-
using (var input = new MemoryStream(data))
41-
using (var output = new MemoryStream())
4248
{
43-
input.Seek(iv.Length, SeekOrigin.Begin);
44-
using (var cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
45-
{
46-
int read;
47-
do
48-
{
49-
read = cryptoStream.Read(buffer, 0, buffer.Length);
50-
51-
if (read > 0)
52-
{
53-
output.Write(buffer, 0, read);
54-
}
55-
} while (read > 0);
56-
57-
return output.ToArray();
58-
}
49+
var output = decryptor.TransformFinalBlock(data, iv.Length, data.Length - iv.Length);
50+
aes.Clear();
51+
return output;
5952
}
6053
#endif
6154
}

0 commit comments

Comments
 (0)