Skip to content

refactor: Add consistent docs and proper naming for certain methods for creating keys #243

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

Merged
merged 7 commits into from
Jun 12, 2025
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,13 +15,27 @@
using System;
using System.Formats.Asn1;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;

namespace Yubico.YubiKey.Cryptography;

/// <summary>
/// A class that converts ASN.1 DER encoded private keys to parameters and values.
/// </summary>
internal class AsnPrivateKeyDecoder
{
/// <summary>
/// Creates an instance of <see cref="IPrivateKey"/> from a PKCS#8
/// ASN.1 DER-encoded private key.
/// </summary>
/// <param name="pkcs8EncodedKey">
/// The ASN.1 DER-encoded private key.
/// </param>
/// <returns>
/// A new instance of <see cref="IPrivateKey"/>.
/// </returns>
/// <exception cref="CryptographicException">Thrown if privateKey does not match expected format.</exception>
/// <exception cref="InvalidOperationException">Thrown if the algorithm is not supported</exception>
public static IPrivateKey CreatePrivateKey(ReadOnlyMemory<byte> pkcs8EncodedKey)
{
var reader = new AsnReader(pkcs8EncodedKey, AsnEncodingRules.DER);
Expand Down Expand Up @@ -67,8 +81,25 @@ public static IPrivateKey CreatePrivateKey(ReadOnlyMemory<byte> pkcs8EncodedKey)
ExceptionMessages.UnsupportedAlgorithm));
}

public static Curve25519PrivateKey CreateCurve25519Key(ReadOnlyMemory<byte> pkcs8EncodedKey) =>
Curve25519PrivateKey.CreateFromPkcs8(pkcs8EncodedKey);
/// <summary>
/// Creates an instance of <see cref="Curve25519PrivateKey"/> from a PKCS#8
/// ASN.1 DER-encoded private key.
/// </summary>
/// <param name="pkcs8EncodedKey">
/// The ASN.1 DER-encoded private key.
/// </param>
/// <returns>
/// A new instance of <see cref="Curve25519PrivateKey"/>.
/// </returns>
/// <exception cref="CryptographicException">Thrown if privateKey does not match expected format.</exception>
/// <exception cref="ArgumentException">Thrown if the algorithm is not <see cref="Oids.X25519"/> or
/// <see cref="Oids.Ed25519"/></exception>
public static Curve25519PrivateKey CreateCurve25519Key(ReadOnlyMemory<byte> pkcs8EncodedKey)
{
(byte[] privateKey, var keyType) = GetCurve25519PrivateKeyData(pkcs8EncodedKey);
using var privateKeyHandle = new ZeroingMemoryHandle(privateKey);
return Curve25519PrivateKey.CreateFromValue(privateKeyHandle.Data, keyType);
}

public static (byte[] privateKey, KeyType keyType) GetCurve25519PrivateKeyData(ReadOnlyMemory<byte> pkcs8EncodedKey)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,26 @@

namespace Yubico.YubiKey.Cryptography;

