|
1 | 1 | using System;
|
| 2 | +using System.Buffers; |
2 | 3 | using System.Buffers.Text;
|
3 | 4 | using System.Diagnostics.CodeAnalysis;
|
4 | 5 | using System.Globalization;
|
@@ -116,9 +117,31 @@ public static RSAParameters GetRsaParameters(string key)
|
116 | 117 | if (keyEndIndex <= -1)
|
117 | 118 | throw new FormatException($"Missing expected '{pemFooter}' PEM footer: " + key.Substring(Math.Max(key.Length - 80, 0)));
|
118 | 119 |
|
| 120 | +#if NET45 || NET461 || NET471 || NETSTANDARD1_3 || NETSTANDARD2_0 |
119 | 121 | key = key.Substring(keyStartIndex, keyEndIndex - keyStartIndex);
|
120 |
| - |
121 | 122 | 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 |
122 | 145 | }
|
123 | 146 |
|
124 | 147 | // Derived from: https://stackoverflow.com/a/32243171/, https://stackoverflow.com/a/26978561/, http://luca.ntop.org/Teaching/Appunti/asn1.html
|
|
0 commit comments