Search code examples
c#cryptographydigital-signaturebouncycastle

Bouncy Castle convert ASN.1 to r and s byte arrays


I have the following code that generates a digital signature:

byte[] GetSignature(byte[] message, byte[] privateKey)
{
    var ecParams = NistNamedCurves.GetByName("P-256");
    var domainParameters = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed());
    var d = new BigInteger(1, privateKey);
    var privateKeyParameters = new ECPrivateKeyParameters(d, domainParameters);

    var signer = SignerUtilities.GetSigner("SHA-256withECDSA");
    signer.Init(true, privateKeyParameters);
    signer.BlockUpdate(message, 0, message.Length);

    var signature = signer.GenerateSignature();
    return signature;
}

This code returns a 71 byte array in ASN.1 format, however my consuming code expects the signature to be 64 bytes, composed of the r and s values. I would like to extract the r and s byte arrays. How do I do this?


Solution

  • In recent versions of bc-csharp, you can just change "SHA-256withECDSA" to "SHA-256withPLAIN-ECDSA" and then GenerateSignature will directly produce the 64 byte signature instead of the ASN.1 value.