Skip to content

PKCS#8 support for ML-DSA #115569

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 6 commits into from
May 20, 2025
Merged
Show file tree
Hide file tree
Changes from 3 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 @@ -24,25 +24,35 @@ internal enum PalMLDsaAlgorithmId
[LibraryImport(Libraries.CryptoNative)]
private static partial int CryptoNative_MLDsaGetPalId(
SafeEvpPKeyHandle mldsa,
out PalMLDsaAlgorithmId mldsaId);

internal static PalMLDsaAlgorithmId MLDsaGetPalId(SafeEvpPKeyHandle key)
out PalMLDsaAlgorithmId mldsaId,
out int hasSeed,
out int hasSecretKey);

internal static PalMLDsaAlgorithmId MLDsaGetPalId(
SafeEvpPKeyHandle key,
out bool hasSeed,
out bool hasSecretKey)
{
const int Success = 1;
const int Yes = 1;
const int Fail = 0;
int result = CryptoNative_MLDsaGetPalId(key, out PalMLDsaAlgorithmId mldsaId);

return result switch
{
Success => mldsaId,
Fail => throw CreateOpenSslCryptographicException(),
int other => throw FailThrow(other),
};
int result = CryptoNative_MLDsaGetPalId(
key,
out PalMLDsaAlgorithmId mldsaId,
out int pKeyHasSeed,
out int pKeyHasSecretKey);

static Exception FailThrow(int result)
switch (result)
{
Debug.Fail($"Unexpected return value {result} from {nameof(CryptoNative_MLDsaGetPalId)}.");
return new CryptographicException();
case Success:
hasSeed = pKeyHasSeed == Yes;
hasSecretKey = pKeyHasSecretKey == Yes;
return mldsaId;
case Fail:
throw CreateOpenSslCryptographicException();
default:
Debug.Fail($"Unexpected return value {result} from {nameof(CryptoNative_MLDsaGetPalId)}.");
throw new CryptographicException();
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8" ?>
<asn:Choice
xmlns:asn="http://schemas.dot.net/asnxml/201808/"
name="MLDsaPrivateKeyAsn"
namespace="System.Security.Cryptography.Asn1">

<!--
https://github.com/lamps-wg/dilithium-certificates/blob/5b23428b08a53aacdb89d93422b81228433e34d8/draft-ietf-lamps-dilithium-certificates.md

ML-DSA-44-PrivateKey ::= CHOICE {
seed [0] OCTET STRING (SIZE (32)),
expandedKey OCTET STRING (SIZE (2560)),
both SEQUENCE {
seed OCTET STRING (SIZE (32)),
expandedKey OCTET STRING (SIZE (2560))
}
}

ML-DSA-65-PrivateKey ::= CHOICE {
seed [0] OCTET STRING (SIZE (32)),
expandedKey OCTET STRING (SIZE (4032)),
both SEQUENCE {
seed OCTET STRING (SIZE (32)),
expandedKey OCTET STRING (SIZE (4032))
}
}

ML-DSA-87-PrivateKey ::= CHOICE {
seed [0] OCTET STRING (SIZE (32)),
expandedKey OCTET STRING (SIZE (4896)),
both SEQUENCE {
seed OCTET STRING (SIZE (32)),
expandedKey OCTET STRING (SIZE (4896))
}
}
-->
<asn:OctetString name="Seed" implicitTag="0" />
<asn:OctetString name="ExpandedKey" />
<asn:AsnType name="Both" typeName="System.Security.Cryptography.Asn1.MLDsaPrivateKeyBothAsn" />
</asn:Choice>
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#pragma warning disable SA1028 // ignore whitespace warnings for generated code
using System;
using System.Formats.Asn1;
using System.Runtime.InteropServices;

namespace System.Security.Cryptography.Asn1
{
[StructLayout(LayoutKind.Sequential)]
internal partial struct MLDsaPrivateKeyAsn
{
internal ReadOnlyMemory<byte>? Seed;
internal ReadOnlyMemory<byte>? ExpandedKey;
internal System.Security.Cryptography.Asn1.MLDsaPrivateKeyBothAsn? Both;

#if DEBUG
static MLDsaPrivateKeyAsn()
{
var usedTags = new System.Collections.Generic.Dictionary<Asn1Tag, string>();
Action<Asn1Tag, string> ensureUniqueTag = (tag, fieldName) =>
{
if (usedTags.TryGetValue(tag, out string? existing))
{
throw new InvalidOperationException($"Tag '{tag}' is in use by both '{existing}' and '{fieldName}'");
}

usedTags.Add(tag, fieldName);
};

ensureUniqueTag(new Asn1Tag(TagClass.ContextSpecific, 0), "Seed");
ensureUniqueTag(Asn1Tag.PrimitiveOctetString, "ExpandedKey");
ensureUniqueTag(Asn1Tag.Sequence, "Both");
}
#endif

internal readonly void Encode(AsnWriter writer)
{
bool wroteValue = false;

if (Seed.HasValue)
{
if (wroteValue)
throw new CryptographicException();

writer.WriteOctetString(Seed.Value.Span, new Asn1Tag(TagClass.ContextSpecific, 0));
wroteValue = true;
}

if (ExpandedKey.HasValue)
{
if (wroteValue)
throw new CryptographicException();

writer.WriteOctetString(ExpandedKey.Value.Span);
wroteValue = true;
}

if (Both.HasValue)
{
if (wroteValue)
throw new CryptographicException();

Both.Value.Encode(writer);
wroteValue = true;
}

if (!wroteValue)
{
throw new CryptographicException();
}
}

internal static MLDsaPrivateKeyAsn Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
try
{
AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet);

DecodeCore(ref reader, encoded, out MLDsaPrivateKeyAsn decoded);
reader.ThrowIfNotEmpty();
return decoded;
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}

internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out MLDsaPrivateKeyAsn decoded)
{
try
{
DecodeCore(ref reader, rebind, out decoded);
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}

private static void DecodeCore(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out MLDsaPrivateKeyAsn decoded)
{
decoded = default;
Asn1Tag tag = reader.PeekTag();
ReadOnlySpan<byte> rebindSpan = rebind.Span;
int offset;
ReadOnlySpan<byte> tmpSpan;

if (tag.HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 0)))
{

if (reader.TryReadPrimitiveOctetString(out tmpSpan, new Asn1Tag(TagClass.ContextSpecific, 0)))
{
decoded.Seed = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray();
}
else
{
decoded.Seed = reader.ReadOctetString(new Asn1Tag(TagClass.ContextSpecific, 0));
}

}
else if (tag.HasSameClassAndValue(Asn1Tag.PrimitiveOctetString))
{

if (reader.TryReadPrimitiveOctetString(out tmpSpan))
{
decoded.ExpandedKey = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray();
}
else
{
decoded.ExpandedKey = reader.ReadOctetString();
}

}
else if (tag.HasSameClassAndValue(Asn1Tag.Sequence))
{
System.Security.Cryptography.Asn1.MLDsaPrivateKeyBothAsn tmpBoth;
System.Security.Cryptography.Asn1.MLDsaPrivateKeyBothAsn.Decode(ref reader, rebind, out tmpBoth);
decoded.Both = tmpBoth;

}
else
{
throw new CryptographicException();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8" ?>
<asn:Sequence
xmlns:asn="http://schemas.dot.net/asnxml/201808/"
name="MLDsaPrivateKeyBothAsn"
namespace="System.Security.Cryptography.Asn1">

<!--
https://github.com/lamps-wg/dilithium-certificates/blob/5b23428b08a53aacdb89d93422b81228433e34d8/draft-ietf-lamps-dilithium-certificates.md

both SEQUENCE {
seed OCTET STRING (SIZE (32)),
expandedKey OCTET STRING (SIZE (2560))
}
-->
<asn:OctetString name="Seed" />
<asn:OctetString name="ExpandedKey" />
</asn:Sequence>
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

#pragma warning disable SA1028 // ignore whitespace warnings for generated code
using System;
using System.Formats.Asn1;
using System.Runtime.InteropServices;

namespace System.Security.Cryptography.Asn1
{
[StructLayout(LayoutKind.Sequential)]
internal partial struct MLDsaPrivateKeyBothAsn
{
internal ReadOnlyMemory<byte> Seed;
internal ReadOnlyMemory<byte> ExpandedKey;

internal readonly void Encode(AsnWriter writer)
{
Encode(writer, Asn1Tag.Sequence);
}

internal readonly void Encode(AsnWriter writer, Asn1Tag tag)
{
writer.PushSequence(tag);

writer.WriteOctetString(Seed.Span);
writer.WriteOctetString(ExpandedKey.Span);
writer.PopSequence(tag);
}

internal static MLDsaPrivateKeyBothAsn Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
return Decode(Asn1Tag.Sequence, encoded, ruleSet);
}

internal static MLDsaPrivateKeyBothAsn Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet)
{
try
{
AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet);

DecodeCore(ref reader, expectedTag, encoded, out MLDsaPrivateKeyBothAsn decoded);
reader.ThrowIfNotEmpty();
return decoded;
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}

internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out MLDsaPrivateKeyBothAsn decoded)
{
Decode(ref reader, Asn1Tag.Sequence, rebind, out decoded);
}

internal static void Decode(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out MLDsaPrivateKeyBothAsn decoded)
{
try
{
DecodeCore(ref reader, expectedTag, rebind, out decoded);
}
catch (AsnContentException e)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding, e);
}
}

private static void DecodeCore(ref AsnValueReader reader, Asn1Tag expectedTag, ReadOnlyMemory<byte> rebind, out MLDsaPrivateKeyBothAsn decoded)
{
decoded = default;
AsnValueReader sequenceReader = reader.ReadSequence(expectedTag);
ReadOnlySpan<byte> rebindSpan = rebind.Span;
int offset;
ReadOnlySpan<byte> tmpSpan;


if (sequenceReader.TryReadPrimitiveOctetString(out tmpSpan))
{
decoded.Seed = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray();
}
else
{
decoded.Seed = sequenceReader.ReadOctetString();
}


if (sequenceReader.TryReadPrimitiveOctetString(out tmpSpan))
{
decoded.ExpandedKey = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray();
}
else
{
decoded.ExpandedKey = sequenceReader.ReadOctetString();
}


sequenceReader.ThrowIfNotEmpty();
}
}
}
Loading
Loading