Skip to content

Instantly share code, notes, and snippets.

@icexin
Created October 13, 2019 09:19
Show Gist options
  • Save icexin/230cba7d1685a162e8d8350a3e91f07b to your computer and use it in GitHub Desktop.
Save icexin/230cba7d1685a162e8d8350a3e91f07b to your computer and use it in GitHub Desktop.
ecdsa sign and verify between go and java
package com.icexin;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.DERSequenceGenerator;
import org.bouncycastle.asn1.nist.NISTNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.params.ECDomainParameters;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.signers.ECDSASigner;
import org.bouncycastle.util.encoders.Hex;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
public class Crypto {
static public byte[] sign(byte[] hash, String privateKey) throws IOException {
X9ECParameters curve = NISTNamedCurves.getByName("P-256");
ECDomainParameters domain = new ECDomainParameters(curve.getCurve(), curve.getG(), curve.getN(), curve.getH());
ECDSASigner signer = new ECDSASigner();
signer.init(true, new ECPrivateKeyParameters(new BigInteger(privateKey), domain));
BigInteger[] signature = signer.generateSignature(hash);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DERSequenceGenerator seq = new DERSequenceGenerator(baos);
seq.addObject(new ASN1Integer(signature[0]));
seq.addObject(new ASN1Integer(signature[1]));
seq.close();
return baos.toByteArray();
}
public static void main(String[] args) throws Exception {
String priv = "24473924603921903401043805245225966818735256098608866349502516970708301627736";
byte[] s = sign("hello".getBytes(), priv);
System.out.println(Hex.toHexString(s));
}
}
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"encoding/asn1"
"encoding/hex"
"fmt"
"math/big"
)
func newPrivateKey(s string) *ecdsa.PrivateKey {
curve := elliptic.P256()
d, ok := big.NewInt(0).SetString(s, 10)
if !ok {
panic("invalid number " + s)
}
x, y := curve.ScalarBaseMult(d.Bytes())
return &ecdsa.PrivateKey{
PublicKey: ecdsa.PublicKey{
Curve: elliptic.P256(),
X: x,
Y: y,
},
D: d,
}
}
func verify(pubkey *ecdsa.PublicKey, hash []byte, hexsig string) bool {
sig, _ := hex.DecodeString(hexsig)
var rs []*big.Int
asn1.Unmarshal(sig, &rs)
r, s := rs[0], rs[1]
return ecdsa.Verify(pubkey, hash, r, s)
}
func main() {
d := "24473924603921903401043805245225966818735256098608866349502516970708301627736"
sig := "3044022059e533a91a79327f511ad8139fc361820d793cc858ce5c69f31720e009cd136e02204a13f88515ed2e64fa36d871b09a8897554306150348083521455b3c48904372"
privateKey := newPrivateKey(d)
publicKey := &privateKey.PublicKey
hash := []byte("hello")
ok := verify(publicKey, hash, sig)
fmt.Println("signature verified:", ok)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment