Error when verifying ECDSA signature in Java with BouncyCastle

允我心安 提交于 2019-11-30 13:41:48
Peter Dettman

The expected ECDSA signature format that the BC (and other provider) implementations work with is a DER-encoded ASN.1 sequence containing two integer values r and s. This signature format has been specified in ANSI X9.62. This is the format in the first set of data you give (note that signature is a total of 70 bytes).

In the second set of data, signature is only 32 bytes, and is not an ASN.1 sequence at all. I would guess that this value is only the s value, and it is missing the r value and the ASN.1 INTEGER encoding for them both, instead encoding the values as a unsigned big integer value with the same size as the key.

this is a sample code to write r and s in ASN1 DER encoded format

    // construct the ASN1Sequence with r and s
    ByteArrayOutputStream outs = new ByteArrayOutputStream();

    byte radd = (byte)(((signed[0] & 0x80) > 0) ? 1 : 0);
    byte sadd = (byte)(((signed[32] & 0x80) > 0) ? 1 : 0);

    byte length = (byte)(0x44 + radd + sadd);

    outs.write(0x30);
    outs.write(length); // length 68 bytes +
    outs.write(0x02); // ASN1Integer
    outs.write(0x20 + radd); // length 32 bytes
    if(radd > 0)
        outs.write(0x00); // positive val
    outs.write(signed, 0, 32);
    outs.write(0x02); // ASN1Integer
    outs.write(0x20 + sadd); // length 32 bytes
    if(sadd > 0)
        outs.write(0x00); // positive val
    outs.write(signed, 32, 32);

    signed = outs.toByteArray();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!