cryptography

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2025 License: ISC Imports: 25 Imported by: 0

README

Cryptography Library

GitHub Tag Go Reference License Go Report Card Contributors Issues

This library provides a comprehensive set of cryptographic utilities for hashing, encryption, and key management. It supports both symmetric and asymmetric cryptography, as well as various hashing algorithms.

Features

  • Symmetric encryption using AES-GCM.
  • Asymmetric encryption using RSA.
  • Hashing with Argon2, bcrypt, and HMAC.
  • Key generation and parsing utilities.

Installation

To use this library, add it to your Go project:

go get github.com/go-universal/cryptography

API Documentation

Symmetric Encryption

Creates a new symmetric encryption driver.

func NewSymmetric(key SimpleKey, signer HashingAlgo) Cryptography
key, _ := cryptography.NewSimpleKey(cryptography.Simple32)
driver := cryptography.NewSymmetric(key, cryptography.SHA256)

data := []byte("my secret data")

// Encrypt
encrypted, _ := driver.EncryptBase64(data)

// Decrypt
decrypted, _ := driver.DecryptBase64(encrypted)
fmt.Println(string(decrypted)) // Output: my secret data
Asymmetric Encryption

Creates a new asymmetric encryption driver with a private key.

func NewAsymmetric(key RSAKey, signer HashingAlgo) Cryptography
NewAsymmetricClient

Creates a new asymmetric encryption driver with a public key.

func NewAsymmetricClient(public *rsa.PublicKey, signer HashingAlgo) Cryptography
key, _ := cryptography.NewRSAKey(cryptography.RSA2048)
driver := cryptography.NewAsymmetric(*key, cryptography.SHA256)

data := []byte("my secret data")

// Encrypt
encrypted, _ := driver.EncryptBase64(data)

// Decrypt
decrypted, _ := driver.DecryptBase64(encrypted)
fmt.Println(string(decrypted)) // Output: my secret data
Hashing

Creates a new Argon2 hasher.

func NewArgon2Hasher(
    saltLength SimpleLength, keyLength uint32,
    memory uint32, iterations uint32, parallelism uint8,
) Hasher

Creates a new bcrypt hasher.

func NewBcryptHasher(cost int) Hasher

Creates a new HMAC hasher.

func HMacHasher(key []byte, algo HashingAlgo) Hasher
password := []byte("my_password")

// Argon2
argon2Hasher := cryptography.NewArgon2Hasher(0, 0, 0, 0, 0)
hashed, _ := argon2Hasher.Hash(password)
valid, _ := argon2Hasher.Validate(hashed, password)
fmt.Println(valid) // Output: true

// bcrypt
bcryptHasher := cryptography.NewBcryptHasher(0)
hashed, _ = bcryptHasher.Hash(password)
valid, _ = bcryptHasher.Validate(hashed, password)
fmt.Println(valid) // Output: true
Key Management
Simple Key

Generates a new random key of the specified length.

func NewSimpleKey(length SimpleLength) (SimpleKey, error)
RSA Key

Generates a new RSA private key of the specified length.

func NewRSAKey(length RSALength) (*RSAKey, error)
Parse Private Key

Parses an RSA private key from PKCS#1 or PKCS#8 format.

func ParsePrivateKey(key []byte, isPEM bool) (*RSAKey, error)
Parse Public Key

Parses an RSA public key from PKIX or PKCS#1 format.

func ParsePublicKey(key []byte, isPEM bool) (*rsa.PublicKey, error)
// Generate a new RSA key
rsaKey, _ := cryptography.NewRSAKey(cryptography.RSA2048)

// Export and parse the private key
privateKeyPEM, _ := rsaKey.PrivateKeyPEM(true)
parsedKey, _ := cryptography.ParsePrivateKey(privateKeyPEM, true)

// Export and parse the public key
publicKeyPEM, _ := rsaKey.PublicKeyPEM(true)
parsedPublicKey, _ := cryptography.ParsePublicKey(publicKeyPEM, true)

License

This project is licensed under the ISC License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HashingAlg

func HashingAlg(algo HashingAlgo) crypto.Hash

HashingAlg maps the hashing algorithm to its corresponding crypto.Hash value. Returns 0 if the algorithm is not supported.

func HashingInstance

func HashingInstance(algo HashingAlgo) func() hash.Hash

HashingInstance returns a new hash.Hash instance for the given algorithm. Returns nil if the algorithm is not supported.

func HashingSize

func HashingSize(algo HashingAlgo) int

