Manu
Manu

Reputation: 1369

ECDSA signature generation using secp256r1 curve (BouncyCastle) giving signature with length 127

I am implementing ECDSA signature generation using secp256r1 curve and SHA256 algorithm using BouncyCastle.

For some of the inputs the signature length is 127 characters long. I feel the "0" at the beginning are getting removed as the signature is stored to BigInteger datatype in ECDSASigner class.

I have added the sample from rfc6979 ECDSA signing using Deterministic Approach

The relevant parts of the code :-

//Private key used in hex format -C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721
        String secretNumberK = "09F634B188CEFD98E7EC88B1AA9852D734D0BC272F7D2A47DECC6EBEB375AAD4";
        SecureRandom secureRandom = new FixedSecureRandom(Hex.decode(secretNumber));
        ECPrivateKeyParameters ecPrivateKeySpec = Util.getECPriKeyParameter(ecPrivateKey);//it is the PrivateKey of the sample shown 
        byte[]  messageInHex = Hex.decode("test");
        
         ECDSASigner ecdsaSigner = new ECDSASigner();

        ecdsaSigner.init(true, new ParametersWithRandom(ecPrivateKeySpec,
                secureRandom));

         BigInteger[]  sig = ecdsaSigner.generateSignature(Util
                .generateSHAHash(messageInHex));
        flag = true;
        LOG.debug("r:: " + sig[0].toString(16).toString());
        LOG.debug("s:: " + sig[1].toString(16).toString());

Expected R and S of Signature as per document:-

 r = 0EAFEA039B20E9B42309FB1D89E213057CBF973DC0CFC8F129EDDDC800EF7719
 s = 4861F0491E6998B9455193E34E7B0D284DDD7149A74B95B9261F13ABDE940954

But Iam getting

r = EAFEA039B20E9B42309FB1D89E213057CBF973DC0CFC8F129EDDDC800EF7719
s = 4861F0491E6998B9455193E34E7B0D284DDD7149A74B95B9261F13ABDE940954

The only difference is the zero in the r value. And because of this length of signature is only 127.

Please let me know if my inference is correct. Is this a bug in Bouncy Castle?

Upvotes: 1

Views: 2458

Answers (1)

David Grayson
David Grayson

Reputation: 87396

This isn't a bug in BouncyCastle. BouncyCastle has returned a BigInteger to you. I don't believe Java's BigInteger class stores any information about how many leading zeros should be printed, and you are not supplying that information when you use .toString(16).toString(), so the inevitable result is that leading zeros will not be shown.

You understand that, for example, hex "0EAF" is the same number as hex "EAF", right? So this is just a string formatting issue. The numbers are correct.

If you want your strings to exactly match the text from the document, you will need to do some additional work when you are formatting your strings in order to add leading zeros.

Here is a similar questions and resources:

Upvotes: 5

Related Questions