ciphers

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2026 License: MIT Imports: 7 Imported by: 0

README

Ciphers

Core classical cipher implementations including Caesar, Vigenère, Affine, Cardan grille, and rail fence ciphers.

Documentation

Overview

Package ciphers provides implementations of various classical and modern encryption ciphers.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CalculateGridSize added in v0.2.0

func CalculateGridSize(gridKeyLen int) (int, error)

CalculateGridSize calculates the size of the grid used based on the provided gridKeyLen.

Return an error if gridKeyLen does not correspond to any valid grid size.

func IsASCIILetter

func IsASCIILetter(char byte) bool

IsASCIILetter checks whether the provided char is an ASCII a-zA-Z letter.

func IsLowerASCIILetter added in v0.2.0

func IsLowerASCIILetter(char byte) bool

IsLowerASCIILetter checks whether the provided char is an ASCII a-z letter.

func IsUpperASCIILetter added in v0.2.0

func IsUpperASCIILetter(char byte) bool

IsUpperASCIILetter checks whether the provided char is an ASCII A-Z letter.

func NormalizeVigenereKey

func NormalizeVigenereKey(key *VigenereKey) ([]byte, error)

NormalizeVigenereKey normalizes a Vigenere key by converting all letters to lowercase and returning only the shift values (a=0, b=1, ..., z=25).

Returns an error if the key is empty or contains non-letter characters.

func RandSequenceIntMaxN added in v0.2.0

func RandSequenceIntMaxN(n int, count int) (<-chan int, error)

RandSequenceIntMaxN generates a sequence of random integers in the range [0, n).

It returns a channel that produces count random integers, each in the range [0, n). The function uses crypto/rand for cryptographically secure random numbers.

Returns an error if n <= 0 or count <= 0.

func ToASCIILetter added in v0.2.0

func ToASCIILetter(char byte) byte

ToASCIILetter converts an ASCII letter to its position in the alphabet (0-25).

For lowercase letters (a-z), it returns 0-25. For uppercase letters (A-Z), it returns 0-25. For non-letter characters, it returns the character unchanged.

Should be used together with IsASCIILetter.

func ValidateCardanKey

func ValidateCardanKey(gridKey *CardanKey) error

ValidateCardanKey validates that a CardanKey is valid for the given grid size.

It checks if:

  1. the key has the correct length
  2. all indices are in bounds,
  3. there are no duplicates
  4. there are no overlaps when rotated
  5. all non-center cells are covered.

Returns an error if the key is invalid.

Types

type AffineCipher added in v0.2.0

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

AffineCipher is a k-rank Affine cipher implementation over Z26.

The cipher encrypts blocks of a-zA-Z characters using the affine transformation: c = (M * p + b) mod 26

Where M is an NxN invertible matrix key and b is an N-dimensional key vector. Non-alphabetic characters are preserved and not transformed.

Leftover a-zA-Z characters that can't create a Nx1 vector are left unencrypted.

func NewAffineCipher added in v0.2.0

func NewAffineCipher(key *AffineKey) (*AffineCipher, error)

NewAffineCipher creates a new Affine cipher with the given key.

The key matrix must be square and invertible modulo 26. The function computes the inverse key matrix using the Chinese Remainder Theorem, combining inverses modulo 2 and modulo 13 to produce the inverse modulo 26.

Returns an error if the key matrix is not square or not invertible or if it doesn't match sizes with key vector.

func (*AffineCipher) DecryptBlock added in v0.2.0

func (ac *AffineCipher) DecryptBlock(dst []byte, src []byte) error

DecryptBlock decrypts src using the Affine cipher and writes the result to dst.

DecryptBlock subtracts the key vector and then multiplies the inverse key matrix by blocks of ASCII letters. Non-letter characters are passed through unchanged.

Leftover a-zA-Z characters that can't create a Nx1 vector are left unencrypted.

src and dst can alias, because Affine cipher performs operations in-place.

src and dst must be the same length.

func (*AffineCipher) EncryptBlock added in v0.2.0

func (ac *AffineCipher) EncryptBlock(dst []byte, src []byte) error

EncryptBlock encrypts src using the Affine cipher and writes the result to dst.

EncryptBlock multiplies the key matrix by blocks of ASCII letters and adds the key vector. Non-letter characters are passed through unchanged.

Leftover a-zA-Z characters that can't create a Nx1 vector are left unencrypted.

src and dst can alias, because Affine cipher performs operations in-place.

src and dst must be the same length.

