Created
October 8, 2021 17:16
-
-
Save DinoChiesa/7520e1dea6e79888acab8ea8206afe92 to your computer and use it in GitHub Desktop.
Java: convert between ASN.1 and P1363 Encoding of Signature
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.bouncycastle.asn1.ASN1EncodableVector; | |
import org.bouncycastle.asn1.ASN1Integer; | |
import org.bouncycastle.asn1.ASN1Sequence; | |
import org.bouncycastle.asn1.DERSequence; | |
import java.math.BigInteger; | |
private static byte[] toP1363(byte[] asn1EncodedSignature) throws Exception { | |
ASN1Sequence seq = ASN1Sequence.getInstance(asn1EncodedSignature); | |
BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getValue(); | |
BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getValue(); | |
int n = (r.bitLength() + 7) / 8; | |
// round up to nearest even integer | |
n = (int) Math.round((n+1)/2) * 2; | |
byte[] out = new byte[2 * n]; | |
toFixed(r, out, 0, n); | |
toFixed(s, out, n, n); | |
return out; | |
} | |
private static byte[] toASN1(byte[] p1363EncodedSignature) throws IOException { | |
int n = p1363EncodedSignature.length / 2; | |
BigInteger r = new BigInteger(+1, Arrays.copyOfRange(p1363EncodedSignature, 0, n)); | |
BigInteger s = new BigInteger(+1, Arrays.copyOfRange(p1363EncodedSignature, n, n * 2)); | |
ASN1EncodableVector v = new ASN1EncodableVector(); | |
v.add(new ASN1Integer(r)); | |
v.add(new ASN1Integer(s)); | |
return new DERSequence(v).getEncoded(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awesome simplification. God bless you, @nicobao.