编程网今天将给大家带来《使用Java验证Golang中创建的签名》,感兴趣的朋友请继续看下去吧!以下内容将会涉及到等等知识点,如果你是正在学习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布尔值总是假的,我做错了什么吗?
解决方案
我能够验证签名。我在这里发帖以防有人遇到同样的问题:
在 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。不知道为什么。
我昨天也遇到了这个问题,最后解决了。
这可能对其他人有帮助:https://github.com/xioxu/signature_in_multiple_lang
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用Java验证Golang中创建的签名》文章吧,也可关注编程网公众号了解相关技术文章。