go_key_rotator

package module
v0.0.0-...-d4c0c7a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 19, 2024 License: MIT Imports: 9 Imported by: 5

README

Go Key Rotator 🔐

Golang License

Build Lint Test Go Report Card

Overview

go_key_rotator is a Go package designed for robust RSA key management. It facilitates generating, rotating, and encoding RSA private keys, and integrates seamlessly with AWS Parameter Store for secure key storage and retrieval. This package is particularly useful for applications that require cryptographic operations like token signing and data encryption.

Features

  • RSA key pair generation
  • PEM encoding for RSA keys
  • Secure storage and retrieval of keys via AWS Parameter Store
  • Automatic key rotation for enhanced security

Installation

To install go_key_rotator, use the go get command:

go get github.com/kmesiab/go_key_rotator

This will download the package along with its dependencies.

Usage

Here's a simple example of how to use go_key_rotator:

package main

import (
   "log"
   "github.com/kmesiab/go_key_rotator"
)

func main() {
   // Example: Using go_key_rotator for RSA key management

   // Create a rotator and give it a ParameterStoreInterface
   keyRotator := rotator.NewKeyRotator(
      rotator.NewAWSParameterStore(sess),
   )

   // Call Rotate and tell it where to store your keys
   // how big to make them
   privateKey, publicKey, err = keyRotator.Rotate(
      psPrivateKeyName, psPublicKeyName, 2048,
   )   
   
   if err != nil {
      log.Fatalf("Failed to rotate private key: %v", err)
   }
   
   log.Println("New RSA keys generated and stored.")
}
Get the current keys
   currentPrivateKey, err := go_key_rotator.GetCurrentRSAPrivateKey()
   if err != nil {
      log.Fatalf("Failed to retrieve current private key: %v", err)
   }

   currentPublicKey, err := go_key_rotator.GetCurrentRSAPublicKey()
   if err != nil {
      log.Fatalf("Failed to retrieve current public key: %v", err)
   }
}

Documentation

Overview

Package go_key_rotator provides a comprehensive solution for RSA key management in Go applications. It facilitates the generation, rotation, and storage of RSA private keys, ensuring secure handling and integration with AWS Parameter Store for encrypted storage. The package includes functionalities to generate new RSA keys, encode them in PEM format, and manage their lifecycle by securely storing and retrieving them from AWS Parameter Store. This aids in enhancing cryptographic practices, allowing for secure token generation and verification. The package is designed to be robust and easy to integrate into Go applications requiring high standards of security for key management and encryption.

Index

Constants

View Source
const (
	DefaultKeySize = MaxKeySize
	MinKeySize     = 2048
	MaxKeySize     = 4096
	RSATypePrivate = "RSA PRIVATE KEY"
	RSATypePublic  = "RSA PUBLIC KEY"
)

Exported constants

Variables

This section is empty.

Functions

func EncodePrivateKeyToPEM

func EncodePrivateKeyToPEM(privateKey *rsa.PrivateKey) []byte

EncodePrivateKeyToPEM converts an RSA private key into PEM (Privacy Enhanced Mail) format. PEM format is a widely used encoding format for cryptographic keys and certificates, which is essentially Base64 encoded data with additional header and footer lines.

Parameters:

privateKey - A pointer to the rsa.PrivateKey that needs to be encoded.

Returns:

A string representing the RSA private key in PEM format.

The function uses the 'pem' package from the Go standard library to perform the encoding. It takes the RSA private key, converts it into a byte slice in PKCS#1 format using 'x509.MarshalPKCS1PrivateKey', and then creates a PEM block with this byte slice. The 'Type' field of the PEM block is set to the value of 'RSAType', typically "RSA PRIVATE KEY", indicating the type of key encoded in the PEM block. Function to encode an RSA private key to PEM format

func EncodePublicKeyToPEM

func EncodePublicKeyToPEM(publicKey *rsa.PublicKey) ([]byte, error)

EncodePublicKeyToPEM to encode an RSA public key to PEM format

Types

type AWSParameterStore

type AWSParameterStore struct {
	Session *session.Session
}

AWSParameterStore is an implementation of the ParameterStoreInterface that interfaces with the AWS Parameter Store. This struct encapsulates an AWS session, which is used to interact with the AWS Simple Systems Manager (SSM) service for retrieving and storing parameters securely. AWS Parameter Store offers a centralized solution for managing configuration data and secrets, which is essential in applications requiring secure and scalable storage solutions.

The AWSParameterStore struct is designed to be used in scenarios where real interactions with AWS services are necessary, such as production environments or integration testing. By implementing the ParameterStoreInterface, it provides a standardized way to interact with parameter store services, ensuring consistency and ease of use in managing application configurations and secrets.

