Skip to content

Commit 4ba9742

Browse files
committed
Use PemEncoding in .NET 5 and later.
This prepares the way to use the new methods that will be added in .NET 10.
1 parent a78c668 commit 4ba9742

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

src/MySqlConnector/Utilities/Utility.cs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,11 @@ public static void LoadRsaParameters(string key, RSA rsa)
9797
public static RSAParameters GetRsaParameters(string key)
9898
#endif
9999
{
100+
#if NET5_0_OR_GREATER
101+
if (!PemEncoding.TryFind(key, out var pemFields))
102+
throw new FormatException(string.Concat("Unrecognized PEM data: ", key.AsSpan(0, Math.Min(key.Length, 80))));
103+
var isPrivate = key.AsSpan()[pemFields.Label].SequenceEqual("RSA PRIVATE KEY");
104+
#else
100105
const string beginRsaPrivateKey = "-----BEGIN RSA PRIVATE KEY-----";
101106
const string endRsaPrivateKey = "-----END RSA PRIVATE KEY-----";
102107
const string beginPublicKey = "-----BEGIN PUBLIC KEY-----";
@@ -135,9 +140,14 @@ public static RSAParameters GetRsaParameters(string key)
135140
#else
136141
throw new FormatException($"Missing expected '{pemFooter}' PEM footer: " + key[Math.Max(key.Length - 80, 0)..]);
137142
#endif
143+
#endif
138144

139145
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
146+
#if NET5_0_OR_GREATER
147+
var keyChars = key.AsSpan()[pemFields.Base64Data];
148+
#else
140149
var keyChars = key.AsSpan()[keyStartIndex..keyEndIndex];
150+
#endif
141151
var bufferLength = keyChars.Length / 4 * 3;
142152
byte[]? buffer = null;
143153
Span<byte> bufferBytes = bufferLength > 1024 ?

tests/MySqlConnector.Tests/UtilityTests.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,9 @@ public void ParseTimeSpanFails(string input)
8787

8888
[Theory]
8989
[InlineData("", "")]
90-
[InlineData("pre", "")]
91-
[InlineData("", "post")]
92-
[InlineData("pre", "post")]
90+
[InlineData("pre\n", "")]
91+
[InlineData("", "\npost")]
92+
[InlineData("pre\n", "\npost")]
9393
public void DecodePublicKey(string pre, string post)
9494
{
9595
#if NET5_0_OR_GREATER
@@ -105,9 +105,9 @@ public void DecodePublicKey(string pre, string post)
105105

106106
[Theory]
107107
[InlineData("", "")]
108-
[InlineData("pre", "")]
109-
[InlineData("", "post")]
110-
[InlineData("pre", "post")]
108+
[InlineData("pre\n", "")]
109+
[InlineData("", "\npost")]
110+
[InlineData("pre\n", "\npost")]
111111
public void DecodePrivateKey(string pre, string post)
112112
{
113113
#if NET5_0_OR_GREATER

0 commit comments

Comments
 (0)