HashingSize returns the size of the hash output for the given algorithm in bytes. Returns 0 if the algorithm is not supported.

func ParseCertificate

func ParseCertificate(cert []byte, isPEM bool) (*x509.Certificate, error)

ParseCertificate parses an x509 certificate.

func ParseCertificateRequest

func ParseCertificateRequest(csr []byte, isPEM bool) (*x509.CertificateRequest, error)

ParseCertificateRequest parses an x509 certificate request (CSR).

func ParsePublicKey

func ParsePublicKey(key []byte, isPEM bool) (*rsa.PublicKey, error)

ParsePublicKey parses an RSA public key from PKIX or PKCS #1 format.

Types

type Cryptography

type Cryptography interface {
	// Sign generates a cryptographic signature for the given data.
	// Returns the signature as a byte slice or an error if signing fails.
	Sign(data []byte) ([]byte, error)

	// ValidateSignature checks if the provided signature is valid for the given data.
	// Returns true if the signature is valid, false otherwise, along with any error encountered.
	ValidateSignature(data []byte, signature []byte) (bool, error)

	// Encrypt encrypts the given data and returns the encrypted result as a byte slice.
	// Returns an error if encryption fails.
	Encrypt(data []byte) ([]byte, error)

	// Decrypt decrypts the given encrypted data and returns the original data as a byte slice.
	// Returns an error if decryption fails.
	Decrypt(data []byte) ([]byte, error)

	// EncryptBase64 encrypts the given data and encodes the result as a base64 string.
	// Returns the base64-encoded encrypted string or an error if encryption fails.
	EncryptBase64(data []byte) (string, error)

	// DecryptBase64 decodes the given base64-encoded string and decrypts it.
	// Returns the original data as a byte slice or an error if decryption fails.
	DecryptBase64(encrypted string) ([]byte, error)
}

Cryptography provides signing, validating, encrypting, and decrypting data. It provides support for both raw byte operations and base64-encoded string operations.

func NewAsymmetric

func NewAsymmetric(key RSAKey, signer HashingAlgo) Cryptography

NewAsymmetric creates a new asymmetric encryption driver with a private key.

func NewAsymmetricClient

func NewAsymmetricClient(public *rsa.PublicKey, signer HashingAlgo) Cryptography

NewAsymmetricClient creates a new asymmetric encryption driver with a public key.

func NewSymmetric

func NewSymmetric(key SimpleKey, signer HashingAlgo) Cryptography

NewSymmetric creates a new symmetric encryption driver.

type Hasher

type Hasher interface {
	// Hash generates a hash from the provided data.
	// Returns the hashed data or an error if the hashing process fails.
	Hash(data []byte) ([]byte, error)

	// Validate compares a hashed value with its possible plaintext equivalent.
	// Returns true if the hash matches the data, otherwise false.
	// An error is returned if the validation process fails.
	Validate(hash, data []byte) (bool, error)
}

Hasher generate and validate hash from data. It is recommended to use secure hashing algorithms like Argon2 or bcrypt for sensitive use cases such as password hashing.

func HMacHasher

func HMacHasher(key []byte, algo HashingAlgo) Hasher

HMacHasher creates a new HMAC hasher instance (recommended for message signing).

func NewArgon2Hasher

func NewArgon2Hasher(
	saltLength SimpleLength, keyLength uint32,
	memory uint32, iterations uint32, parallelism uint8,
) Hasher

NewArgon2Hasher creates a new Argon2 hasher with the specified parameters (recommended for password). If a parameter is 0, a default value is used.

func NewBcryptHasher

func NewBcryptHasher(cost int) Hasher

NewBcryptHasher creates a new bcrypt hasher (alternative for password). If a parameter is 0, a default value is used.

type HashingAlgo

type HashingAlgo string

HashingAlgo represents the hashing algorithm.

const (
	MD5  HashingAlgo = "MD5"  // MD5 algorithm (not recommended for security)
	SHA1 HashingAlgo = "SHA1" // SHA1 algorithm (not recommended for security)

	SHA224 HashingAlgo = "SHA224" // SHA2 224 algorithm
	SHA256 HashingAlgo = "SHA256" // SHA2 256 algorithm (recommended)
	SHA384 HashingAlgo = "SHA384" // SHA2 384 algorithm
	SHA512 HashingAlgo = "SHA512" // SHA2 512 algorithm

	SHA3224 HashingAlgo = "SHA3224" // SHA3 224 algorithm
	SHA3256 HashingAlgo = "SHA3256" // SHA3 256 algorithm
	SHA3384 HashingAlgo = "SHA3384" // SHA3 384 algorithm
	SHA3512 HashingAlgo = "SHA3512" // SHA3 512 algorithm
)

