cryptography

package
v0.0.1-20260114-103824... Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package cryptography provides RSA-AES hybrid encryption utilities:

  • GenerateRSAKeypair: create RSA private/public keypair (4096 bits)
  • SavePrivateKeyPEM / SavePublicKeyPEM: write keys to disk as PEM
  • LoadPrivateKeyPEM / LoadPublicKeyPEM: load keys from PEM files
  • EncryptWithPublicKey: hybrid encrypt using RSA-OAEP (SHA-256) + AES-256-GCM
  • DecryptWithPrivateKey: hybrid decrypt
  • SignWithPrivateKey / VerifyWithPublicKey: optional signing using RSA-PSS (SHA-256)

High-level format for encrypted blob returned by EncryptWithPublicKey:

[2 bytes big-endian len of encKey][encKey][12 bytes GCM nonce][ciphertext-with-gcm-tag]

Security notes:

  • RSA 4096 bits for envelope encryption (OAEP + SHA-256).
  • AES-256-GCM for symmetric encryption (authenticated).
  • Nonce is 12 bytes as required by GCM.
  • Use crypto/rand for all randomness.
  • Protect private keys (filesystem permissions, secret stores, etc.).

Index

Constants

View Source
const (
	PRIVATE_KEY = "PRIVATE KEY"
	PUBLIC_KEY  = "PUBLIC KEY"
)
View Source
const (
	RSA_PRIVATE_KEY = "RSA PRIVATE KEY"
)

Variables

View Source
var DefaultHashSizeBytes = getDefaultHashSize()

DefaultHashSizeBytes defines the default hash output size (in bytes). You can override this by setting the environment variable HASH_SIZE (1–32).

Functions

func CompareHash

func CompareHash(hash1, hash2 string) bool

CompareHash safely compares two hash strings in constant time.

Returns true if they match, false otherwise.

Example:

ok := CompareHash(storedHash, receivedHash)
if ok { ... }

func Generate128BitHash

func Generate128BitHash(key, data []byte) (string, error)

Generate128BitHash creates a small, secure keyed hash using BLAKE2s.

Parameters:

  • key: secret key (recommended at least 16 bytes)
  • data: input to hash (e.g., OTP, message, etc.)

Returns:

  • base64-url-safe string (no padding)

Example:

hash, err := Generate128BitHash([]byte("key123"), []byte("otp-123456"))
fmt.Println("Hash:", hash)

func Generate16ByteKeyString

func Generate16ByteKeyString() (string, error)

Generate16ByteKeyString returns a random 16-byte key as a hex string

func Generate256BitHash

func Generate256BitHash(key, data []byte) (string, error)

Generate256BitHash creates a small, secure keyed hash using BLAKE2s.

Parameters:

  • key: secret key (recommended at least 16 bytes)
  • data: input to hash (e.g., OTP, message, etc.)

Returns:

  • base64-url-safe string (no padding)

Example:

hash, err := Generate256BitHash([]byte("key123"), []byte("otp-123456"))
fmt.Println("Hash:", hash)

func Generate32ByteKeyString

func Generate32ByteKeyString() (string, error)

Generate32ByteKeyString returns a random 32-byte key as a hex string

func GenerateAndSaveEd25519KeyPair

func GenerateAndSaveEd25519KeyPair(publicKeyPath, privateKeyPath string) error

GenerateAndSaveEd25519KeyPair generates a new Ed25519 key pair and saves the PEM-encoded keys to the specified files.

func GenerateAndSaveRSAKeypair

func GenerateAndSaveRSAKeypair(publicKeyPath, privateKeyPath string) error

func GenerateByteKeyString

func GenerateByteKeyString(length int) (string, error)

GenerateByteKeyString returns a random key of specified length as a hex string

func GenerateEd25519KeyPair

func GenerateEd25519KeyPair() (string, string, error)

GenerateEd25519KeyPair generates a new Ed25519 key pair and returns the PEM-encoded public and private keys.

func GenerateHash

func GenerateHash(key, data []byte, size int) (string, error)

func GenerateRSAKeypair

func GenerateRSAKeypair(bits int) (*rsa.PrivateKey, error)

GenerateRSAKeypair generates an RSA private key of given bits (recommend 4096).

func LoadEd25519PrivateKey

