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 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
Hi @DinoChiesa
If I use toASN1 and pass the result to ContentInfo:
https://github.com/bcgit/bc-java/blob/1cae5431b0f315e1c7dc40392bcd60cf785831b4/core/src/main/java/org/bouncycastle/asn1/pkcs/ContentInfo.java#L45
That line expects the first entry in the sequence to be an ASN1ObjectIdentifier type but of course it is of type ASN1Integer, which results in a class cast exception.
How does one incorporate the expected ASN1ObjectIdentifier ? I assume the value is something like:
1.2.840.10045.4.1 ecdsaWithSHA1 (ANSI X9.62 ECDSA algorithm with SHA2)
https://stackoverflow.com/questions/72097765/retrieving-signature-r-and-s-element-from-asn-1-cms-signature-bouncy-castle