Skip to content

Commit 33723ba

Browse files
committed
fix: Correct implementation of ES256K signatures.
1 parent 783089b commit 33723ba

File tree

2 files changed

+16
-7
lines changed

2 files changed

+16
-7
lines changed

src/main/java/com/danubetech/keyformats/crypto/impl/secp256k1_ES256K_PrivateKeySigner.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import com.danubetech.keyformats.jose.JWSAlgorithm;
55
import org.bitcoinj.core.ECKey;
66
import org.bitcoinj.core.Sha256Hash;
7+
import org.bitcoinj.core.Utils;
78

89
import java.security.GeneralSecurityException;
910

@@ -17,6 +18,13 @@ public secp256k1_ES256K_PrivateKeySigner(ECKey privateKey) {
1718
@Override
1819
public byte[] sign(byte[] content) throws GeneralSecurityException {
1920

20-
return this.getPrivateKey().sign(Sha256Hash.of(content)).encodeToDER();
21+
ECKey.ECDSASignature ecdsaSignature = this.getPrivateKey().sign(Sha256Hash.of(content));
22+
byte[] r = Utils.bigIntegerToBytes(ecdsaSignature.r, 32);
23+
byte[] s = Utils.bigIntegerToBytes(ecdsaSignature.s, 32);
24+
25+
byte[] signatureBytes = new byte[64];
26+
System.arraycopy(r, 0, signatureBytes, 0, r.length);
27+
System.arraycopy(s, 0, signatureBytes, 32, s.length);
28+
return signatureBytes;
2129
}
2230
}

src/main/java/com/danubetech/keyformats/crypto/impl/secp256k1_ES256K_PublicKeyVerifier.java

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
import com.danubetech.keyformats.jose.JWSAlgorithm;
55
import org.bitcoinj.core.ECKey;
66
import org.bitcoinj.core.Sha256Hash;
7-
import org.bitcoinj.core.SignatureDecodeException;
87

8+
import java.math.BigInteger;
99
import java.security.GeneralSecurityException;
1010

1111
public class secp256k1_ES256K_PublicKeyVerifier extends PublicKeyVerifier<ECKey> {
@@ -18,12 +18,13 @@ public secp256k1_ES256K_PublicKeyVerifier(ECKey publicKey) {
1818
@Override
1919
public boolean verify(byte[] content, byte[] signature) throws GeneralSecurityException {
2020

21-
try {
21+
byte[] r = new byte[32];
22+
byte[] s = new byte[32];
23+
System.arraycopy(signature, 0, r, 0, r.length);
24+
System.arraycopy(signature, 32, s, 0, s.length);
2225

23-
return this.getPublicKey().verify(Sha256Hash.hash(content), signature);
24-
} catch (SignatureDecodeException ex) {
26+
ECKey.ECDSASignature ecdsaSignature = new ECKey.ECDSASignature(new BigInteger(1, r), new BigInteger(1, s));
2527

26-
throw new GeneralSecurityException(ex.getMessage(), ex);
27-
}
28+
return this.getPublicKey().verify(Sha256Hash.of(content), ecdsaSignature);
2829
}
2930
}

0 commit comments

Comments
 (0)