go-http-peering/crypto/pem.go

75 lines
1.5 KiB
Go
Raw Permalink Normal View History

2019-02-03 20:56:58 +01:00
package crypto
import (
2019-02-22 17:35:49 +01:00
"crypto"
"crypto/rand"
2019-02-03 20:56:58 +01:00
"crypto/rsa"
"crypto/x509"
"encoding/pem"
jwt "github.com/dgrijalva/jwt-go"
2022-09-12 17:46:59 +02:00
"github.com/pkg/errors"
2023-11-21 14:13:32 +01:00
"golang.org/x/crypto/ssh"
2019-02-03 20:56:58 +01:00
)
2019-02-22 17:35:49 +01:00
func EncodePublicKeyToPEM(key crypto.PublicKey) ([]byte, error) {
2019-02-03 20:56:58 +01:00
pub, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
2022-09-12 17:46:59 +02:00
return nil, errors.WithStack(err)
2019-02-03 20:56:58 +01:00
}
data := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: pub,
})
return data, nil
}
2019-02-22 17:35:49 +01:00
func DecodePEMToPublicKey(pem []byte) (crypto.PublicKey, error) {
2019-02-03 20:56:58 +01:00
return jwt.ParseRSAPublicKeyFromPEM(pem)
}
2019-02-22 17:35:49 +01:00
func DecodePEMEncryptedPrivateKey(key []byte, passphrase []byte) (*rsa.PrivateKey, error) {
2023-11-21 14:13:32 +01:00
var (
rawKey interface{}
err error
)
2019-02-22 17:35:49 +01:00
2023-11-21 14:13:32 +01:00
if len(passphrase) == 0 {
rawKey, err = ssh.ParseRawPrivateKey(key)
} else {
rawKey, err = ssh.ParseRawPrivateKeyWithPassphrase(key, passphrase)
2019-02-22 17:35:49 +01:00
}
2023-11-21 14:13:32 +01:00
if err != nil {
2022-09-12 17:46:59 +02:00
return nil, errors.WithStack(err)
2019-02-22 17:35:49 +01:00
}
var privateKey *rsa.PrivateKey
var ok bool
2023-11-21 14:13:32 +01:00
if privateKey, ok = rawKey.(*rsa.PrivateKey); !ok {
2019-02-22 17:35:49 +01:00
return nil, errors.New("invalid RSA private key")
}
return privateKey, nil
}
func EncodePrivateKeyToEncryptedPEM(key *rsa.PrivateKey, passphrase []byte) ([]byte, error) {
if passphrase == nil {
return nil, errors.New("passphrase cannot be empty")
}
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
block, err := x509.EncryptPEMBlock(
rand.Reader, block.Type,
block.Bytes, passphrase, x509.PEMCipherAES256,
)
if err != nil {
2022-09-12 17:46:59 +02:00
return nil, errors.WithStack(err)
2019-02-22 17:35:49 +01:00
}
return pem.EncodeToMemory(block), nil
}