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

问题描述 投票:4回答:1

例如,我正在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布尔值始终为假,我做错了吗?

java go digital-signature x509
1个回答
1
投票

我能够验证签名。我张贴在这里,以防有人遇到相同的问题:

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文件中有公钥,并且:

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。不知道为什么。

© www.soinside.com 2019 - 2024. All rights reserved.