Aqui está meu código:
package main
import (
"encoding/pem"
"encoding/base64"
"crypto/x509"
"crypto/rsa"
"fmt"
)
func main() {
key := `-----BEGIN PRIVATE KEY-----
MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqPfgaTEWEP3S9w0t
gsicURfo+nLW09/0KfOPinhYZ4ouzU+3xC4pSlEp8Ut9FgL0AgqNslNaK34Kq+NZ
jO9DAQIDAQABAkAgkuLEHLaqkWhLgNKagSajeobLS3rPT0Agm0f7k55FXVt743hw
Ngkp98bMNrzy9AQ1mJGbQZGrpr4c8ZAx3aRNAiEAoxK/MgGeeLui385KJ7ZOYktj
hLBNAB69fKwTZFsUNh0CIQEJQRpFCcydunv2bENcN/oBTRw39E8GNv2pIcNxZkcb
NQIgbYSzn3Py6AasNj6nEtCfB+i1p3F35TK/87DlPSrmAgkCIQDJLhFoj1gbwRbH
/bDRPrtlRUDDx44wHoEhSDRdy77eiQIgE6z/k6I+ChN1LLttwX0galITxmAYrOBh
BVl433tgTTQ=
-----END PRIVATE KEY-----`
var ciphertext = "L812/9Y8TSpwErlLR6Bz4J3uR/T5YaqtTtB5jxtD1qazGPI5t15V9drWi58colGOZFeCnGKpCrtQWKk4HWRocQ==";
keyBytes := []byte(key)
decodedKey, _ := pem.Decode(keyBytes)
privateKey, err := x509.ParsePKCS8PrivateKey(decodedKey.Bytes)
if err != nil {
panic(err)
}
ciphertextBytes, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
panic(err)
}
plaintextBytes, err := privateKey.Decrypt(nil, ciphertextBytes, &rsa.PKCS1v15DecryptOptions{})
if err != nil {
panic(err)
}
plaintext := string(plaintextBytes[:])
fmt.Println(plaintext)
}
Quando eu executo eu recebo privateKey.Decrypt undefined (type any has no field or method Decrypt)
.
Superficialmente, parece que isso pode ser causado por uma chave PKCS8 inválida, mas acredito que a chave seja válida. Infelizmente, não tenho conhecimento de uma maneira de testar sua validade com a ferramenta pkcs8 do OpenSSL . Com a ferramenta rsa do OpenSSL e com a ferramenta x509 do OpenSSL você pode usar a -text
opção, mas a ferramenta pkcs8 não tem essa opção. Em vez disso, aqui está a saída do asn1parse:
0:d=0 hl=4 l= 340 cons: SEQUENCE
4:d=1 hl=2 l= 1 prim: INTEGER :00
7:d=1 hl=2 l= 13 cons: SEQUENCE
9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
20:d=2 hl=2 l= 0 prim: NULL
22:d=1 hl=4 l= 318 prim: OCTET STRING
ParsePKCS8PrivateKey
retorna umany
tipo de chave as, que é um alias deinterface{}
, veja aqui . O pano de fundo é que o PKCS#8 pode conter diferentes tipos de chave, por exemplo, RSA, chave EC, etc.O tipo de chave concreto deve, portanto, ser determinado por meio de uma afirmação de tipo , no caso de RSA, que se aplica aqui:
privateKey.(*rsa.PrivateKey)
.Possível correção:
ou alternativamente: