Remove a few initialization allocations from Cng (dotnet/corefx#41373)
authorStephen Toub <stoub@microsoft.com>
Fri, 27 Sep 2019 03:22:52 +0000 (20:22 -0700)
committerGitHub <noreply@github.com>
Fri, 27 Sep 2019 03:22:52 +0000 (20:22 -0700)
Save four "startup" allocations in System.Security.Cryptography.Cng.

- Appending the '\0' is better done at the call site, because then the concat is done with two constants at compile time.
- There's no benefit to using ToCharArray instead of just passing in the string.
- Once we get rid of those, we can just inline the construction into the declarations.

Commit migrated from https://github.com/dotnet/corefx/commit/296c0e71ddcc4885d30af18dea829c1923cfdc5c

src/libraries/System.Security.Cryptography.Cng/src/Internal/Cryptography/BasicSymmetricCipherNCrypt.cs

index d972efa..b3f443d 100644 (file)
@@ -120,16 +120,12 @@ namespace Internal.Cryptography
             }
         }
 
-        private static CngProperty CreateCngPropertyForCipherMode(string cipherMode)
-        {
-            byte[] cipherModeBytes = Encoding.Unicode.GetBytes((cipherMode + "\0").ToCharArray());
-            return new CngProperty(Interop.NCrypt.NCRYPT_CHAINING_MODE_PROPERTY, cipherModeBytes, CngPropertyOptions.None);
-        }
-
         private CngKey _cngKey;
         private readonly bool _encrypting;
 
-        private static readonly CngProperty s_ECBMode = CreateCngPropertyForCipherMode(Interop.BCrypt.BCRYPT_CHAIN_MODE_ECB);
-        private static readonly CngProperty s_CBCMode = CreateCngPropertyForCipherMode(Interop.BCrypt.BCRYPT_CHAIN_MODE_CBC);
+        private static readonly CngProperty s_ECBMode =
+            new CngProperty(Interop.NCrypt.NCRYPT_CHAINING_MODE_PROPERTY, Encoding.UTF8.GetBytes(Interop.BCrypt.BCRYPT_CHAIN_MODE_ECB + "\0"), CngPropertyOptions.None);
+        private static readonly CngProperty s_CBCMode =
+            new CngProperty(Interop.NCrypt.NCRYPT_CHAINING_MODE_PROPERTY, Encoding.UTF8.GetBytes(Interop.BCrypt.BCRYPT_CHAIN_MODE_CBC + "\0"), CngPropertyOptions.None);
     }
 }