Class: Affine::Cipher
- Inherits:
-
Object
- Object
- Affine::Cipher
- Defined in:
- lib/affine/cipher.rb
Overview
Instance Method Summary collapse
-
#decipher(ciphertext) ⇒ Object
(also: #decrypt)
Decrypt one
ciphertext
into aplaintext
. -
#encipher(plaintext) ⇒ Object
(also: #encrypt)
Encrypt one
plaintext
into aciphertext
. -
#initialize(modulus, a_key, b_key) ⇒ Cipher
constructor
Cipher objects are used both for decryption and encryption.
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.
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
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
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 |