如何使用Go创建PKCS#8私钥

时间:2018-02-16 11:31:57

标签: go pkcs#1 pkcs#8

我想生成tls证书。

首先我需要私钥。

-----BEGIN PRIVATE KEY-----
BASE64 ENCODED DATA
-----END PRIVATE KEY-----

但是,我可以生成 RSA 私钥

// "crypto/rsa"
rsa.GenerateKey(cryptorand.Reader, 2048)

让我跟随

-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----

我无法使用它。我需要PKCS#8私钥以BEGIN PRIVATE KEY

开头

如何生成PKCS#8私钥?

或者有没有办法将PKCS#1转换为PKCS#8密钥?

2 个答案:

答案 0 :(得分:0)

以下是基于the custom PKCS#8 marshal function in this answer的解决方案:

package main

import (
  "crypto/rand"
  "crypto/rsa"
  "crypto/x509"
  "encoding/asn1"
  "encoding/pem"
  "fmt"
)

type PKCS8Key struct {
  Version             int
  PrivateKeyAlgorithm []asn1.ObjectIdentifier
  PrivateKey          []byte
}

func MarshalPKCS8PrivateKey(key *rsa.PrivateKey) ([]byte, error) {
  var pkey PKCS8Key
  pkey.Version = 0
  pkey.PrivateKeyAlgorithm = make([]asn1.ObjectIdentifier, 1)
  pkey.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
  pkey.PrivateKey = x509.MarshalPKCS1PrivateKey(key)
  return asn1.Marshal(pkey)
}

func main() {
  // Generate the private key.
  privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
  fatal(err)

  // Encode the private key into PEM data.
  bytes, err := MarshalPKCS8PrivateKey(privateKey)
  fatal(err)
  privatePem := pem.EncodeToMemory(
    &pem.Block{
      Type:  "PRIVATE KEY",
      Bytes: bytes,
    },
  )
  fmt.Printf("%s\n", privatePem)
  // -----BEGIN PRIVATE KEY-----
  // MIIEvAIBADALBgkqhkiG9w0BAQEEggSoMIIEpAIBAAKCAQEAz5xD5cdqdE0PMmk1
  // 4YN6Tj0ybTsvS5C95ogQmBJ4bGxiuGPR5JtIc+UmT8bnCHtK5xnHiP+gPWunwmhS
  // ...
  // qpb1NZsMLz2lRXqx+3Pq7Q==
  // -----END PRIVATE KEY-----
}

func fatal(err error) {
  if err != nil {
    panic(err)
  }
}

答案 1 :(得分:0)

我不知道你究竟是怎么得到文字-----开始RSA私钥----- Go stdlib crypto没有PKCS#8 marshaller,但asn1.Marchal()中有通用encoding/asn1,PKCS#8标准(rfc5208)提供ASN#1语法定义,所以你可以这样做:

import (
    "crypto/rsa"
    "crypto/x509"
    "encoding/asn1"
)
type Pkcs8Key struct {
    Version             int
    PrivateKeyAlgorithm []asn1.ObjectIdentifier
    PrivateKey          []byte
}
func RsaToPkcs8(key *rsa.PrivateKey) ([]byte, error) {
    var pkey Pkcs8Key
    pkey.Version = 0
    pkey.PrivateKeyAlgorithm = make([]asn1.ObjectIdentifier, 1)
    pkey.PrivateKeyAlgorithm[0] = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
    pkey.PrivateKey = x509.MarshalPKCS1PrivateKey(key)

    return asn1.Marshal(pkey)
}