func (*AffineCipher) InverseKey added in v0.2.0

func (ac *AffineCipher) InverseKey() AffineKey

InverseKey returns the inverse matrix to cipher's Key Matrix and the key vector, such so:

Key x Inverse = Identity Matrix

func (*AffineCipher) IsInPlace added in v0.2.0

func (ac *AffineCipher) IsInPlace() bool

IsInPlace returns whether the cipher can perform encryption/decryption in-place.

Affine cipher supports in-place operations.

func (*AffineCipher) Key added in v0.2.0

func (ac *AffineCipher) Key() AffineKey

Key returns the cipher's Key Matrix and the key vector.

type AffineKey added in v0.2.0

type AffineKey struct {
	MatrixKey [][]int `json:"matrix"`
	VectorKey []int   `json:"vector"`
}

AffineKey represents the key for a Affine cipher.

It contains a square matrix and a key vector.

func GenerateAffineKey added in v0.2.0

func GenerateAffineKey(size int) (*AffineKey, error)

GenerateAffineKey generates a random invertible key for the Affine cipher.

The size parameter specifies the dimensions of the key matrix (NxN). The function generates random matrices until it finds one that is invertible modulo 26 and returns it together with a random key vector.

O(random) Time Complexity.

Returns an error if size <= 0.

type BlockCipher

type BlockCipher interface {
	/*
		IsInPlace returns whether the cipher can perform encryption/decryption in-place.

		In-place operations allow src and dst slices to alias.
	*/
	IsInPlace() bool
	/*
		EncryptBlock encrypts src and writes the result to dst.

		If implementation allows for in-place operations, dst and src can alias.

		src and dst must be the same length; the expected length is
		implementation-defined — consult the concrete type for details.
	*/
	EncryptBlock(dst []byte, src []byte) error
	/*
		DecryptBlock decrypts src and writes the result to dst.

		If implementation allows for in-place operations, dst and src can alias.

		src and dst must be the same length; the expected length is
		implementation-defined — consult the concrete type for details.
	*/
	DecryptBlock(dst []byte, src []byte) error
}

BlockCipher is the interface that all block ciphers must implement.

It provides methods for encryption and decryption of fixed-size blocks.

type CaesarCipher

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

CaesarCipher is a substitution cipher that shifts letters by a fixed key.

It uses precomputed substitution and reverse tables for efficient encryption/decryption.

Example:

Key:        3
Plaintext:  Hello
-----------------
+H e l l o
 3 3 3 3 3
 K h o o r
-----------------
Ciphertext: Khoor

func NewCaesarCipher

func NewCaesarCipher(key *CaesarKey) *CaesarCipher

NewCaesarCipher creates a new Caesar cipher with the given key.

The key is the number of positions to shift letters (keys are reduced modulo 26). It supports negative keys.

func (*CaesarCipher) DecryptBlock

func (cc *CaesarCipher) DecryptBlock(dst []byte, src []byte) error

DecryptBlock decrypts src using the Caesar cipher and writes the result to dst.

src and dst can alias, because Caesar cipher performs operations in-place.

src and dst must be the same length.

func (*CaesarCipher) EncryptBlock

func (cc *CaesarCipher) EncryptBlock(dst []byte, src []byte) error

EncryptBlock encrypts src using the Caesar cipher and writes the result to dst.

src and dst can alias, because Caesar cipher performs operations in-place.

src and dst must be the same length.

func (*CaesarCipher) IsInPlace

func (cc *CaesarCipher) IsInPlace() bool

IsInPlace returns whether the cipher can perform encryption/decryption in-place.

Caesar cipher supports in-place operations.

func (*CaesarCipher) Key

func (cc *CaesarCipher) Key() CaesarKey

Key returns the underlying key.

type CaesarKey added in v0.2.0

type CaesarKey struct {
	Key int `json:"key"`
}

CarsarKey represents a key for Caesar cipher.

It consists of a byte shift.

type CardanCipher

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

CardanCipher is a grille-based transposition cipher that uses a rotating grid (Cardan grille) to encrypt messages.

The cipher works by placing holes in a grid pattern and rotating the grid four times to mark which positions are "holes".

func NewCardanCipher

func NewCardanCipher(gridKey *CardanKey) (*CardanCipher, error)

NewCardanCipher creates a new Cardan cipher with the given key.

Returns an error if the key is invalid.

func (*CardanCipher) DecryptBlock

func (cc *CardanCipher) DecryptBlock(dst []byte, src []byte) error

