Skip to content

Commit 14dcafc

Browse files
committed
Refactor AesEncryptionHelper and check for sting length when using < net8
1 parent b2c4067 commit 14dcafc

File tree

1 file changed

+14
-21
lines changed

1 file changed

+14
-21
lines changed

src/UglyToad.PdfPig/Encryption/AesEncryptionHelper.cs

Lines changed: 14 additions & 21 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

@@ -30,32 +30,25 @@ public static byte[] Decrypt(byte[] data, byte[] finalKey)
3030
var encryptedData = data.AsSpan(iv.Length);
3131
if (encryptedData.IsEmpty)
3232
{
33+
aes.Clear();
3334
return [];
3435
}
35-
return aes.DecryptCbc(encryptedData, iv, PaddingMode.PKCS7);
36+
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)