Fix a "data too small" error in PasswordBasedEncryption
authorJeremy Barton <jbarton@microsoft.com>
Mon, 11 Nov 2019 20:52:44 +0000 (12:52 -0800)
committerGitHub <noreply@github.com>
Mon, 11 Nov 2019 20:52:44 +0000 (12:52 -0800)
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

src/libraries/Common/src/System/Security/Cryptography/PasswordBasedEncryption.cs
src/libraries/System.Security.Cryptography.Pkcs/tests/Pkcs12/Pkcs12BuilderTests.cs

index 44732d8..c5af8f1 100644 (file)
@@ -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,
index a829c25..e963142 100644 (file)
@@ -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);
+        }
     }
 }