ECDSA Digital Signature Verification in Java

LinkedIn Tweet Facebook
ECDSA Digital Signature Verification in Java

Digital Signature

Digital signatures are used to verify

Digital signature can be generated by any cryptographic hash function. Let's say SHA256.

The author sends both public key and the signature with the document.

Elliptic curve with Digital Signature Algorithm (ECDSA)

ECDSA is designed for digital signatures. This algorithm generates a private-public key pair. The keys can be reused. So this code can be called once and we use the pair values for sending and receiving.

ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("B-571");
KeyPairGenerator g = KeyPairGenerator.getInstance("ECDSA", "BC");
g.initialize(ecSpec, new SecureRandom());
KeyPair keypair = g.generateKeyPair();
String publicKey = keypair.getPublic();
String privateKey = keypair.getPrivate(); 

Sign and Send

The sender signs the message with private key and sends

to the receiver.

//at sender's end
Signature ecdsaSign = Signature.getInstance("SHA256withECDSA", "BC");
ecdsaSign.initSign(privateKey);
ecdsaSign.update(plaintext.getBytes("UTF-8"));
byte[] signature = ecdsaSign.sign();

The same algorith needs to be used on the client as well to verify the download. So it's better the sender also sends the algorithm used for signing. In our case it's SHA256withECDSA

Receive and Verify

Let's say the receiver gets a json object


JSONObject obj = ...;

// at receiver's end
Signature ecdsaVerify = Signature.getInstance("SHA256withECDSA", "BC");
ecdsaVerify.initVerify(obj.getString("publicKey"));
ecdsaVerify.update(obj.getString("message").getBytes("UTF-8"));
boolean result = ecdsaVerify.verify(obj.getString("signature"));