Fields: - Session: An AWS session used to create an SSM service client for Parameter Store interactions.

Usage: Create an instance of AWSParameterStore with an initialized AWS session to perform operations like retrieving and storing RSA keys or other sensitive configuration data in the AWS Parameter Store.

func (AWSParameterStore) GetParameter

func (p AWSParameterStore) GetParameter(name string) (string, error)

GetParameter retrieves a value from AWS Parameter Store. Parameters:

name - The name of the parameter to retrieve. This is the key used when the parameter
       was stored in the Parameter Store.

Returns:

The value of the parameter as a string and an error. If the retrieval is successful,
the error will be nil. If the retrieval fails, the returned string will be empty,
and the error will contain details about the failure.

This function is used to fetch configuration data or secrets (like private keys) from the AWS Parameter Store, which is a service that provides secure, hierarchical storage for configuration data management and secrets management. The function creates a new AWS session and uses the SSM (Simple Systems Manager) service client to retrieve the parameter. If the parameter is a SecureString, it will be automatically decrypted by the service (as indicated by 'WithDecryption' set to true) before being returned.

func (AWSParameterStore) PutParameter

func (p AWSParameterStore) PutParameter(parameterName, value, parameterType string) error

PutParameter stores a given value in the AWS Parameter Store.

Parameters:

parameterName - The name of the parameter to set in the Parameter Store.
                 This name is used as the key to retrieve the parameter later.
value - The value to be stored. In the context of RSA keys, this
                 would typically be the private key in PEM format.
parameterType - The type of the parameter, usually "String" or "SecureString".
                 "SecureString" is used for sensitive data that needs to be encrypted.

Returns:

An error if the storage operation fails, otherwise nil.

This function initializes an AWS session and uses the SSM (Simple Systems Manager) service client to store a parameter in the Parameter Store. The parameter can be a regular string or an encrypted string (SecureString) based on the 'parameterType'. The 'Overwrite' field in the PutParameterInput struct is set to true, allowing this function to update the value of an existing parameter with the same name.

type KeyRotator

type KeyRotator struct {
	ParamStore ParameterStoreInterface
}

func NewKeyRotator

func NewKeyRotator(ps ParameterStoreInterface) *KeyRotator

NewKeyRotator creates a new instance of KeyRotator with the given ParameterStore.

func (*KeyRotator) GenerateKeyPair

func (r *KeyRotator) GenerateKeyPair(size int) (*rsa.PublicKey, *rsa.PrivateKey, error)

GenerateKeyPair creates a new RSA public/private key pair of the specified size. It is a convenience function for quickly generating RSA keys for cryptographic operations. The size parameter specifies the length of the key in bits and must be at least 1024 bits to ensure a minimum level of security. The function returns a pointer to the generated RSA public key, a pointer to the RSA private key, and an error. An error is returned if the key size is less than the minimum requirement or if there is an issue in key generation.

Parameters: - size: The size of the RSA key pair to generate, in bits. Must be at least 1024 bits.

Returns: - *rsa.PublicKey: A pointer to the generated RSA public key. - *rsa.PrivateKey: A pointer to the generated RSA private key. - error: An error object, which is non-nil if there is an issue in key generation.

Usage: Use this function to quickly generate RSA key pairs for encryption, decryption, signing, or other cryptographic operations, where a specific key size is required.

func (*KeyRotator) GetCurrentRSAPrivateKey

func (r *KeyRotator) GetCurrentRSAPrivateKey(parameterStoreKey string) (*rsa.PrivateKey, error)

GetCurrentRSAPrivateKey retrieves the current RSA private key used for signing. This function fetches the private key from AWS Parameter Store, where it is stored in PEM format. The function then decodes the PEM encoded data to obtain the RSA private key and returns it for use in cryptographic operations like token signing. Returns an error if it fails to retrieve or decode the private key.

func (*KeyRotator) GetCurrentRSAPublicKey

func (r *KeyRotator) GetCurrentRSAPublicKey(parameterStoreKey string) (*rsa.PublicKey, error)

GetCurrentRSAPublicKey retrieves the current RSA public key used for operations like verifying signatures. It fetches the public key from AWS Parameter Store, where it's stored in PEM (Privacy Enhanced Mail) format.

The function performs the following steps:

  1. Fetch the PEM-encoded public key string from the AWS Parameter Store using the key name defined in parameterStoreKeyNamePublicKey.
  2. Decode the PEM encoded data to extract the RSA public key. - PEM is a Base64 encoded format with delimiters for storing cryptographic keys and is widely used for its readability.
  3. Parse the decoded PEM block to get the actual RSA public key. - This uses x509.ParsePKIXPublicKey for parsing the public key in PKIX format.
  4. Validate and assert the type of the parsed key to ensure it is an RSA public key.

