...

Source file src/edge-infra.dev/pkg/edge/iam/crypto/rsa.go

Documentation: edge-infra.dev/pkg/edge/iam/crypto

     1  package crypto
     2  
     3  import (
     4  	"crypto/rand"
     5  	"crypto/rsa"
     6  	"crypto/x509"
     7  	"encoding/pem"
     8  )
     9  
    10  // CreatePrivateKey generates an RSA keypair
    11  func CreatePrivateKey() *rsa.PrivateKey {
    12  	pk, _ := rsa.GenerateKey(rand.Reader, 4096)
    13  	return pk
    14  }
    15  
    16  // Serialize an rsa.PrivateKey
    17  func Serialize(privateKey *rsa.PrivateKey) string {
    18  	// Use x509 to encode the private key
    19  	privateKeyBytes, _ := x509.MarshalPKCS8PrivateKey(privateKey)
    20  
    21  	// Use pem to encode the private key
    22  	privateKeyPem := pem.EncodeToMemory(
    23  		&pem.Block{
    24  			Type:  "PRIVATE KEY",
    25  			Bytes: privateKeyBytes,
    26  		},
    27  	)
    28  
    29  	return string(privateKeyPem)
    30  }
    31  
    32  // Deserialize a string back to a rsa.PrivateKey
    33  func Deserialize(serializedPK string) *rsa.PrivateKey {
    34  	// Decode the PEM encoded private key
    35  	block, _ := pem.Decode([]byte(serializedPK))
    36  
    37  	// Decode the x509 encoded private key
    38  	privateKey, _ := x509.ParsePKCS8PrivateKey(block.Bytes)
    39  
    40  	return privateKey.(*rsa.PrivateKey)
    41  }
    42  

View as plain text