DecryptBlock decrypts src using the Cardan cipher and writes the result to dst.

src and dst cannot alias.

src and dst must be the same length and must match gridSize*gridSize.

func (*CardanCipher) EncryptBlock

func (cc *CardanCipher) EncryptBlock(dst []byte, src []byte) error

EncryptBlock encrypts src using the Cardan cipher and writes the result to dst.

src and dst cannot alias.

src and dst must be the same length and must match gridSize*gridSize.

func (*CardanCipher) IsInPlace

func (cc *CardanCipher) IsInPlace() bool

IsInPlace returns whether the cipher can perform encryption/decryption in-place.

Cardan cipher does not support in-place operations since bytes are written to non-sequential positions, requiring a separate destination buffer.

func (*CardanCipher) Key added in v0.2.0

func (cc *CardanCipher) Key() CardanKey

Key returns the underlying gridKey Cardan Cipher uses to construct a permutation.

type CardanKey

type CardanKey struct {
	Key []int `json:"key"`
}

CardanKey represents the key for a Cardan grille cipher.

It contains a list of indexes that form the initial hole pattern.

func GenerateCardanKey

func GenerateCardanKey(gridSize int) (*CardanKey, error)

GenerateCardanKey generates a random valid CardanKey for the given grid size.

The grid size must be positive.

Returns an error if key generation fails.

func (*CardanKey) String

func (ck *CardanKey) String() string

String returns a JSON string representation of the CardanKey.

If JSON string representation fails falls back to fmt.Sprintf formatting.

type CipherMode

type CipherMode int8

CipherMode represents the mode of operation for a cipher, either encryption or decryption.

const (
	// Encrypt indicates encryption mode.
	Encrypt CipherMode = iota
	// Decrypt indicates decryption mode.
	Decrypt
)

func (CipherMode) String

func (mode CipherMode) String() string

String returns the string representation of the CipherMode.

type RailFenceCipher

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

RailFenceCipher is a transposition cipher that writes plaintext in a zigzag pattern across a number of "rails" and then reads off row by row.

The key specifies the number of rails to use.

Example:

key:        3
Plaintext:  HelloWorld
----------------------
  l   o
 e l w r d
H   o   l
----------------------
Ciphertext: loelwrdHol

func NewRailFenceCipher

func NewRailFenceCipher(key *RailFenceKey) (*RailFenceCipher, error)

NewRailFenceCipher creates a new Rail Fence cipher with the given key.

The key consists of the height of the rails (must be >= 1) and the length of the block (must be >= 1).

If height is 1, permutationTable becomes nil. EncryptBlock() and DecryptBlock() handle the height == 1 case separately.

If height is >= permutationLength, permutationTable reverses the text.

Returns an error if the key is < 1 or length of the block is <= 0.

func (*RailFenceCipher) DecryptBlock

func (rfc *RailFenceCipher) DecryptBlock(dst []byte, src []byte) error

DecryptBlock decrypts src using the Rail Fence cipher and writes the result to dst.

src and dst cannot alias.

src and dst must be the same length and must match the permutationLength used when creating the cipher.

func (*RailFenceCipher) EncryptBlock

func (rfc *RailFenceCipher) EncryptBlock(dst []byte, src []byte) error

EncryptBlock encrypts src using the Rail Fence cipher and writes the result to dst.

src and dst cannot alias.

src and dst must be the same length and must match the permutationLength used when creating the cipher.

func (*RailFenceCipher) IsInPlace

func (rfc *RailFenceCipher) IsInPlace() bool

IsInPlace returns whether the cipher can perform encryption/decryption in-place.

Rail Fence cipher does not support in-place operations since bytes are written to non-sequential positions, requiring a separate destination buffer.

func (*RailFenceCipher) Key

func (rfc *RailFenceCipher) Key() RailFenceKey

Key returns the underlying key and the length of the permutation block.

type RailFenceKey added in v0.2.0

type RailFenceKey struct {
	Key               int `json:"keyy"`
	PermutationLength int `json:"permutation_length"`
}

RailFenceKey represents a key for a RailFence cipher.

It contains the height of the fence (Key) and the length of the permutation block (PermutationLength).

type VigenereAutoKeyCipher

type VigenereAutoKeyCipher struct {
	VigenereCipher
}

VigenereAutoKeyCipher is a variant of the Vigenere cipher that uses the plaintext itself (after the key) as the key for subsequent encryptions, providing stronger security than the standard Vigenere cipher.

