From adcd55b240c264acdbd5ad7e05fe089e43f64261 Mon Sep 17 00:00:00 2001 From: Jeremy Barton Date: Mon, 11 Nov 2019 12:52:44 -0800 Subject: [PATCH] Fix a "data too small" error in PasswordBasedEncryption Found during the Unix PFX reader/writer work, but wasn't directly relevant to that change. Commit migrated from https://github.com/dotnet/corefx/commit/2d713265d5aecd5fe34099042e13fe7ba54dcdd1 --- .../Cryptography/PasswordBasedEncryption.cs | 17 ++++++++----- .../tests/Pkcs12/Pkcs12BuilderTests.cs | 28 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 6 deletions(-) diff --git a/src/libraries/Common/src/System/Security/Cryptography/PasswordBasedEncryption.cs b/src/libraries/Common/src/System/Security/Cryptography/PasswordBasedEncryption.cs index 44732d8..c5af8f1 100644 --- a/src/libraries/Common/src/System/Security/Cryptography/PasswordBasedEncryption.cs +++ b/src/libraries/Common/src/System/Security/Cryptography/PasswordBasedEncryption.cs @@ -398,12 +398,17 @@ namespace System.Security.Cryptography { source.CopyTo(sourceRent); - int written = encryptor.TransformBlock( - sourceRent, - 0, - fullBlocksLength, - destination, - 0); + int written = 0; + + if (fullBlocksLength != 0) + { + written = encryptor.TransformBlock( + sourceRent, + 0, + fullBlocksLength, + destination, + 0); + } byte[] lastBlock = encryptor.TransformFinalBlock( sourceRent, diff --git a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/Pkcs12BuilderTests.cs b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/Pkcs12BuilderTests.cs index a829c25..e963142 100644 --- a/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/Pkcs12BuilderTests.cs +++ b/src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/Pkcs12BuilderTests.cs @@ -481,5 +481,33 @@ namespace System.Security.Cryptography.Pkcs.Tests.Pkcs12 Assert.Equal(3 + encode1.Length, encode2.Length); } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public static void BuildWithEmptySafeContents(bool encrypted) + { + string pw = nameof(BuildWithEmptySafeContents); + + Pkcs12Builder builder = new Pkcs12Builder(); + Pkcs12SafeContents empty = new Pkcs12SafeContents(); + + if (encrypted) + { + builder.AddSafeContentsEncrypted(empty, pw, s_win7Pbe); + } + else + { + builder.AddSafeContentsUnencrypted(empty); + } + + builder.SealWithMac(pw, HashAlgorithmName.SHA1, 1); + byte[] pfxBytes = builder.Encode(); + + X509Certificate2Collection coll = new X509Certificate2Collection(); + coll.Import(pfxBytes, pw, default); + + Assert.Equal(0, coll.Count); + } } } -- 2.7.4