Returns:

  • *rsa.PublicKey: The RSA public key retrieved and decoded from the Parameter Store.
  • error: An error object if any issue occurs during the key retrieval and decoding process. Possible errors include failure to fetch from Parameter Store, failure to decode the PEM block, or the data not being an RSA public key.

Usage: This function is typically used for cryptographic operations that require an RSA public key, such as verifying JWT tokens.

func (*KeyRotator) Rotate

func (r *KeyRotator) Rotate(
	parameterStoreKeyNamePrivateKey,
	parameterStoreKeyNamePublicKey string,
	keySize int,
) (*rsa.PrivateKey, *rsa.PublicKey, error)

Rotate generates and stores new RSA private and public keys in AWS Parameter Store with a specified key size.

This function allows specifying the size of the RSA key pair to be generated, providing flexibility in terms of security and performance.

The steps involved in this function are: 1. Generate a new RSA key pair with the provided key size. 2. Encode the private key into PEM format. 3. Extract and encode the public key from the private key into PEM format. 4. Store both keys in AWS Parameter Store as SecureStrings.

Parameters: - parameterStoreKeyNamePrivateKey: The identifier for storing the private key. - parameterStoreKeyNamePublicKey: The identifier for storing the public key. - keySize: The size of the RSA key pair to generate, in bits. - session: The AWS session for accessing Parameter Store.

Returns: - *rsa.PrivateKey: The generated RSA private key. - *rsa.PublicKey: The corresponding RSA public key. - error: Non-nil if there is an issue in key generation, encoding, or storing.

Usage: This function is used when specific control over the key size is required during key rotation, suitable for scenarios where custom key sizes are needed.

func (*KeyRotator) RotatePrivateKeyAndPublicKey

func (r *KeyRotator) RotatePrivateKeyAndPublicKey(
	parameterStoreKeyNamePrivateKey string,
	parameterStoreKeyNamePublicKey string,
	_ *session.Session,
) (*rsa.PrivateKey, *rsa.PublicKey, error)

RotatePrivateKeyAndPublicKey [DEPRECATED] generates and stores new RSA private and public keys in AWS Parameter Store using a default key size.

This function is a convenience wrapper around the Rotate function, using a predefined default key size (DefaultKeySize). It performs the same steps as Rotate but without the need to specify the key size. The steps are:

1. Generate a new RSA key pair with the default key size (DefaultKeySize). 2. Encode the private key into PEM format. 3. Extract and encode the public key from the private key into PEM format. 4. Store both keys in AWS Parameter Store as SecureStrings.

Parameters: - parameterStoreKeyNamePrivateKey: The identifier for storing the private key. - parameterStoreKeyNamePublicKey: The identifier for storing the public key. - session: (UNUSED) The AWS session for accessing Parameter Store.

Returns: - *rsa.PrivateKey: The generated RSA private key. - *rsa.PublicKey: The corresponding RSA public key. - error: Non-nil if there is an issue in key generation, encoding, or storing.

Usage: This function is intended for standard key rotation scenarios where the default key size is sufficient.

type MockParameterStore

type MockParameterStore struct {
	Parameters map[string]string
	// contains filtered or unexported fields
}

MockParameterStore with error simulation capability

func NewMockParameterStore

func NewMockParameterStore(simulateError bool) *MockParameterStore

NewMockParameterStore creates and returns a new instance of MockParameterStore. It initializes the Parameters map, ready to be used for storing and retrieving parameters.

func (*MockParameterStore) GetParameter

func (m *MockParameterStore) GetParameter(name string) (string, error)

func (*MockParameterStore) PutParameter

func (m *MockParameterStore) PutParameter(name, value, _ string) error

func (*MockParameterStore) SimulateError

func (m *MockParameterStore) SimulateError(simulate bool)

type ParameterStoreInterface

type ParameterStoreInterface interface {
	GetParameter(name string) (string, error)
	PutParameter(name, value, parameterType string) error
}

func NewAWSParameterStore

func NewAWSParameterStore(session *session.Session) ParameterStoreInterface

NewAWSParameterStore creates and returns a new instance of AWSParameterStore. This function accepts an AWS session and returns an AWSParameterStore struct that implements the ParameterStoreInterface. The returned instance is used to interact with the AWS Parameter Store service, allowing for the storage and retrieval of parameters such as configuration settings or cryptographic keys.

Parameters:

  • session: An initialized AWS session that provides the necessary configuration and credentials for accessing AWS services.

Returns:

  • ParameterStoreInterface: An instance of AWSParameterStore which can be used to interact with the AWS Parameter Store.

Usage: Use this function to create an AWSParameterStore instance when you need to perform operations on the AWS Parameter Store in your application. This is particularly useful for scenarios requiring direct interaction with AWS services for parameter management.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL