package routecrypto

import (
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
)

// RSAPrivateKeyToPem takes an RSA private key and formats it in PEM-encoded bytes.
func RSAPrivateKeyToPem(k *rsa.PrivateKey) []byte {
	pemblock := &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: x509.MarshalPKCS1PrivateKey(k),
	}
	return pem.EncodeToMemory(pemblock)
}

// PemToRSAPrivateKey takes a PEM-encoded rsa private key and returns it.
func PemToRSAPrivateKey(data []byte) (*rsa.PrivateKey, error) {
	var block *pem.Block

	block, _ = pem.Decode([]byte(data))
	pKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	return pKey, nil
}
