Skip to content

DER to P1363 in Java using BouncyCastle only #6

Description

@nicobao

Hi there,

I came across this repository upon a Google search on how to convert DER encoded signature to P1363 in Java.
Thanks for your work!

After lots of tinkering, I discovered it is possible to convert to P1363 by relying on BouncyCastle entirely, without any custom arithmetic:

import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.crypto.signers.PlainDSAEncoding;
import org.bouncycastle.math.ec.custom.sec.SecP256R1Curve;
    
// the asn1EncodedSignature param is typically generated by
// Signature signature = Signature.getInstance("SHA256withECDSA");
// with AndroidKeyStore as provider
private byte[] toP1363(byte[] asn1EncodedSignature) {
    ASN1Sequence seq = ASN1Sequence.getInstance(asn1EncodedSignature);
    BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getValue();
    BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getValue();
    BigInteger n = new SecP256R1Curve().getOrder();
    return PlainDSAEncoding.INSTANCE.encode(n, r, s);
}

Note that it works on Android, and you don't need to add BouncyCastle as a global Provider or anything. You can just use the classes as shown above.

Just wanted to add this here it case it can help somebody - as for production, it is safer to rely on a well-known library than using custom code.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions