我有加密的字串和非對稱 RSA 密鑰。該字串由 PHP 及其函式openssl_public_encrypt用密鑰的公共部分和 PKCS#1 v1.5 填充進行加密。我想用 Go lang 和密鑰的私有部分解密加密的字串。
我知道如何在 PHP 中解密它:
<?php
$encrypted = file_get_contents('./encryptedString.txt');
$privKey = file_get_contents('./private.key');
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $privKey);
print_r($decrypted);
我知道如何在 Bash 中解密它:
#!/bin/bash
cat encryptedString.txt | base64 -d > encryptedString64.txt
openssl rsautl -decrypt -in ./encryptedString64.txt -inkey ./private.key
我想在 GO lang 中以相同的方式解密字串。我已經嘗試過crypto/rsa包中的一些功能:
func DecryptString(privKey *rsa.PrivateKey, encryptedString []byte) ([]byte, error) {
decryptedBytes, err := rsa.DecryptOAEP(sha256.New(), nil, privKey, encryptedString, nil)
if err != nil {
return nil, err
}
return decryptedBytes, nil
}
func GetPrivateKey() (*rsa.PrivateKey, error) {
pemString := `******************`
block, _ := pem.Decode([]byte(pemString))
parseResult, _ := x509.ParsePKCS8PrivateKey(block.Bytes)
key := parseResult.(*rsa.PrivateKey)
return key, nil
}
...但我仍然收到錯誤“crypto/rsa:解密錯誤”或空結果。我錯過了什么?
uj5u.com熱心網友回復:
謝謝大家的意見。我已經解決了,我在下面發布了解決方案。
func main() {
privateKeyB, err := ioutil.ReadFile("private.key")
if err != nil {
log.Fatal("Failed to read private key - " err.Error())
}
block, _ := pem.Decode(privateKeyB)
parseResult, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
log.Fatal("Failed to parse private key - " err.Error())
}
privateKey := parseResult.(*rsa.PrivateKey)
encStringB, err := ioutil.ReadFile("encryptedString.txt")
if err != nil {
log.Fatal("Failed to read encrypted string - " err.Error())
}
encString64, err := base64.StdEncoding.DecodeString(string(encStringB))
if err != nil {
log.Fatal("Failed to decode encrypted string to base64 - " err.Error())
}
decryptedB, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, encString64)
if err != nil {
log.Fatal("Failed to decrypt string - " err.Error())
}
fmt.Println(string(decryptedB))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/362239.html
上一篇:Linux和Windows如何將檔案打包成一個可執行檔案?
下一篇:通過PuTTY與TCP服務器通信