/// <summary>
/// A class that converts ASN.1 DER encoded X.509 SubjectPublicKeyInfo to instances of IPublicKey.
/// </summary>
internal class AsnPublicKeyDecoder
{
public static IPublicKey CreatePublicKey(ReadOnlyMemory<byte> pkcs8EncodedKey)
/// <summary>
/// Creates an instance of <see cref="IPublicKey"/> from a
/// ASN.1 DER-encoded SubjectPublicKeyInfo.
/// </summary>
/// <param name="subjectPublicKeyInfo">
/// The ASN.1 DER-encoded SubjectPublicKeyInfo.
/// </param>
/// <returns>
/// A new instance of <see cref="IPublicKey"/>.
/// </returns>
/// <exception cref="CryptographicException">Thrown if public key does not match expected format.</exception>
/// <exception cref="InvalidOperationException">Thrown if the algorithm is not supported</exception>
public static IPublicKey CreatePublicKey(ReadOnlyMemory<byte> subjectPublicKeyInfo)
{
var reader = new AsnReader(pkcs8EncodedKey, AsnEncodingRules.DER);
var reader = new AsnReader(subjectPublicKeyInfo, AsnEncodingRules.DER);
var seqSubjectPublicKeyInfo = reader.ReadSequence();
var seqAlgorithmIdentifier = seqSubjectPublicKeyInfo.ReadSequence();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,21 @@

namespace Yubico.YubiKey.Cryptography;

/// <summary>
/// Represents a Curve25519 private key.
/// </summary>
/// <remarks>
/// This sealed class encapsulates Curve25519 private key data and supports
/// both Ed25519 and X25519 cryptographic operations.
/// It also provides factory methods for creating instances from private key values or DER-encoded data.
/// </remarks>
public sealed class Curve25519PrivateKey : PrivateKey
{
private readonly Memory<byte> _privateKey;

/// <inheritdoc />
public override KeyType KeyType => KeyDefinition.KeyType;

/// <summary>
/// Gets the key definition associated with this RSA private key.
/// </summary>
Expand All @@ -37,7 +45,7 @@ public sealed class Curve25519PrivateKey : PrivateKey
/// </summary>
/// <returns>A <see cref="ReadOnlyMemory{T}"/> containing the private scalar value.</returns>
public ReadOnlyMemory<byte> PrivateKey => _privateKey;

private Curve25519PrivateKey(
ReadOnlyMemory<byte> privateKey,
KeyType keyType)
Expand All @@ -53,9 +61,9 @@ private Curve25519PrivateKey(

privateKey.CopyTo(_privateKey);
}

/// <inheritdoc />
public override byte[] ExportPkcs8PrivateKey()
public override byte[] ExportPkcs8PrivateKey()
{
ThrowIfDisposed();
return AsnPrivateKeyEncoder.EncodeToPkcs8(_privateKey, KeyType);
Expand All @@ -70,10 +78,10 @@ public override byte[] ExportPkcs8PrivateKey()

/// <summary>
/// Creates an instance of <see cref="Curve25519PrivateKey"/> from a PKCS#8
/// DER-encoded private key.
/// ASN.1 DER-encoded private key.
/// </summary>
/// <param name="pkcs8EncodedKey">
/// The DER-encoded private key.
/// The ASN.1 DER-encoded private key.
/// </param>
/// <returns>
/// A new instance of <see cref="Curve25519PrivateKey"/>.
Expand All @@ -88,7 +96,7 @@ public static Curve25519PrivateKey CreateFromPkcs8(ReadOnlyMemory<byte> pkcs8Enc
using var privateKeyHandle = new ZeroingMemoryHandle(privateKey);
return new Curve25519PrivateKey(privateKeyHandle.Data, keyType);
}

/// <summary>
/// Creates an instance of <see cref="Curve25519PrivateKey"/> from the given
/// <paramref name="privateKey"/> and <paramref name="keyType"/>.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,19 @@
// limitations under the License.

using System;
using System.Formats.Asn1;
using System.Globalization;
using System.Security.Cryptography;

namespace Yubico.YubiKey.Cryptography;

/// <summary>
/// Represents a Curve25519 public key.
/// </summary>
/// <remarks>
/// This sealed class encapsulates Curve25519 public key data as a compressed point
/// and supports both Ed25519 and X25519 key types.
/// It also provides factory methods for creating instances from public point values or DER-encoded data.
/// </remarks>
public sealed class Curve25519PublicKey : PublicKey
{
private readonly Memory<byte> _publicPoint;
Expand Down Expand Up @@ -52,7 +59,7 @@ private Curve25519PublicKey(

publicPoint.CopyTo(_publicPoint);
}

/// <summary>
/// Converts this public key to an ASN.1 DER encoded format (X.509 SubjectPublicKeyInfo).
/// </summary>
Expand All @@ -63,33 +70,21 @@ public override byte[] ExportSubjectPublicKeyInfo() =>
AsnPublicKeyEncoder.EncodeToSubjectPublicKeyInfo(_publicPoint, KeyDefinition.KeyType);

/// <summary>
/// Creates a new instance of <see cref="Curve25519PublicKey"/> from a DER-encoded public key.
/// Creates a new instance of <see cref="Curve25519PublicKey"/> from a DER-encoded SubjectPublicKeyInfo.
/// </summary>
/// <param name="encodedKey">
/// The DER-encoded public key.
/// <param name="subjectPublicKeyInfo">
/// The DER-encoded SubjectPublicKeyInfo.
/// </param>
/// <returns>
/// A new instance of <see cref="Curve25519PublicKey"/>.
/// </returns>
/// <exception cref="CryptographicException">
/// Thrown if the public key is invalid.
/// Thrown if the subjectPublicKeyInfo is invalid.
/// </exception>
public static Curve25519PublicKey CreateFromPkcs8(ReadOnlyMemory<byte> encodedKey)
{
var reader = new AsnReader(encodedKey, AsnEncodingRules.DER);
var seqSubjectPublicKeyInfo = reader.ReadSequence();
var seqAlgorithmIdentifier = seqSubjectPublicKeyInfo.ReadSequence();

string oidAlgorithm = seqAlgorithmIdentifier.ReadObjectIdentifier();
byte[] subjectPublicKey = seqSubjectPublicKeyInfo.ReadBitString(out int unusedBitCount);
if (unusedBitCount != 0)
{
throw new CryptographicException("Invalid public key encoding");
}

var keyType = KeyDefinitions.GetKeyTypeByOid(oidAlgorithm);
return CreateFromValue(subjectPublicKey, keyType);
}
public static Curve25519PublicKey CreateFromSubjectPublicKeyInfo(ReadOnlyMemory<byte> subjectPublicKeyInfo) =>
AsnPublicKeyDecoder
.CreatePublicKey(subjectPublicKeyInfo)
.Cast<Curve25519PublicKey>();

/// <summary>
/// Creates an instance of <see cref="Curve25519PublicKey"/> from the given
Expand All @@ -114,4 +109,8 @@ public static Curve25519PublicKey CreateFromValue(ReadOnlyMemory<byte> publicPoi

return new Curve25519PublicKey(publicPoint, keyDefinition);
}

[Obsolete("Use CreateFromSubjectPublicKeyInfo instead", false)]
public static Curve25519PublicKey CreateFromPkcs8(ReadOnlyMemory<byte> subjectPublicKeyInfo) =>
CreateFromSubjectPublicKeyInfo(subjectPublicKeyInfo);
}
19 changes: 12 additions & 7 deletions Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/ECPrivateKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ namespace Yubico.YubiKey.Cryptography
/// Represents the parameters for an Elliptic Curve (EC) private key.
/// </summary>
/// <remarks>
/// This class encapsulates the parameters specific to EC private keys and
/// contains the necessary private key data.
/// This class encapsulates the parameters specific to EC private keys
/// and provides factory methods for creating instances from EC parameters
/// or DER-encoded data.
/// </remarks>
public class ECPrivateKey : PrivateKey
{
Expand All @@ -33,7 +34,7 @@ public class ECPrivateKey : PrivateKey
/// An <see cref="ECParameters"/> structure containing the curve parameters, key, and other
/// cryptographic elements needed for EC operations.
/// </value>
public ECParameters Parameters { get;}
public ECParameters Parameters { get; }

/// <summary>
/// Gets the key definition associated with this RSA private key.
Expand Down Expand Up @@ -84,7 +85,7 @@ protected ECPrivateKey(ECDsa ecdsaObject)
Parameters = ecdsaObject.ExportParameters(true);
KeyDefinition = KeyDefinitions.GetByOid(Parameters.Curve.Oid);
}

/// <inheritdoc/>
public override byte[] ExportPkcs8PrivateKey()
{
Expand Down Expand Up @@ -115,12 +116,16 @@ public override void Clear()
public static ECPrivateKey CreateFromPkcs8(ReadOnlyMemory<byte> encodedKey)
{
var parameters = AsnPrivateKeyDecoder.CreateECParameters(encodedKey);

return CreateFromParameters(parameters);
}

#pragma warning disable CS0618 // Type or member is obsolete.

/// <summary>
/// Creates an instance of <see cref="ECPrivateKey"/> from the given <paramref name="parameters"/>.
/// </summary>
/// <param name="parameters">The parameters to create the key from.</param>
/// <returns>An instance of <see cref="ECPrivateKey"/>.</returns>
public static ECPrivateKey CreateFromParameters(ECParameters parameters) => new(parameters);
#pragma warning restore CS0618 // Type or member is obsolete

/// <summary>
/// Creates a new instance of <see cref="ECPrivateKey"/> from the given
Expand Down
24 changes: 15 additions & 9 deletions Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/ECPublicKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@
namespace Yubico.YubiKey.Cryptography;

/// <summary>
/// Represents the parameters for an Elliptic Curve (EC) public key.
/// Represents an Elliptic Curve (EC) public key.
/// </summary>
/// <remarks>
/// This class encapsulates the parameters specific to EC public keys,
/// ensuring that the key only contains necessary public key components.
/// This class encapsulates EC public key parameters and provides cryptographic operations
/// for NIST elliptic curves and provides factory methods for creating instances from EC parameters or DER-encoded data.
/// </remarks>
public class ECPublicKey : PublicKey
{
Expand Down Expand Up @@ -99,7 +99,7 @@ protected ECPublicKey(ECDsa ecdsa)

/// <inheritdoc />
public override byte[] ExportSubjectPublicKeyInfo() => AsnPublicKeyEncoder.EncodeToSubjectPublicKeyInfo(Parameters);

/// <summary>
/// Creates an instance of <see cref="ECPublicKey"/> from the given <paramref name="parameters"/>.
/// </summary>
Expand Down Expand Up @@ -141,13 +141,19 @@ public static ECPublicKey CreateFromValue(ReadOnlyMemory<byte> publicPoint, KeyT
}

/// <summary>
/// Creates an instance of <see cref="ECPublicKey"/> from a DER-encoded public key.
/// Creates an instance of <see cref="ECPublicKey"/> from a DER-encoded SubjectPublicKeyInfo.
/// </summary>
/// <param name="encodedKey">The DER-encoded public key.</param>
/// <param name="subjectPublicKeyInfo">The DER-encoded SubjectPublicKeyInfo.</param>
/// <returns>An instance of <see cref="IPublicKey"/>.</returns>
/// <exception cref="CryptographicException">
/// Thrown if the public key is invalid.
/// Thrown if the subjectPublicKeyInfo is invalid.
/// </exception>
public static ECPublicKey CreateFromPkcs8(ReadOnlyMemory<byte> encodedKey) =>
(ECPublicKey)AsnPublicKeyDecoder.CreatePublicKey(encodedKey);
public static ECPublicKey CreateFromSubjectPublicKeyInfo(ReadOnlyMemory<byte> subjectPublicKeyInfo) =>
AsnPublicKeyDecoder
.CreatePublicKey(subjectPublicKeyInfo)
.Cast<ECPublicKey>();

[Obsolete("Use CreateFromSubjectPublicKeyInfo instead", false)]
public static ECPublicKey CreateFromPkcs8(ReadOnlyMemory<byte> subjectPublicKeyInfo) =>
CreateFromSubjectPublicKeyInfo(subjectPublicKeyInfo);
}
7 changes: 7 additions & 0 deletions Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/IKeyBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@

namespace Yubico.YubiKey.Cryptography;

/// <summary>
/// Defines the base contract for all cryptographic keys, providing key type identification.
/// </summary>
/// <remarks>
/// This interface serves as the foundation for both public and private key abstractions,
/// enabling polymorphic key type handling across different cryptographic algorithms.
/// </remarks>
public interface IKeyBase
{
/// <summary>
Expand Down
8 changes: 8 additions & 0 deletions Yubico.YubiKey/src/Yubico/YubiKey/Cryptography/IPrivateKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,14 @@

namespace Yubico.YubiKey.Cryptography;

/// <summary>
/// Defines the contract for cryptographic private keys.
/// </summary>
/// <remarks>
/// This interface extends <see cref="IKeyBase"/> to include private key-specific operations
/// for PKCS#8 export and secure memory cleanup.
/// Known implementations include <see cref="ECPrivateKey"/>, <see cref="RSAPrivateKey"/> and <see cref="Curve25519PrivateKey"/>,.
/// </remarks>
public interface IPrivateKey : IKeyBase
{
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,33 @@

namespace Yubico.YubiKey.Cryptography;


/// <summary>
/// Extension methods for <see cref="IPrivateKey"/> to provide type-safe casting operations.
/// </summary>
public static class IPrivateKeyExtensions
{
/// <summary>
/// Casts the key to the specified type.
/// Safely casts an <see cref="IPrivateKey"/> instance to a specific derived type.
/// </summary>
/// <param name="key"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
/// <exception cref="InvalidCastException"></exception>
/// <typeparam name="T">The target type that implements <see cref="IPrivateKey"/>.</typeparam>
/// <param name="key">The private key instance to cast.</param>
/// <returns>The private key cast to the specified type <typeparamref name="T"/>.</returns>
/// <exception cref="InvalidCastException">
/// Thrown when the <paramref name="key"/> cannot be cast to type <typeparamref name="T"/>.
/// The exception message includes both the source and target type names for debugging.
/// </exception>
/// <example>
/// <code>
/// IPrivateKey genericKey = GetPrivateKey();
/// RsaPrivateKey rsaKey = genericKey.Cast&lt;RsaPrivateKey&gt;();
/// // throws InvalidCastException if genericKey is not an RsaPrivateKey
/// </code>
/// </example>
/// <remarks>
/// This method provides a more explicit alternative to direct casting with clearer error messages.
/// Prefer this over unsafe casting operations when type safety is critical for cryptographic operations.
/// </remarks>
public static T Cast<T>(this IPrivateKey key) where T : class, IPrivateKey =>
key as T ?? throw new InvalidCastException($"Cannot cast {key.GetType()} to {typeof(T)}");
}
Loading
Loading