ParsePKCS8PrivateKey 未解析我的 PKCS8 编码密钥

问题描述 投票:0回答:1

这是我的代码:

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
go rsa private-key pkcs#8
1个回答
1
投票

ParsePKCS8PrivateKey
返回
any
作为键类型,它是
interface{}
的别名,请参阅 here。背景是 PKCS#8 可以包含不同的密钥类型,例如RSA、EC 密钥等
因此,在 RSA 的情况下,具体密钥类型必须通过类型断言来确定,这适用于此处:
privateKey.(*rsa.PrivateKey)

可能的修复:

plaintextBytes, err := privateKey.(*rsa.PrivateKey).Decrypt(nil, ciphertextBytes, &rsa.PKCS1v15DecryptOptions{})

或者:

plaintextBytes, err := rsa.DecryptPKCS1v15(nil, privateKey.(*rsa.PrivateKey), ciphertextBytes)
© www.soinside.com 2019 - 2024. All rights reserved.