func LoadEd25519PrivateKey(filePath string, content []byte) (ed25519.PrivateKey, error)

LoadEd25519PrivateKey loads an Ed25519 private key from a PEM file or []byte content

func LoadEd25519PublicKey

func LoadEd25519PublicKey(filePath string, content []byte) (ed25519.PublicKey, error)

LoadEd25519PublicKey loads an Ed25519 public key from a PEM file or []byte content

func LoadRSAPrivateKeyPEM

func LoadRSAPrivateKeyPEM(path string) (*rsa.PrivateKey, error)

LoadRSAPrivateKeyPEM loads a PKCS#1 PEM-encoded RSA private key.

func LoadRSAPublicKeyPEM

func LoadRSAPublicKeyPEM(path string) (*rsa.PublicKey, error)

LoadRSAPublicKeyPEM loads a PKIX PEM-encoded RSA public key.

func SavePrivateKeyPEM

func SavePrivateKeyPEM(path string, priv *rsa.PrivateKey) error

SavePrivateKeyPEM saves a PKCS#1 PEM-encoded RSA private key.

func SavePublicKeyPEM

func SavePublicKeyPEM(path string, pub *rsa.PublicKey) error

SavePublicKeyPEM saves a PKIX (X.509) PEM-encoded RSA public key.

Types

type CryptoManager

type CryptoManager struct {
	// contains filtered or unexported fields
}

CryptoManager wraps RSA key management, encryption, and signing.

func NewCryptoManager

func NewCryptoManager(opts ...Option) (*CryptoManager, error)

NewCryptoManager initializes a CryptoManager with optional parameters.

func (*CryptoManager) Decrypt

func (c *CryptoManager) Decrypt(value string) ([]byte, error)

Decrypt reverses Encrypt:

  • Reads encKey length + encKey
  • Decrypts encKey using RSA-OAEP to obtain AES key
  • Uses AES-GCM with nonce to decrypt ciphertext

func (*CryptoManager) Encrypt

func (c *CryptoManager) Encrypt(plaintext []byte) (string, error)

Encrypt performs hybrid encryption:

  • Generates ephemeral AES-256 key
  • Encrypts plaintext using AES-GCM
  • Encrypts AES key using RSA-OAEP(SHA-256)
  • Returns concatenation: [2-byte len][encKey][12-byte nonce][ciphertext+tag]

func (*CryptoManager) PrivateKey

func (c *CryptoManager) PrivateKey() *rsa.PrivateKey

PrivateKey returns the private key.

func (*CryptoManager) PublicKey

func (c *CryptoManager) PublicKey() *rsa.PublicKey

PublicKey returns the public key.

func (*CryptoManager) SaveKeys

func (c *CryptoManager) SaveKeys(privPath, pubPath string) error

SaveKeys saves private and public keys to PEM files.

func (*CryptoManager) Sign

func (c *CryptoManager) Sign(data []byte) ([]byte, error)

Sign signs the given data using RSA-PSS.

func (*CryptoManager) Verify

func (c *CryptoManager) Verify(data, sig []byte) error

Verify verifies a signature using the public key.

type Option

type Option func(*CryptoManager) error

Option defines a function type for functional options.

func WithHash

func WithHash(hash crypto.Hash) Option

WithHash sets the hash algorithm (default: SHA256).

func WithKeyPair

func WithKeyPair(priv *rsa.PrivateKey, pub *rsa.PublicKey) Option

WithKeyPair allows providing existing RSA keys. If both private and public keys are provided, they will be used as is. If neither private nor public key is provided, we will need a environment variable to get the private and public key path MUST have the environment variable RSA_PRIVATE_KEY_PATH and RSA_PUBLIC_KEY_PATH set

func WithKeySize

func WithKeySize(bits int) Option

WithKeySize sets RSA key size (default: 4096).

func WithPrivateKey

func WithPrivateKey(priv *rsa.PrivateKey) Option

WithPrivateKey allows providing existing RSA private key. MUST have the environment variable RSA_PRIVATE_KEY_PATH set if the priv is nil

func WithPublicKey

func WithPublicKey(pub *rsa.PublicKey) Option

WithPublicKey allows providing existing RSA public key. MUST have the environment variable RSA_PUBLIC_KEY_PATH set if the pub is nil

Jump to

Keyboard shortcuts

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