I have encrypted string and asymmetric RSA key. The string was encrypted by PHP and its function openssl_public_encrypt
with public part of the key and PKCS#1 v1.5 padding. I want to decrypt encrypted string with Go lang and private part of the key.
I know how to decrypt it in 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);
I know how to decrypt it in Bash:
#!/bin/bash
cat encryptedString.txt | base64 -d > encryptedString64.txt
openssl rsautl -decrypt -in ./encryptedString64.txt -inkey ./private.key
I want to decrypt the string in the same way in GO lang. I've already tried some function from crypto/rsa
package:
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
}
...but I'm still getting error "crypto/rsa: decryption error" or empty results. What am I missing?
CodePudding user response:
Thank you all for your comments. I have solved it and I am posting the solution below.
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))
}