Skip to content

Commit

Permalink
Use PemEncoding in .NET 5 and later.
Browse files Browse the repository at this point in the history
This prepares the way to use the new methods that will be added in .NET 10.
  • Loading branch information
bgrainger committed Feb 26, 2025
1 parent a78c668 commit 4ba9742
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
10 changes: 10 additions & 0 deletions src/MySqlConnector/Utilities/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ public static void LoadRsaParameters(string key, RSA rsa)
public static RSAParameters GetRsaParameters(string key)
#endif
{
#if NET5_0_OR_GREATER
if (!PemEncoding.TryFind(key, out var pemFields))
throw new FormatException(string.Concat("Unrecognized PEM data: ", key.AsSpan(0, Math.Min(key.Length, 80))));
var isPrivate = key.AsSpan()[pemFields.Label].SequenceEqual("RSA PRIVATE KEY");
#else
const string beginRsaPrivateKey = "-----BEGIN RSA PRIVATE KEY-----";
const string endRsaPrivateKey = "-----END RSA PRIVATE KEY-----";
const string beginPublicKey = "-----BEGIN PUBLIC KEY-----";
Expand Down Expand Up @@ -135,9 +140,14 @@ public static RSAParameters GetRsaParameters(string key)
#else
throw new FormatException($"Missing expected '{pemFooter}' PEM footer: " + key[Math.Max(key.Length - 80, 0)..]);
#endif
#endif

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
#if NET5_0_OR_GREATER
var keyChars = key.AsSpan()[pemFields.Base64Data];
#else
var keyChars = key.AsSpan()[keyStartIndex..keyEndIndex];
#endif
var bufferLength = keyChars.Length / 4 * 3;
byte[]? buffer = null;
Span<byte> bufferBytes = bufferLength > 1024 ?
Expand Down
12 changes: 6 additions & 6 deletions tests/MySqlConnector.Tests/UtilityTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ public void ParseTimeSpanFails(string input)

[Theory]
[InlineData("", "")]
[InlineData("pre", "")]
[InlineData("", "post")]
[InlineData("pre", "post")]
[InlineData("pre\n", "")]
[InlineData("", "\npost")]
[InlineData("pre\n", "\npost")]
public void DecodePublicKey(string pre, string post)
{
#if NET5_0_OR_GREATER
Expand All @@ -105,9 +105,9 @@ public void DecodePublicKey(string pre, string post)

[Theory]
[InlineData("", "")]
[InlineData("pre", "")]
[InlineData("", "post")]
[InlineData("pre", "post")]
[InlineData("pre\n", "")]
[InlineData("", "\npost")]
[InlineData("pre\n", "\npost")]
public void DecodePrivateKey(string pre, string post)
{
#if NET5_0_OR_GREATER
Expand Down

0 comments on commit 4ba9742

Please sign in to comment.