簡體   English   中英

從 ECDSA 簽名 signedxml c# 中提取 r 和 s

[英]Extract r and s from ECDSA signature signedxml c#

我在 .net 5 中使用 Signedxml 類使用 ECDSA 生成簽名,我需要 r 和 s 的值,但我無法提取它,另一個問題是簽名長度。 我的簽名總是 64 字節,但 ECDSA 簽名長度是 71,我不知道為什么這個長度會改變。 請幫我提取 r 和 s

將 ECDSA 簽名從 ASN.1/DER 轉換為 P1363 (r|s) 格式時,必須考慮以下幾點:

  • 在 ASN.1/DER 格式中 r 和 s 包含為有符號的大端數組,在 P1363 格式中包含為無符號的大端數組。
  • 在 ASN.1/DER 格式中,r 和 s 作為最小大小的數組包含在內,在 P1363 中,兩者都使用前導 0x00 值填充到它們的最大大小(生成點順序的長度)。 示例:對於 NIST P-256,r 和 s 的最大大小各為 32 個字節。

.NET 5+ 使用AsnReader類的可能實現:

using System.Formats.Asn1;
...
public static byte[] DERtoP1363(byte[] derSignature, int maxSize)
{
    AsnReader sequence = new AsnReader(derSignature, AsnEncodingRules.DER).ReadSequence();
    byte[] rBytes = sequence.ReadInteger().ToByteArray(true, true); // convert to unsigned, big endian
    byte[] sBytes = sequence.ReadInteger().ToByteArray(true, true); // convert to unsigned, big endian
    byte[] rsBytes = new byte[2 * maxSize];
    Buffer.BlockCopy(rBytes, 0, rsBytes, maxSize - rBytes.Length, rBytes.Length);     // resize to maximum size
    Buffer.BlockCopy(sBytes, 0, rsBytes, 2 * maxSize - sBytes.Length, sBytes.Length); // resize to maximum size
    return rsBytes;
}

AsnReader從 .NET 5 開始可用。

為了完整性:在其他 .NET 版本中,可以應用 BouncyCastle(使用Org.BouncyCastle.Asn1命名空間中的類)。 為此, DERtoP1363()中的前三行必須替換為:

Asn1Sequence sequence = Asn1Sequence.GetInstance(derSignature);
byte[] rBytes = DerInteger.GetInstance(sequence[0]).PositiveValue.ToByteArrayUnsigned();
byte[] sBytes = DerInteger.GetInstance(sequence[1]).PositiveValue.ToByteArrayUnsigned();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM