summary refs log tree commit diff
diff options
context:
space:
mode:
authorPeter Dettman <peter.dettman@bouncycastle.org>2023-04-11 18:33:01 +0700
committerPeter Dettman <peter.dettman@bouncycastle.org>2023-04-11 18:33:01 +0700
commitdb4e4f5a6ff5348cb6279baa997e361b6c47fcbb (patch)
treeac84d5387f10063922cdcf273b11d5bd5b7d07ca
parentAdd Memory/Span accessors to avoid some copies (diff)
downloadBouncyCastle.NET-ed25519-db4e4f5a6ff5348cb6279baa997e361b6c47fcbb.tar.xz
Reduce allocations in hex encoding
-rw-r--r--crypto/src/openssl/MiscPemGenerator.cs4
-rw-r--r--crypto/src/util/encoders/Hex.cs60
-rw-r--r--crypto/src/util/encoders/HexEncoder.cs39
3 files changed, 93 insertions, 10 deletions
diff --git a/crypto/src/openssl/MiscPemGenerator.cs b/crypto/src/openssl/MiscPemGenerator.cs
index cfbb5e96d..75d1e65b3 100644
--- a/crypto/src/openssl/MiscPemGenerator.cs
+++ b/crypto/src/openssl/MiscPemGenerator.cs
@@ -189,7 +189,7 @@ namespace Org.BouncyCastle.OpenSsl
 
             var headers = new List<PemHeader>(2);
             headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
-            headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv).ToUpperInvariant()));
+            headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv, true)));
 
             return new PemObject(type, headers, encData);
         }
@@ -249,7 +249,7 @@ namespace Org.BouncyCastle.OpenSsl
 
             var headers = new List<PemHeader>(2);
             headers.Add(new PemHeader("Proc-Type", "4,ENCRYPTED"));
-            headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv).ToUpperInvariant()));
+            headers.Add(new PemHeader("DEK-Info", dekAlgName + "," + Hex.ToHexString(iv, true)));
 
             return new PemObject(type, headers, encData);
         }
diff --git a/crypto/src/util/encoders/Hex.cs b/crypto/src/util/encoders/Hex.cs
index 0b2a48995..644b318e0 100644
--- a/crypto/src/util/encoders/Hex.cs
+++ b/crypto/src/util/encoders/Hex.cs
@@ -1,4 +1,5 @@
 using System;
+using System.Diagnostics;
 using System.IO;
 
 namespace Org.BouncyCastle.Utilities.Encoders
@@ -6,6 +7,7 @@ namespace Org.BouncyCastle.Utilities.Encoders
     /// <summary>
     /// Class to decode and encode Hex.
     /// </summary>
+    // TODO[api] Make static
     public sealed class Hex
     {
         private static readonly HexEncoder encoder = new HexEncoder();
@@ -14,20 +16,62 @@ namespace Org.BouncyCastle.Utilities.Encoders
         {
         }
 
-        public static string ToHexString(
-            byte[] data)
+        public static string ToHexString(byte[] data)
         {
-            return ToHexString(data, 0, data.Length);
+            return ToHexString(data, false);
         }
 
-        public static string ToHexString(
-            byte[]	data,
-            int		off,
-            int		length)
+        public static string ToHexString(byte[] data, bool upperCase)
+        {
+            return ToHexString(data, 0, data.Length, upperCase);
+        }
+
+        public static string ToHexString(byte[]	data, int off, int length)
         {
+            return ToHexString(data, off, length, false);
+        }
+
+        public static string ToHexString(byte[] data, int off, int length, bool upperCase)
+        {
+#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
+            return ToHexString(data.AsMemory(off, length), upperCase);
+#else
             byte[] hex = Encode(data, off, length);
-            return Strings.FromAsciiByteArray(hex);
+            var result = Strings.FromAsciiByteArray(hex);
+            if (upperCase)
+            {
+                result = result.ToUpperInvariant();
+            }
+            return result;
+#endif
+        }
+
+#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
+        public static string ToHexString(ReadOnlyMemory<byte> data, bool upperCase = false)
+        {
+            if (data.Length == 0)
+                return string.Empty;
+            if (data.Length > int.MaxValue / 2)
+                throw new ArgumentOutOfRangeException(nameof(data));
+
+            if (upperCase)
+            {
+                return string.Create(data.Length * 2, data, (chars, data) =>
+                {
+                    int length = HexEncoder.EncodeUpper(data.Span, chars);
+                    Debug.Assert(chars.Length == length);
+                });
+            }
+            else
+            {
+                return string.Create(data.Length * 2, data, (chars, data) =>
+                {
+                    int length = HexEncoder.EncodeLower(data.Span, chars);
+                    Debug.Assert(chars.Length == length);
+                });
+            }
         }
+#endif
 
         /**
          * encode the input data producing a Hex encoded byte array.
diff --git a/crypto/src/util/encoders/HexEncoder.cs b/crypto/src/util/encoders/HexEncoder.cs
index a36f31dbd..05933af05 100644
--- a/crypto/src/util/encoders/HexEncoder.cs
+++ b/crypto/src/util/encoders/HexEncoder.cs
@@ -6,6 +6,45 @@ namespace Org.BouncyCastle.Utilities.Encoders
     public class HexEncoder
         : IEncoder
     {
+        private static readonly char[] CharsLower = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
+        private static readonly char[] CharsUpper = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+
+#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
+        internal static int EncodeLower(ReadOnlySpan<byte> input, Span<char> output)
+        {
+            int inPos = 0;
+            int inEnd = input.Length;
+            int outPos = 0;
+
+            while (inPos < inEnd)
+            {
+                uint b = input[inPos++];
+
+                output[outPos++] = CharsLower[b >> 4];
+                output[outPos++] = CharsLower[b & 0xF];
+            }
+
+            return outPos;
+        }
+
+        internal static int EncodeUpper(ReadOnlySpan<byte> input, Span<char> output)
+        {
+            int inPos = 0;
+            int inEnd = input.Length;
+            int outPos = 0;
+
+            while (inPos < inEnd)
+            {
+                uint b = input[inPos++];
+
+                output[outPos++] = CharsUpper[b >> 4];
+                output[outPos++] = CharsUpper[b & 0xF];
+            }
+
+            return outPos;
+        }
+#endif
+
         protected readonly byte[] encodingTable =
         {
             (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',