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

Use key services and data keys where possible for faster EC operations. #38101

Closed
wants to merge 1 commit into from
Closed
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
@@ -0,0 +1,53 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

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

namespace Internal.Cryptography
{
internal static partial class AsymmetricAlgorithmHelpers
{
// Encodes a EC key as an uncompressed set of concatenated scalars,
// optionally including the private key. To omit the private parameter,
// "d" must have a length of zero.
public static (Range PublicKey, Range? PrivateKey) EncodeToUncompressedAnsiX963Key(
ReadOnlySpan<byte> x,
ReadOnlySpan<byte> y,
ReadOnlySpan<byte> d,
Span<byte> destination)
{
const byte UncompressedKeyPrefix = 0x04;
if (x.Length != y.Length || (d.Length > 0 && d.Length != y.Length))
throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey);

int size = 1 + x.Length + y.Length + d.Length; // 0x04 || X || Y { || D }

if (destination.Length < size)
{
Debug.Fail("destination.Length < size");
throw new CryptographicException();
}

destination[0] = UncompressedKeyPrefix;
x.CopyTo(destination.Slice(1));
y.CopyTo(destination.Slice(1 + x.Length));
Range publicKey = 0..(1 + x.Length + y.Length);
Range? privateKey;

if (d.Length > 0)
{
d.CopyTo(destination[publicKey.End..]);
privateKey = 0..size;
}
else
{
privateKey = null;
}

return (publicKey, privateKey);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.Apple;

internal static partial class Interop
{
internal static partial class AppleCrypto
{
internal enum PAL_KeyAlgorithm : uint
{
Unknown = 0,
EC = 1,
RSA = 2,
}

internal enum PAL_SignatureAlgorithm : uint
{
Unknown = 0,
RsaPkcs1 = 1,
EC = 2,
DSA = 3
}

internal static unsafe SafeSecKeyRefHandle CreateDataKey(
ReadOnlySpan<byte> keyData,
int keySizeInBits,
PAL_KeyAlgorithm keyAlgorithm,
bool isPublic)
{
fixed (byte* pKey = keyData)
{
int result = AppleCryptoNative_CreateDataKey(
pKey,
keyData.Length,
keySizeInBits,
keyAlgorithm,
isPublic ? 1 : 0,
out SafeSecKeyRefHandle dataKey,
out SafeCFErrorHandle errorHandle);

using (errorHandle)
{
const int Success = 1;
const int kErrorSeeError = -2;

return result switch
{
Success => dataKey,
kErrorSeeError => throw CreateExceptionForCFError(errorHandle),
_ => throw new CryptographicException { HResult = result }
Copy link
Member

Choose a reason for hiding this comment

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

The unexpected error codes should Debug.Fail, then probably just throw a default CryptographicException (consistency with the existing paths).

};
}
}
}

internal static bool KeyServicesVerifySignature(
SafeSecKeyRefHandle publicKey,
ReadOnlySpan<byte> dataHash,
ReadOnlySpan<byte> signature,
PAL_HashAlgorithm hashAlgorithm,
PAL_SignatureAlgorithm signatureAlgorithm,
bool digest)
{
const int Valid = 1;
const int Invalid = 0;
const int kErrorSeeError = -2;

int result = AppleCryptoNative_SecKeyVerifySignature(
publicKey,
dataHash,
signature,
hashAlgorithm,
signatureAlgorithm,
digest,
out SafeCFErrorHandle errorHandle);

using (errorHandle)
{
return result switch
{
Valid => true,
Invalid => false,
kErrorSeeError => throw CreateExceptionForCFError(errorHandle),
_ => throw new CryptographicException { HResult = result }
};
}
}

internal static byte[] KeyServicesCreateSignature(
SafeSecKeyRefHandle privateKey,
ReadOnlySpan<byte> dataHash,
PAL_HashAlgorithm hashAlgorithm,
PAL_SignatureAlgorithm signatureAlgorithm,
bool digest)
{
const int Success = 1;
const int kErrorSeeError = -2;

int result = AppleCryptoNative_SecKeyCreateSignature(
privateKey,
dataHash,
hashAlgorithm,
signatureAlgorithm,
digest,
out SafeCFDataHandle signature,
out SafeCFErrorHandle errorHandle);

using (errorHandle)
using (signature)
{
return result switch
{
Success => CoreFoundation.CFGetData(signature),
kErrorSeeError => throw CreateExceptionForCFError(errorHandle),
_ => throw new CryptographicException { HResult = result }
};
}
}

[DllImport(Libraries.AppleCryptoNative)]
private static unsafe extern int AppleCryptoNative_CreateDataKey(
byte* pKey,
int cbKey,
int keySizeInBits,
PAL_KeyAlgorithm keyAlgorithm,
int isPublic,
out SafeSecKeyRefHandle pDataKey,
out SafeCFErrorHandle pErrorOut);

private static unsafe int AppleCryptoNative_SecKeyVerifySignature(
SafeSecKeyRefHandle publicKey,
ReadOnlySpan<byte> dataHash,
ReadOnlySpan<byte> signature,
PAL_HashAlgorithm hashAlgorithm,
PAL_SignatureAlgorithm signatureAlgorithm,
bool digest,
out SafeCFErrorHandle pErrorOut)
{
fixed (byte* pDataHash = dataHash)
fixed (byte* pSignature = signature)
{
return AppleCryptoNative_SecKeyVerifySignature(
publicKey,
pDataHash,
dataHash.Length,
pSignature,
signature.Length,
hashAlgorithm,
signatureAlgorithm,
digest ? 1 : 0,
out pErrorOut);
}
}

[DllImport(Libraries.AppleCryptoNative)]
private static unsafe extern int AppleCryptoNative_SecKeyVerifySignature(
SafeSecKeyRefHandle publicKey,
byte* pbDataHash,
int cbDataHash,
byte* pbSignature,
int cbSignature,
PAL_HashAlgorithm hashAlgorithm,
PAL_SignatureAlgorithm signatureAlgorithm,
int digest,
out SafeCFErrorHandle pErrorOut);

private static unsafe int AppleCryptoNative_SecKeyCreateSignature(
SafeSecKeyRefHandle privateKey,
ReadOnlySpan<byte> dataHash,
PAL_HashAlgorithm hashAlgorithm,
PAL_SignatureAlgorithm signatureAlgorithm,
bool digest,
out SafeCFDataHandle pSignatureOut,
out SafeCFErrorHandle pErrorOut)
{
fixed (byte* pDataHash = dataHash)
{
return AppleCryptoNative_SecKeyCreateSignature(
privateKey,
pDataHash,
dataHash.Length,
hashAlgorithm,
signatureAlgorithm,
digest ? 1 : 0,
out pSignatureOut,
out pErrorOut);
}
}

[DllImport(Libraries.AppleCryptoNative)]
private static unsafe extern int AppleCryptoNative_SecKeyCreateSignature(
SafeSecKeyRefHandle privateKey,
byte* pbDataHash,
int cbDataHash,
PAL_HashAlgorithm hashAlgorithm,
PAL_SignatureAlgorithm signatureAlgorithm,
int digest,
out SafeCFDataHandle pSignatureOut,
out SafeCFErrorHandle pErrorOut);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System.IO;
using System.Diagnostics;
using System.Security.Cryptography.Apple;
using Internal.Cryptography;

Expand Down Expand Up @@ -107,7 +108,22 @@ public override byte[] SignHash(byte[] hash)
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}

byte[] derFormatSignature = Interop.AppleCrypto.GenerateSignature(keys.PrivateKey, hash);
byte[] derFormatSignature;

if (keys.PrivateDataKey != null)
{
derFormatSignature = Interop.AppleCrypto.KeyServicesCreateSignature(
keys.PrivateDataKey,
hash,
Interop.AppleCrypto.PAL_HashAlgorithm.Unknown,
Interop.AppleCrypto.PAL_SignatureAlgorithm.EC,
digest: true);
}
else
{
derFormatSignature = Interop.AppleCrypto.GenerateSignature(keys.PrivateKey, hash);
}

byte[] ieeeFormatSignature = AsymmetricAlgorithmHelpers.ConvertDerToIeee1363(
derFormatSignature.AsSpan(0, derFormatSignature.Length),
KeySize);
Expand All @@ -123,7 +139,22 @@ public override bool TrySignHash(ReadOnlySpan<byte> source, Span<byte> destinati
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
}

byte[] derFormatSignature = Interop.AppleCrypto.GenerateSignature(keys.PrivateKey, source);
byte[] derFormatSignature;

if (keys.PrivateDataKey != null)
{
derFormatSignature = Interop.AppleCrypto.KeyServicesCreateSignature(
keys.PrivateDataKey,
source,
Interop.AppleCrypto.PAL_HashAlgorithm.Unknown,
Interop.AppleCrypto.PAL_SignatureAlgorithm.EC,
digest: true);
}
else
{
derFormatSignature = Interop.AppleCrypto.GenerateSignature(keys.PrivateKey, source);
}

byte[] ieeeFormatSignature = AsymmetricAlgorithmHelpers.ConvertDerToIeee1363(
derFormatSignature.AsSpan(0, derFormatSignature.Length),
KeySize);
Expand Down Expand Up @@ -165,10 +196,26 @@ public override bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> sign
return false;
}

return Interop.AppleCrypto.VerifySignature(
GetKeys().PublicKey,
hash,
AsymmetricAlgorithmHelpers.ConvertIeee1363ToDer(signature));
SecKeyPair keys = GetKeys();
byte[] formattedSignature = AsymmetricAlgorithmHelpers.ConvertIeee1363ToDer(signature);

if (keys.PublicDataKey != null)
Copy link
Member

Choose a reason for hiding this comment

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

Would there ever be a situation where we can't get a public data key?

{
return Interop.AppleCrypto.KeyServicesVerifySignature(
keys.PublicDataKey,
hash,
formattedSignature,
Interop.AppleCrypto.PAL_HashAlgorithm.Unknown,
Interop.AppleCrypto.PAL_SignatureAlgorithm.EC,
digest: true);
}
else
{
return Interop.AppleCrypto.VerifySignature(
keys.PublicKey,
hash,
formattedSignature);
}
}

protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
Expand Down
Loading