libcipher

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

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

Go to latest
Published: Oct 5, 2024 License: MIT Imports: 12 Imported by: 1

README

libcipher

libbipher provides high-level abstractions for common cryptographic operations. It is designed to facilitate sensitive message handling such as encryption, decryption, and signing.

Features

  • AES-CBC: Provides secure encryption with HMAC for integrity checking.
  • AES-GCM: Offers authenticated encryption with built-in integrity verification.
  • Key Generation: Supports custom key lengths and key generation.

Installation

To install the library, run:

go get github.com/cecmp/libcipher

Usage

AES-CBC Encryption/Decryption with HMAC
package main

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"log"

	"github.com/cecmp/libcipher"
)

func main() {
	// Generate a 64-byte key (32 bytes for encryption, 32 bytes for integrity).
	key, err := libcipher.GenerateKey(64)
	if err != nil {
		log.Fatal("Error generating key:", err)
	}

	encryptionKey := key[:32]
	integrityKey := key[32:]

	// Example plaintext.
	plaintext := []byte("This is a secret message.")

	// Encrypt the plaintext.
	encryptor, err := libcipher.NewCBCHMACEncryptor(encryptionKey, integrityKey, sha256.New, rand.Reader)
	if err != nil {
		log.Fatal("Error creating encryptor:", err)
	}
	ciphertext, err := encryptor.Crypt(plaintext, nil)
	if err != nil {
		log.Fatal("Error encrypting message:", err)
	}

	// Encode ciphertext in base64 for easier transmission/storage.
	ciphertextBase64 := base64.StdEncoding.EncodeToString(ciphertext)
	fmt.Println("Encrypted (base64):", ciphertextBase64)

	// Decrypt the ciphertext.
	decryptor, err := libcipher.NewCBCHMACDecryptor(encryptionKey, integrityKey, sha256.New)
	if err != nil {
		log.Fatal("Error creating decryptor:", err)
	}
	decodedCiphertext, _ := base64.StdEncoding.DecodeString(ciphertextBase64)
	decryptedText, _, err := decryptor.Crypt(decodedCiphertext)
	if err != nil {
		log.Fatal("Error decrypting message:", err)
	}

	fmt.Println("Decrypted message:", string(decryptedText))
}

For other cryptographic primitives such as AES-GCM, refer to the tests for more detailed usage.

Roadmap

  • planned: asymmetric encryption
  • planned: higher key lengths support for AES-GCM
  • planned: tokens and signed data
  • planned: better documentation
  • planned: key derivation functions
  • planned: (maybe) linked records

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateKey

func GenerateKey(keyLength int) (string, error)

GenerateKey generates a cryptographically random key with the specified length.

Types

type CipherTextError

type CipherTextError string

func (CipherTextError) Error

func (e CipherTextError) Error() string

type Decryptor

type Decryptor interface {
	// Encrypts/Decrypts a message, misuse may lead to a panic.
	Crypt(cipherpackage []byte) ([]byte, []byte, error)
}

provides a method to crypt a cipher package. Misuse of this method may lead to a panic.

func NewCBCHMACDecryptor

func NewCBCHMACDecryptor(encyptionKey []byte, integrityKey []byte, calculateMAC func() hash.Hash) (Decryptor, error)

Configure & init the AES-CBC+HMAC cryptor in decryption mode.

func NewGCMDecryptor

func NewGCMDecryptor(encyptionKey []byte) (Decryptor, error)

NewGCMDecryptor creates a new Decryptor using AES-GCM with the given key.

type EncryptionKeyError

type EncryptionKeyError string

func (EncryptionKeyError) Error

func (e EncryptionKeyError) Error() string

type Encryptor

type Encryptor interface {
	// Encrypts/Decrypts a message, misuse may lead to a panic.
	Crypt(message []byte, additionalData []byte) ([]byte, error)
}

provides a method to crypt a message with additional data. Misuse of this method may lead to a panic.

func NewCBCHMACEncryptor

func NewCBCHMACEncryptor(encyptionKey []byte, integrityKey []byte, calculateMAC func() hash.Hash, rand io.Reader) (Encryptor, error)

Configure & init the AES-CBC+HMAC cryptor in encryption mode. AES-CBC with PKCS7 padding HMAC for integrity.

The final encrypted string format:
[ MAC | AD-Lenght | AD | Initialization Vector | Block 1 | Block 2 | ... ]
uses rand from the arguments for introducing randomness.

Don't use this for big messages, the whole cypher has to be in mem for computing the Hmac.

The encryption key and integrity key must be distinct. Both keys have to be keept secret. Rotating must be done to both keys simultaneously.

Compromised Encryption Key:

An attacker, possessing the encryption key, could decrypt sensitive data.
If you rotate only the integrity key, they still have access to the previously encrypted data.

Compromised Integrity Key:

An attacker with the integrity key could potentially modify encrypted data,
forge HMACs, and tamper with the system without detection.
Even if you rotate the encryption key, the integrity of past data is compromised.

the MAC is calculated from ( AD-Lenght | AD | Initialization Vector | Block 1 | Block 2 | ... )

GCM Comparison:

	Use CBC with HMAC over GCM (or any stream cipher) when avoiding nonce collisions can be challenging is a problem.
	This is the case if you deal with:
	- high-volume systems (the probability of nonce collisions increases, especially if the nonce space is limited).
	- distributed environments (coordinating nonce generation across nodes and ensuring uniqueness becomes even more complex).
	- or scenarios where encrypted data needs to be stored persistently. For example, if encrypted data is stored in a database.
      and later retrieved and re-encrypted, ensuring that a new, unique nonce is used each time can be challenging.

Since this is a one-person project, ensure you review the code before using it to validate its security and correctness.

func NewGCMEncryptor

func NewGCMEncryptor(encyptionKey []byte, rand io.Reader) (Encryptor, error)

NewGCMEncryptor creates a new Encryptor using AES-GCM with the given key.

type IntegrityKeyError

type IntegrityKeyError string

func (IntegrityKeyError) Error

func (e IntegrityKeyError) Error() string

type InvalidUsageError

type InvalidUsageError string

func (InvalidUsageError) Error

func (e InvalidUsageError) Error() string

type KeyGenerationError

type KeyGenerationError string

func (KeyGenerationError) Error

func (e KeyGenerationError) Error() string

type MessageError

type MessageError string

func (MessageError) Error

func (e MessageError) Error() string

Jump to

Keyboard shortcuts

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