在Scala上验证SHA1withECDSA签名

时间:2018-05-01 10:49:45

标签: java scala digital-signature ecdsa key-pair

我正在尝试编写简单的代码来创建公钥/私钥,签名和验证ECDSA签名。我不知道为什么验证返回false。请帮帮我。

**我也尝试将提供商设置为“SunEC”,但它仍无法正常工作

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)
}

1 个答案:

答案 0 :(得分:1)

签名确实以某种方式封装散列在数据上。在RSA签名的情况下,哈希仅包含在签名中。在ECDSA的情况下,哈希在签名计算中使用并且无法检索,但它当然仍可用于验证签名。

签名中未包含的是计算签名的数据。相反,您需要在验证方法中使用signatureInstance.update(text.getBytes("UTF-8"))提供数据,就像生成签名的方法一样。