Can you help me to find a simple tutorial of how sign a string using ECDSA algorithm in java. But without using any third-party libraries like bouncycastle. Just JDK 7. I found
class ECCCipher {
@Override
public byte[] sign(PrivateKey privateKey, String message) throws Exception {
Signature signature = Signature.getInstance("SHA1withECDSA");
signature.initSign(privateKey);
signature.update(message.getBytes());
return signature.sign();
}
@Override
public boolean verify(PublicKey publicKey, byte[] signed, String message) throws Exception {
Signature signature = Signature.getInstance("SHA1withECDSA");
signature.initVerify(publicKey);
signature.update(message.getBytes());
return signature.verify(signed);
}
}
========================
public class ECCCipherTest {
private final KeyPairGenerator keygen;
public ECCCipherTest() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
Security.addProvider(new BouncyCastleProvider());
this.keygen = KeyPairGenerator.getInstance("ECDSA", "BC");
keygen.initialize(new ECGenParameterSpec("brainpoolP384r1"));
}
@Test
public void ECC_CipherTest_1() throws Exception {
String message = "hello world";
ICipher cipher = new ECCCipher();
KeyPair keyPair = keygen.generateKeyPair();
byte[] encrypted = cipher.sign(keyPair.getPrivate(), message);
Assert.assertTrue(cipher.verify(keyPair.getPublic(), encrypted, message));
}
}
this is a small code snippet from my project. it works for me. I have included one junit test as well; hopefully this helps.
just in case anyone wonders how we load the private key and pubkey: (note: privKey is the byte array representing the BigInteger in java, and the pubKey is the curve point in binary format)
@Override
public PrivateKey generatePrivateKey(byte[] keyBin) throws InvalidKeySpecException, NoSuchAlgorithmException {
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1");
KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
ECNamedCurveSpec params = new ECNamedCurveSpec("secp256k1", spec.getCurve(), spec.getG(), spec.getN());
ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec(new BigInteger(keyBin), params);
return kf.generatePrivate(privKeySpec);
}
@Override
public PublicKey generatePublicKey(byte[] keyBin) throws InvalidKeySpecException, NoSuchAlgorithmException {
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("secp256k1");
KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
ECNamedCurveSpec params = new ECNamedCurveSpec("secp256k1", spec.getCurve(), spec.getG(), spec.getN());
ECPoint point = ECPointUtil.decodePoint(params.getCurve(), keyBin);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);
return kf.generatePublic(pubKeySpec);
}