使用 Java 验证在 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 布尔值始终为假,我做错了什么吗?


千万里不及你
浏览 167回答 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 gobyte[] signatureDecoded = Base64.getDecoder().decode(signatureString);boolean endorserSignatureIsValid = signature.verify(signatureDecoded);//It is now valid我无法使用 Base64.getDecoder() (java.lang.IllegalArgumentException: Illegal base64 character a) 来解码 publicKeyPEM,所以我使用了 BASE64Decoder。不知道为什么。

紫衣仙女

我昨天也遇到这个问题,最后解决了。它可能对其他人有帮助:https ://github.com/xioxu/signature_in_multiple_lang
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go