使用 Java 验证在 Golang 中创建的签名

Using Java to verify signature created in Golang

我正在用 Go 创建签名,例如:

//I'm reading a file with -----BEGIN RSA PRIVATE KEY-----
privateKeyPem := strings.Replace(privateKeyString, `\n`, "\n", -1) //file has '/n' instead of break lines for dev purposes
block, _ := pem.Decode([]byte(privateKeyPem))
key, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
hashedString := sha256.Sum256([]byte(stringTosign))
signature, err = rsa.SignPKCS1v15(rand.Reader, key, crypto2.SHA256, hashedString[:])
signatureString := base64.StdEncoding.EncodeToString(signature)

Java 程序接收变量 signatureString 并执行:

byte[] keyBytes = Files.readAllBytes(Paths.get("./golangSignerPubKey.der"));
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey publicKey =  kf.generatePublic(spec);
Signature signature = Signature.getInstance("SHA256withRSA", "BC");
signature.initVerify(publicKey);
signature.update(stringUnsigned.getBytes());
boolean signatureIsValid = signature.verify(Base64.getDecoder().decode(signatureString.getBytes()));

但是 signatureIsValid 布尔值始终为 false,我做错了什么吗?

我能够验证签名。我在这里发帖以防有人遇到同样的问题:

Go 中的签名创建:

bytesToSign := []byte (stringToSign)
block, err8 := pem.Decode([]byte(privateKeyPem)) //-----BEGIN RSA PRIVATE KEY----
if err8 != nil {
    logger.Debugf("Error trying decode endorser private key")
}
key, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
h := sha256.New()
h.Write(bytesToSign)
d := h.Sum(nil)
signature, err = rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, d)
if err != nil {
    panic(err)
}
signatureString = base64.StdEncoding.EncodeToString(signature)

Java中的签名验证(接收signatureString): 我在 .pub 文件中有 public 键,并且:

byte[] keyBytes = Files.readAllBytes(Paths.get("./public_key.pub"));
String temp = new String(keyBytes);
String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKeyPEM = publicKeyPEM.replace("\n-----END PUBLIC KEY-----", "");
BASE64Decoder b64= new BASE64Decoder();
byte[] decoded = b64.decodeBuffer(publicKeyPEM);
X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
publicKey = kf.generatePublic(spec);
Signature signature = Signature.getInstance("SHA256withRSA", "BC");
signature.initVerify(publicKey);
signature.update(bytesToVerify); //bytesToVerify = bytesToSign in go
byte[] signatureDecoded = Base64.getDecoder().decode(signatureString);
boolean endorserSignatureIsValid = signature.verify(signatureDecoded);
//It is now valid

我无法使用 Base64.getDecoder()(java.lang.IllegalArgumentException:非法 base64 字符 a)来解码 publicKeyPEM,所以我使用了 BASE64Decoder。不知道为什么。

我昨天也遇到了这个问题,终于解决了。

可能对其他人有帮助:https://github.com/xioxu/signature_in_multiple_lang