Supported hashing algorithms.

type RSAKey

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

RSAKey wraps an RSA private key and provides utility methods.

func NewRSAKey

func NewRSAKey(length RSALength) (*RSAKey, error)

NewRSAKey generates a new RSA private key of the specified length.

func ParsePrivateKey

func ParsePrivateKey(key []byte, isPEM bool) (*RSAKey, error)

ParsePrivateKey parses an RSA private key from PKCS #1 or PKCS #8 format.

func (*RSAKey) IssueCertificateBytes

func (k *RSAKey) IssueCertificateBytes(subject pkix.Name, algo x509.SignatureAlgorithm, options *x509.Certificate) ([]byte, error)

IssueCertificateBytes generates a self-signed certificate in DER format.

func (*RSAKey) IssueCertificatePEM

func (k *RSAKey) IssueCertificatePEM(subject pkix.Name, algo x509.SignatureAlgorithm, options *x509.Certificate) ([]byte, error)

IssueCertificatePEM generates a self-signed certificate in PEM format.

func (*RSAKey) PrivateKey

func (k *RSAKey) PrivateKey() *rsa.PrivateKey

PrivateKey returns the RSA private key.

func (*RSAKey) PrivateKeyBytes

func (k *RSAKey) PrivateKeyBytes(usePKCS8 bool) ([]byte, error)

PrivateKeyBytes returns the private key in PKCS#1 or PKCS#8 format. PKCS #1 is not recommended for security as it's considered weak and can potentially be broken by modern computational capabilities.

func (*RSAKey) PrivateKeyPEM

func (k *RSAKey) PrivateKeyPEM(usePKCS8 bool) ([]byte, error)

PrivateKeyPEM returns the private key in PEM-encoded format (PKCS#1 or PKCS#8). PKCS #1 is not recommended for security as it's considered weak and can potentially be broken by modern computational capabilities.

func (*RSAKey) PublicKey

func (k *RSAKey) PublicKey() *rsa.PublicKey

PublicKey returns the RSA public key.

func (*RSAKey) PublicKeyBytes

func (k *RSAKey) PublicKeyBytes(usePKCS8 bool) ([]byte, error)

PublicKeyBytes returns the public key in PKIX or PKCS#1 format. PKCS #1 is not recommended for security as it's considered weak and can potentially be broken by modern computational capabilities.

func (*RSAKey) PublicKeyPEM

func (k *RSAKey) PublicKeyPEM(usePKCS8 bool) ([]byte, error)

PublicKeyPEM returns the public key in PEM-encoded format (PKIX or PKCS#1). PKCS #1 is not recommended for security as it's considered weak and can potentially be broken by modern computational capabilities.

type RSALength

type RSALength int

RSALength defines the bit length of RSA keys.

const (
	RSA1024 RSALength = 1024 // Weak and not recommended for modern security.
	RSA2048 RSALength = 2048 // Minimum recommended size for modern applications.
	RSA3072 RSALength = 3072 // Stronger security for long-term protection.
	RSA4096 RSALength = 4096 // Highly secure but slower performance.
)

type SimpleKey

type SimpleKey []byte

SimpleKey represents a cryptographic key as a byte slice.

func NewSimpleKey

func NewSimpleKey(length SimpleLength) (SimpleKey, error)

NewSimpleKey generates a new random key of the specified length. Returns an error if the random number generation fails.

func (SimpleKey) Base64

func (k SimpleKey) Base64() string

Base64 returns the key as a Base64-encoded string.

func (SimpleKey) Bytes

func (k SimpleKey) Bytes() []byte

Bytes returns the key as a byte slice.

func (SimpleKey) Hex

func (k SimpleKey) Hex() string

Hex returns the key as a hexadecimal string.

func (SimpleKey) String

func (k SimpleKey) String() string

String implements the fmt.Stringer interface. By default, it returns the key as a hexadecimal string.

type SimpleLength

type SimpleLength int

SimpleLength defines the length of the key in bytes.

const (
	Simple16 SimpleLength = 16 // 128-bit key
	Simple24 SimpleLength = 24 // 192-bit key
	Simple32 SimpleLength = 32 // 256-bit key
)

Predefined key lengths for convenience.

Jump to

Keyboard shortcuts

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