Reputation: 71
I am trying to write simple code for creating public/private keys, signing and verifying ECDSA signature. I have no idea why verification returns false. Please help me.
** I also tried to set provider to "SunEC" but it still doesn't work
val signatureECDSA = "SHA1withECDSA"
val signatureInstance = Signature.getInstance(signatureECDSA)
def sign(text: String, privateKey: PrivateKey): Array[Byte] = {
signatureInstance.initSign(privateKey)
signatureInstance.update(text.getBytes("UTF-8"))
signatureInstance.sign
}
def verify(signature: Array[Byte], publicKey: PublicKey): Boolean = {
signatureInstance.initVerify(publicKey)
signatureInstance.verify(signature)
}
def createPrivatePublicKeyPair(): Unit = {
val keyGen = KeyPairGenerator.getInstance("EC")
val ecSpec = new ECGenParameterSpec("secp256k1")
keyGen.initialize(ecSpec)
val keyPair = keyGen.generateKeyPair
val publicKey = keyPair.getPublic
val privateKey = keyPair.getPrivate
val ecPrivateKey = privateKey.asInstanceOf[ECPrivateKey]
val ecPublicKey = publicKey.asInstanceOf[ECPublicKey]
val msg = "This is a message"
val signature = sign(msg, ecPrivateKey)
System.out.println("Signature: " + new BigInteger(1, signature).toString(16))
val result = verify(signature, ecPublicKey)
System.out.println("public key matched with signature " + result)
}
Upvotes: 1
Views: 515
Reputation: 93948
The signature does encapsulate the hash over the data in some way or other. In the case of RSA signatures the hash is simply contained in the signature. In the case of ECDSA the hash is used within the signature calculation and cannot be retrieved, but it can of course still be used to verify the signature.
What is not included in the signature is the data over which the signature is calculated. Instead you need to provide the data using signatureInstance.update(text.getBytes("UTF-8"))
in the verification method, just as in the method that generates the signature.
Upvotes: 1