0

I am using google cloud KMS to manage my keys. Using JAVA client libs to interact with KMS. I receive byte array as a signature of a message as below

        byte[] plaintext = message.getBytes(StandardCharsets.UTF_8);

        // Calculate the digest.
        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
        byte[] hash = sha256.digest(plaintext);

        // Build the digest object.
        Digest digest = Digest.newBuilder().setSha256(ByteString.copyFrom(hash)).build();

        // Sign the digest.
        AsymmetricSignResponse result = client.asymmetricSign(keyVersionName, digest);

        byte[] signature = result.getSignature().toByteArray();

How to get a pair to integers {r, s} as a signature as stated here

neo007
  • 27
  • 7
  • Are you asking because you need `r` and `s` in some other process, or because you're hoping to verify the signature? Within a Java codebase, it's most straightforward to verify the signature using the standard library without extracting `r` and `s`. – bdhess Oct 20 '22 at 13:53
  • i need r and s for doing some other process.. – neo007 Oct 20 '22 at 15:15

1 Answers1

2

R and S are packed into an Ecdsa-Sig-Value ASN.1 structure. The most straightforward way to extract them would be to rely on a library like BouncyCastle that can read the ASN.1 sequence. For example

import java.math.BigInteger;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Sequence;

private static BigInteger[] extractRandS(byte[] asn1EncodedSignature) {
    ASN1Sequence seq = ASN1Sequence.getInstance(asn1EncodedSignature);
    BigInteger r = ((ASN1Integer) seq.getObjectAt(0)).getValue();
    BigInteger s = ((ASN1Integer) seq.getObjectAt(1)).getValue();
    return new BigInteger[]{r, s};
}
bdhess
  • 628
  • 3
  • 6