Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change iOS PEM searcher to use PemEncoding.TryFindUtf8 #109564

Merged
merged 3 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,8 @@ internal static class PemLabels
internal const string Pkcs7Certificate = "PKCS7";
internal const string X509CertificateRevocationList = "X509 CRL";
internal const string Pkcs10CertificateRequest = "CERTIFICATE REQUEST";

internal static ReadOnlySpan<byte> X509CertificateUtf8 => "CERTIFICATE"u8;
internal static ReadOnlySpan<byte> Pkcs7CertificateUtf8 => "PKCS7"u8;
}
}
Original file line number Diff line number Diff line change
@@ -1,54 +1,63 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Diagnostics;
using System.Security.Cryptography;

namespace System.Security.Cryptography
{
internal readonly ref struct PemEnumerator
internal static class PemEnumerator
{
private readonly ReadOnlySpan<char> _contents;
internal static PemEnumerator<char> Utf16(ReadOnlySpan<char> pemData)
{
return new PemEnumerator<char>(pemData, PemEncoding.TryFind);
}

public PemEnumerator(ReadOnlySpan<char> contents)
internal static PemEnumerator<byte> Utf8(ReadOnlySpan<byte> pemData)
{
return new PemEnumerator<byte>(pemData, PemEncoding.TryFindUtf8);
}
}

internal readonly ref struct PemEnumerator<TChar>
{
internal delegate bool TryFindFunc(ReadOnlySpan<TChar> pemData, out PemFields fields);

private readonly ReadOnlySpan<TChar> _contents;
private readonly TryFindFunc _tryFindFunc;

internal PemEnumerator(ReadOnlySpan<TChar> contents, TryFindFunc findFunc)
{
_contents = contents;
_tryFindFunc = findFunc;
}

public Enumerator GetEnumerator() => new Enumerator(_contents);
public Enumerator GetEnumerator() => new Enumerator(_contents, _tryFindFunc);

internal ref struct Enumerator
{
private ReadOnlySpan<char> _contents;
private ReadOnlySpan<TChar> _contents;
private PemFields _pemFields;
private readonly TryFindFunc _tryFindFunc;

public Enumerator(ReadOnlySpan<char> contents)
internal Enumerator(ReadOnlySpan<TChar> contents, TryFindFunc tryFindFunc)
{
_contents = contents;
_pemFields = default;
_tryFindFunc = tryFindFunc;
}

public PemFieldItem Current => new PemFieldItem(_contents, _pemFields);
public readonly PemFieldItem Current => new PemFieldItem(_contents, _pemFields);

public bool MoveNext()
{
_contents = _contents[_pemFields.Location.End..];
return PemEncoding.TryFind(_contents, out _pemFields);
return _tryFindFunc(_contents, out _pemFields);
}

internal readonly ref struct PemFieldItem
internal readonly ref struct PemFieldItem(ReadOnlySpan<TChar> contents, PemFields pemFields)
{
private readonly ReadOnlySpan<char> _contents;
private readonly PemFields _pemFields;

public PemFieldItem(ReadOnlySpan<char> contents, PemFields pemFields)
{
_contents = contents;
_pemFields = pemFields;
}
private readonly ReadOnlySpan<TChar> _contents = contents;
private readonly PemFields _pemFields = pemFields;

public void Deconstruct(out ReadOnlySpan<char> contents, out PemFields pemFields)
public void Deconstruct(out ReadOnlySpan<TChar> contents, out PemFields pemFields)
{
contents = _contents;
pemFields = _pemFields;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,59 +2,48 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Buffers;
using System.Buffers.Text;
using System.Diagnostics;
using System.Text;
using Internal.Cryptography;

namespace System.Security.Cryptography.X509Certificates
{
internal sealed partial class AppleCertificatePal : ICertificatePal
{
internal delegate bool DerCallback(ReadOnlySpan<byte> derData, X509ContentType contentType);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need a dedicated delegate anymore with allows ref struct on Func now, so use Func.


internal static bool TryDecodePem(ReadOnlySpan<byte> rawData, DerCallback derCallback)
internal static void TryDecodePem(ReadOnlySpan<byte> rawData, Func<ReadOnlySpan<byte>, X509ContentType, bool> derCallback)
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The return value from this method was always ignored and seemed to have no purpose any more. So it became void.

{
// If the character is a control character that isn't whitespace, then we're probably using a DER encoding
// and not using a PEM encoding in ASCII.
// and not using a PEM encoding in UTF8.
if (char.IsControl((char)rawData[0]) && !char.IsWhiteSpace((char)rawData[0]))
{
return false;
}

// Look for the PEM marker. This doesn't guarantee it will be a valid PEM since we don't check whether
// the marker is at the beginning of line or whether the line is a complete marker. It's just a quick
// check to avoid conversion from bytes to characters if the content is DER encoded.
if (rawData.IndexOf("-----BEGIN "u8) < 0)
{
return false;
return;
}

char[] certPem = ArrayPool<char>.Shared.Rent(rawData.Length);
byte[]? certBytes = null;

try
{
Encoding.ASCII.GetChars(rawData, certPem);

foreach ((ReadOnlySpan<char> contents, PemFields fields) in new PemEnumerator(certPem.AsSpan(0, rawData.Length)))
foreach ((ReadOnlySpan<byte> contents, PemFields fields) in PemEnumerator.Utf8(rawData))
{
ReadOnlySpan<char> label = contents[fields.Label];
ReadOnlySpan<byte> label = contents[fields.Label];
bool isCertificate = label.SequenceEqual(PemLabels.X509CertificateUtf8);

if (label.SequenceEqual(PemLabels.X509Certificate) || label.SequenceEqual(PemLabels.Pkcs7Certificate))
if (isCertificate || label.SequenceEqual(PemLabels.Pkcs7CertificateUtf8))
{
certBytes = CryptoPool.Rent(fields.DecodedDataLength);

if (!Convert.TryFromBase64Chars(contents[fields.Base64Data], certBytes, out int bytesWritten)
|| bytesWritten != fields.DecodedDataLength)
OperationStatus decodeResult = Base64.DecodeFromUtf8(
contents[fields.Base64Data],
certBytes,
out _,
out int bytesWritten);

if (decodeResult != OperationStatus.Done || bytesWritten != fields.DecodedDataLength)
{
Debug.Fail("The contents should have already been validated by the PEM reader.");
throw new CryptographicException(SR.Cryptography_X509_NoPemCertificate);
}

X509ContentType contentType =
label.SequenceEqual(PemLabels.X509Certificate) ?
X509ContentType.Cert :
X509ContentType.Pkcs7;
X509ContentType contentType = isCertificate ? X509ContentType.Cert : X509ContentType.Pkcs7;
bool cont = derCallback(certBytes.AsSpan(0, bytesWritten), contentType);

byte[] toReturn = certBytes;
Expand All @@ -63,22 +52,18 @@ internal static bool TryDecodePem(ReadOnlySpan<byte> rawData, DerCallback derCal

if (!cont)
{
return true;
return;
}
}
}
}
finally
{
ArrayPool<char>.Shared.Return(certPem, clearArray: true);

if (certBytes != null)
{
CryptoPool.Return(certBytes, clearSize: 0);
}
}

return true;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public static CertificateRequest LoadSigningRequestPem(
throw new ArgumentOutOfRangeException(nameof(options), options, SR.Argument_InvalidFlag);
}

foreach ((ReadOnlySpan<char> contents, PemFields fields) in new PemEnumerator(pkcs10Pem))
foreach ((ReadOnlySpan<char> contents, PemFields fields) in PemEnumerator.Utf16(pkcs10Pem))
{
if (contents[fields.Label].SequenceEqual(PemLabels.Pkcs10CertificateRequest))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ public static CertificateRevocationListBuilder LoadPem(string currentCrl, out Bi
/// </exception>
public static CertificateRevocationListBuilder LoadPem(ReadOnlySpan<char> currentCrl, out BigInteger currentCrlNumber)
{
foreach ((ReadOnlySpan<char> contents, PemFields fields) in new PemEnumerator(currentCrl))
foreach ((ReadOnlySpan<char> contents, PemFields fields) in PemEnumerator.Utf16(currentCrl))
{
if (contents[fields.Label].SequenceEqual(PemLabels.X509CertificateRevocationList))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1080,7 +1080,7 @@ private static bool IsECDiffieHellman(X509Certificate2 certificate)
[UnsupportedOSPlatform("browser")]
public static X509Certificate2 CreateFromPem(ReadOnlySpan<char> certPem)
{
foreach ((ReadOnlySpan<char> contents, PemFields fields) in new PemEnumerator(certPem))
foreach ((ReadOnlySpan<char> contents, PemFields fields) in PemEnumerator.Utf16(certPem))
{
ReadOnlySpan<char> label = contents[fields.Label];

Expand Down Expand Up @@ -1432,7 +1432,7 @@ private static X509Certificate2 ExtractKeyFromPem<TAlg>(
Func<TAlg> factory,
Func<TAlg, X509Certificate2> import) where TAlg : AsymmetricAlgorithm
{
foreach ((ReadOnlySpan<char> contents, PemFields fields) in new PemEnumerator(keyPem))
foreach ((ReadOnlySpan<char> contents, PemFields fields) in PemEnumerator.Utf16(keyPem))
{
ReadOnlySpan<char> label = contents[fields.Label];

Expand Down Expand Up @@ -1466,7 +1466,7 @@ private static X509Certificate2 ExtractKeyFromEncryptedPem<TAlg>(
Func<TAlg> factory,
Func<TAlg, X509Certificate2> import) where TAlg : AsymmetricAlgorithm
{
foreach ((ReadOnlySpan<char> contents, PemFields fields) in new PemEnumerator(keyPem))
foreach ((ReadOnlySpan<char> contents, PemFields fields) in PemEnumerator.Utf16(keyPem))
{
ReadOnlySpan<char> label = contents[fields.Label];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ public void ImportFromPem(ReadOnlySpan<char> certPem)

try
{
foreach ((ReadOnlySpan<char> contents, PemFields fields) in new PemEnumerator(certPem))
foreach ((ReadOnlySpan<char> contents, PemFields fields) in PemEnumerator.Utf16(certPem))
{
ReadOnlySpan<char> label = contents[fields.Label];

Expand Down
Loading