我正在尝试使用java验证ECDSA签名,该密钥是使用golang创建的:
preferredDisplayMode = .primaryOverlay
签名发生在这里:(消息是使用此方法由golang编码的):
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"reflect"
)
func doit(){
privateKey, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
publicKey := &privateKey.PublicKey
if !elliptic.P384().IsOnCurve(publicKey.X, publicKey.Y) {
fmt.Printf(" public key invalid. ")
}
encPriv, encPub := encode(privateKey, publicKey)
fmt.Println(encPriv)
fmt.Println(encPub)
}
解码方面正在发生:
func SignMessage(message []byte) (r *big.Int, s *big.Int, err error) {
zero := big.NewInt(0)
// Hash message:
h := sha1.New()
io.WriteString(h, string(message))
hashBytes := h.Sum(nil)
hash := fmt.Sprintf("%x", hashBytes)
// hash message
// get private key from disk:
pemEncoded, err := ioutil.ReadFile("./ecc/eccpriv.pem")
if err != nil {
return zero, zero, err
}
pemEncodedPub, err := ioutil.ReadFile("./ecc/eccpub.pem")
if err != nil {
return zero, zero, err
}
var priv *ecdsa.PrivateKey
//var _pub *ecdsa.PublicKey
priv, _, err = ECCDecodeFromPem(pemEncoded, pemEncodedPub)
if err != nil {
return zero, zero, err
}
r, s, err = ecdsa.Sign(rand.Reader, priv, []byte(hash))
if err != nil {
return zero, zero, err
}
return r, s, nil
}
但是,不幸的是,该程序失败是因为:
//Verify Response
String signature = ac.getECCDSAPublicKeyFromServer();
String cleanSignature = ac.cleanBytes(signature);
byte[] bSignature = Base64.getDecoder().decode(cleanSignature);
System.out.println(cleanSignature);
PublicKey ecdsaPublicKey = ac.getPemPublicKeyFromString(signature,"ECDSA");
//PublicKey ecdsaPublicKey = ac.getECDSAKeyFromBytes(cleanSignature.getBytes("UTF-8"));
Signature ecdsaVerify = Signature.getInstance("ECDSA", "BC");
ecdsaVerify.initVerify(ecdsaPublicKey);
ecdsaVerify.update(json_response.getBytes("UTF-8"));
System.out.println("SIG:");
for(int i=0;i<bSignature.length;i++){
System.out.println(bSignature[i]);
}
System.out.println(new String(bSignature, StandardCharsets.UTF_8));
System.out.println("/SIG");
boolean result = ecdsaVerify.verify(bSignature);
System.out.println("Result is:"+result);
由于公共密钥,这会引起一个有趣的困境:
Exception in thread "main" java.security.SignatureException: error decoding signature bytes.
at org.bouncycastle.jcajce.provider.asymmetric.util.DSABase.engineVerify(Unknown Source)
at java.base/java.security.Signature$Delegate.engineVerify(Signature.java:1245)
at java.base/java.security.Signature.verify(Signature.java:674)
at ...
根据此网站,看来是正确的:
密钥已正确生成,并且ASN.1 Parse对其进行了正确解码。 为什么Java不喜欢我的代码?
另外,请原谅我的缩进。
答案 0 :(得分:1)
我认为您的问题在这里:
hash := fmt.Sprintf("%x", hashBytes)
而且您必须直接将hashBytes传递给
r, s, err = ecdsa.Sign(rand.Reader, priv, hashBytes)