Skip to content

Commit 84c3a8d

Browse files
committed
Decrypt should take into account unpadding for the final output if padding is specified.
1 parent 79ff9a3 commit 84c3a8d

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/Renci.SshNet/Security/Cryptography/BlockCipher.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
using System;
22

3+
using Org.BouncyCastle.Crypto.Paddings;
4+
35
using Renci.SshNet.Security.Cryptography.Ciphers;
6+
using Renci.SshNet.Security.Cryptography.Ciphers.Paddings;
47

58
namespace Renci.SshNet.Security.Cryptography
69
{
@@ -153,6 +156,12 @@ public override byte[] Decrypt(byte[] input, int offset, int length)
153156
throw new InvalidOperationException("Encryption error.");
154157
}
155158

159+
if (_padding is PKCS7Padding)
160+
{
161+
var paddingLength = new Pkcs7Padding().PadCount(output);
162+
Array.Resize(ref output, output.Length - paddingLength);
163+
}
164+
156165
return output;
157166
}
158167

test/Renci.SshNet.Tests/Classes/Security/Cryptography/BlockCipherTest.cs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,17 +56,19 @@ public void EncryptShouldTakeIntoAccountPaddingForLengthOfInputBufferPassedToEnc
5656
}
5757

5858
[TestMethod]
59-
public void DecryptShouldTakeIntoAccountPaddingForLengthOfOutputBufferPassedToDecryptBlock()
59+
public void DecryptShouldTakeIntoAccountUnPaddingForTheFinalOutput()
6060
{
61-
var input = new byte[] { 0x2c, 0x1a, 0x05, 0x00, 0x68 };
62-
var output = new byte[] { 0x0a, 0x00, 0x03, 0x02, 0x06, 0x08, 0x07, 0x05 };
61+
var input = new byte[] { 0x0a, 0x00, 0x03, 0x02, 0x06, 0x08, 0x07, 0x05 };
62+
var output = new byte[] { 0x2c, 0x1a, 0x05, 0x00, 0x68 };
63+
var padding = new byte[] { 0x03, 0x03, 0x03 };
6364
var key = new byte[] { 0x17, 0x78, 0x56, 0xe1, 0x3e, 0xbd, 0x3e, 0x50, 0x1d, 0x79, 0x3f, 0x0f, 0x55, 0x37, 0x45, 0x54 };
6465
var blockCipher = new BlockCipherStub(key, 8, null, new PKCS7Padding())
6566
{
6667
DecryptBlockDelegate = (inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset) =>
6768
{
6869
Assert.AreEqual(8, outputBuffer.Length);
6970
Buffer.BlockCopy(output, 0, outputBuffer, 0, output.Length);
71+
Buffer.BlockCopy(padding, 0, outputBuffer, output.Length, padding.Length);
7072
return inputBuffer.Length;
7173
}
7274
};

0 commit comments

Comments
 (0)