Class: Affine::Cipher

Inherits:
Object
  • Object
show all
Defined in:
lib/affine/cipher.rb

Overview

The affine cipher for positive integers. This algorithm is only defined for positive integers, and many arguments have further restrictions.

Usage

@a = Affine::Cipher.new(2176782371, 65182241782, 123235151)
ct = @a.encipher(14)
14 == @a.decipher(ct)

Instance Method Summary collapse

Constructor Details

#initialize(modulus, a_key, b_key) ⇒ Cipher

Cipher objects are used both for decryption and encryption.

Arguments

modulus

specifies how many different plaintexts and ciphertexts are available.

a_key

multiplied against the plaintext. Must be coprime with modulus.

b_key

added to the multiplied plaintext. No restrictions, but it’s modulus math, so making it larger than modulus is useless.

Raises:



22
23
24
25
26
27
28
# File 'lib/affine/cipher.rb', line 22

def initialize(modulus, a_key, b_key)
  raise CoprimeError.new(modulus, a_key) if modulus.gcd(a_key) != 1
  @modulus = modulus
  @a_key = a_key
  @b_key = b_key
  @a_inv = extended_gcd(a_key, modulus)
end

Instance Method Details

#decipher(ciphertext) ⇒ Object Also known as: decrypt

Decrypt one ciphertext into a plaintext.

Argument

ciphertext

a single positive integer between 0 and the modulus for the cipher

Raises:



45
46
47
48
# File 'lib/affine/cipher.rb', line 45

def decipher(ciphertext)
  raise RangeError.new(ciphertext, @modulus) if ciphertext > @modulus
  (@a_inv * (ciphertext - @b_key)) % @modulus
end

#encipher(plaintext) ⇒ Object Also known as: encrypt

Encrypt one plaintext into a ciphertext.

Argument

plaintext

a single positive integer between 0 and the modulus for the cipher

Raises:



35
36
37
38
# File 'lib/affine/cipher.rb', line 35

def encipher(plaintext)
  raise RangeError.new(plaintext, @modulus) if plaintext > @modulus
  ((@a_key * plaintext) + @b_key) % @modulus
end