这是我的代码:
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)
}
当我运行它时,我得到了privateKey.Decrypt undefined (type any has no field or method Decrypt)
。
从表面上看,这似乎是由无效的 PKCS8 密钥引起的,但我相信该密钥是有效的。不幸的是,我不知道如何使用OpenSSL 的 pkcs8 工具测试其有效性。使用OpenSSL 的 rsa 工具和OpenSSL 的 x509 工具,您可以使用该-text
选项,但 pkcs8 工具没有这样的选项。取而代之的是 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
返回一个any
as key 类型,它是 的别名interface{}
,请参见此处。背景是 PKCS#8 可以包含不同的密钥类型,例如 RSA、EC 密钥等。因此,在 RSA 的情况下,具体密钥类型必须通过类型断言来确定,这适用于此处: 。
privateKey.(*rsa.PrivateKey)
可能的修复:
或者: