Skip to content

Commit 9bbcfff

Browse files
committed
Use TryFromBase64Chars and stack-allocated buffers if possible.
1 parent e789e70 commit 9bbcfff

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/MySqlConnector/Utilities/Utility.cs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Buffers;
23
using System.Buffers.Text;
34
using System.Diagnostics.CodeAnalysis;
45
using System.Globalization;
@@ -116,9 +117,31 @@ public static RSAParameters GetRsaParameters(string key)
116117
if (keyEndIndex <= -1)
117118
throw new FormatException($"Missing expected '{pemFooter}' PEM footer: " + key.Substring(Math.Max(key.Length - 80, 0)));
118119

120+
#if NET45 || NET461 || NET471 || NETSTANDARD1_3 || NETSTANDARD2_0
119121
key = key.Substring(keyStartIndex, keyEndIndex - keyStartIndex);
120-
121122
return GetRsaParameters(System.Convert.FromBase64String(key), isPrivate);
123+
#else
124+
var keyChars = key.AsSpan().Slice(keyStartIndex, keyEndIndex - keyStartIndex);
125+
var bufferLength = keyChars.Length / 4 * 3;
126+
byte[]? buffer = null;
127+
Span<byte> bufferBytes = bufferLength <= 1024 ? stackalloc byte[bufferLength] : default;
128+
if (bufferLength > 1024)
129+
{
130+
buffer = ArrayPool<byte>.Shared.Rent(bufferLength);
131+
bufferBytes = buffer.AsSpan();
132+
}
133+
try
134+
{
135+
if (!System.Convert.TryFromBase64Chars(keyChars, bufferBytes, out var bytesWritten))
136+
throw new FormatException("The input is not a valid Base-64 string.");
137+
return GetRsaParameters(bufferBytes.Slice(0, bytesWritten), isPrivate);
138+
}
139+
finally
140+
{
141+
if (buffer is not null)
142+
ArrayPool<byte>.Shared.Return(buffer);
143+
}
144+
#endif
122145
}
123146

124147
// Derived from: https://stackoverflow.com/a/32243171/, https://stackoverflow.com/a/26978561/, http://luca.ntop.org/Teaching/Appunti/asn1.html

0 commit comments

Comments
 (0)