WritePrivateKeyToFile writes the private key to a given file.
(fname string, priv *rsa.PrivateKey)
| 88 | |
| 89 | // WritePrivateKeyToFile writes the private key to a given file. |
| 90 | func WritePrivateKeyToFile(fname string, priv *rsa.PrivateKey) (err error) { |
| 91 | f, err := os.OpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, privateKeyFileMode) //nolint:gosec |
| 92 | if err != nil { |
| 93 | return errors.Wrap(err, "error opening private key file") |
| 94 | } |
| 95 | |
| 96 | defer func() { |
| 97 | err = stderrors.Join(err, f.Close()) |
| 98 | }() |
| 99 | |
| 100 | privBytes, err := x509.MarshalPKCS8PrivateKey(priv) |
| 101 | if err != nil { |
| 102 | return errors.Wrap(err, "Unable to marshal private key") |
| 103 | } |
| 104 | |
| 105 | if err := pem.Encode(f, &pem.Block{Type: "PRIVATE KEY", Bytes: privBytes}); err != nil { |
| 106 | return errors.Wrap(err, "Failed to write data to") |
| 107 | } |
| 108 | |
| 109 | return nil |
| 110 | } |
| 111 | |
| 112 | // WriteCertificateToFile writes the certificate to a given file. |
| 113 | func WriteCertificateToFile(fname string, cert *x509.Certificate) (err error) { |