Example:

key:        Cat
Plaintext:  HelloWorld
---------------------
+H e l l o W o r l d
 C a t H e l l o W o
 J e e s s H z f h r
---------------------
Ciphertext: JeessHzfhr

func NewVigenereAutoKeyCipher

func NewVigenereAutoKeyCipher(key *VigenereKey) (*VigenereAutoKeyCipher, error)

NewVigenereAutoKeyCipher creates a new Vigenere Auto-key cipher with the given key.

The key must be a non-empty string of ASCII letters.

Returns an error if the key is invalid.

func NewVigenereAutoKeyCipherNormalized

func NewVigenereAutoKeyCipherNormalized(key []byte) *VigenereAutoKeyCipher

NewVigenereAutoKeyCipherNormalized creates a new Vigenere Auto-key cipher with an already normalized key.

func (*VigenereAutoKeyCipher) DecryptBlock

func (vCipher *VigenereAutoKeyCipher) DecryptBlock(dst []byte, src []byte) error

DecryptBlock decrypts src using the Vigenere Auto-key cipher and writes the result to dst.

The key cycles over letter characters only; non-letter characters are passed through unchanged.

src and dst cannot alias.

src and dst must be the same length.

func (*VigenereAutoKeyCipher) EncryptBlock

func (vCipher *VigenereAutoKeyCipher) EncryptBlock(dst []byte, src []byte) error

EncryptBlock encrypts src using the Vigenere Auto-key cipher and writes the result to dst.

The key cycles over letter characters only; non-letter characters are passed through unchanged.

src and dst cannot alias.

src and dst must be the same length.

func (*VigenereAutoKeyCipher) IsInPlace

func (vCipher *VigenereAutoKeyCipher) IsInPlace() bool

IsInPlace returns whether the cipher can perform encryption/decryption in-place.

Vigenere Auto-key cipher does not support in-place operations since decryption reads from dst as key material before it is fully written.

type VigenereCipher

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

VigenereCipher is a polyalphabetic substitution cipher that uses a keyword to encrypt messages by shifting each letter by a different amount based on the corresponding letter in the key.

Example:

Key:        Cat
Plaintext:  HelloWorld
---------------------
+H e l l o W o r l d
 C a t C a t C a t C
 J e e n o P q r e f
---------------------
Ciphertext: JeenoPqref

func NewVigenereCipher

func NewVigenereCipher(key *VigenereKey) (*VigenereCipher, error)

NewVigenereCipher creates a new Vigenere cipher with the given key.

The key must be a non-empty string of ASCII letters.

Returns an error if the key is invalid.

func NewVigenereCipherNormalized

func NewVigenereCipherNormalized(key []byte) *VigenereCipher

NewVigenereCipherNormalized creates a new Vigenere cipher with an already normalized key.

func (*VigenereCipher) DecryptBlock

func (vc *VigenereCipher) DecryptBlock(dst []byte, src []byte) error

DecryptBlock decrypts src using the Vigenere cipher and writes the result to dst.

The key cycles over letter characters only; non-letter characters are passed through unchanged.

src and dst can alias, because Vigenere cipher performs operations in-place.

src and dst must be the same length.

func (*VigenereCipher) EncryptBlock

func (vc *VigenereCipher) EncryptBlock(dst []byte, src []byte) error

EncryptBlock encrypts src using the Vigenere cipher and writes the result to dst.

The key cycles over letter characters only; non-letter characters are passed through unchanged.

src and dst can alias, because Vigenere cipher performs operations in-place.

src and dst must be the same length.

func (*VigenereCipher) IsInPlace

func (vc *VigenereCipher) IsInPlace() bool

IsInPlace returns whether the cipher can perform encryption/decryption in-place.

Vigenere cipher supports in-place operations.

func (*VigenereCipher) Key

func (vc *VigenereCipher) Key() VigenereKey

Key returns the underlying key.

type VigenereKey added in v0.2.0

type VigenereKey struct {
	Key []byte `json:"key"`
}

VigenereKey represents a Vigenere/Vigenere Auto-Key cipher key.

It consists of a word/key/phrase/sequence of ASCII a-zA-Z letters.

Directories

Path Synopsis
Package analyze provides functionality for cryptanalysis of classical ciphers.
Package analyze provides functionality for cryptanalysis of classical ciphers.
mathutils provides functions and structs to perform mathematical operations.
mathutils provides functions and structs to perform mathematical operations.

Jump to

Keyboard shortcuts

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