# Algorithms_in_C++: ciphers/hill_cipher.cpp File Reference

hill_cipher.cpp File Reference

Implementation of Hill cipher algorithm. More...

`#include <cassert>`
`#include <cmath>`
`#include <cstring>`
`#include <ctime>`
`#include <fstream>`
`#include <iomanip>`
`#include <iostream>`
`#include <string>`
`#include "../numerical_methods/lu_decomposition.h"`
Include dependency graph for hill_cipher.cpp:

## Classes

class | ciphers::HillCipher
| Implementation of Hill Cipher algorithm. More...

## Namespaces

| ciphers
| Algorithms for encryption and decryption.

## Functions

template<typename T >
static std::ostream & | operator<< (std::ostream &out, matrix< T > const &v)
void | test1 (const std::string &text)
| Self test 1 - using 3x3 randomly generated key. More...
void | test2 (const std::string &text)
| Self test 2 - using 8x8 randomly generated key. More...
int | main ()

## Variables

static const char * | ciphers::STRKEY

## Detailed Description

Implementation of Hill cipher algorithm.

Program to generate the encryption-decryption key and perform encryption and decryption of ASCII text using the famous block cipher algorithm. This is a powerful encryption algorithm that is relatively easy to implement with a given key. The strength of the algorithm depends on the size of the block encryption matrix key; the bigger the matrix, the stronger the encryption and more difficult to break it. However, the important requirement for the matrix is that:

1. matrix should be invertible - all inversion conditions should be satisfied and
2. its determinant must not have any common factors with the length of character set Due to this restriction, most implementations only implement with small 3x3 encryption keys and a small subset of ASCII alphabets.

In the current implementation, I present to you an implementation for generating larger encryption keys (I have attempted upto 10x10) and an ASCII character set of 97 printable characters. Hence, a typical ASCII text file could be easily encrypted with the module. The larger character set increases the modulo of cipher and hence the matrix determinants can get very large very quickly rendering them ill-defined.

Note
  This program uses determinant computation using LU decomposition from the file lu_decomposition.h
  The matrix generation algorithm is very rudimentary and does not guarantee an invertible modulus matrix.

Todo:
  Better matrix generation algorithm.

Author
  Krishna Vedala

## Function Documentation

## main()

int main | ( |  | ) |

Main function

{
std::srand(std::time(nullptr));
std::cout << "Key dictionary: (" << std::strlen(ciphers::STRKEY) << ")\n\t"
<< ciphers::STRKEY << "\n";
std::string text = "This is a simple text with numb3r5 and exclamat!0n.";
test1(text);
test2(text);
return 0;
}
Here is the call graph for this function:

## operator<<()

template<typename T >

static std::ostream& operator<< | ( | std::ostream & | out,
|  | matrix< T > const & | v
| ) |  |

static

operator to print a matrix

{
const int width = 15;
const char separator = ' ';
for (size_t row = 0; row < v.size(); row++) {
for (size_t col = 0; col < v[row].size(); col++)
out << std::left << std::setw(width) << std::setfill(separator)
<< v[row][col];
out << std::endl;
}
return out;
}
Here is the call graph for this function:

## test1()

void test1 | ( | const std::string & | text | ) |

Self test 1 - using 3x3 randomly generated key.

Parameters

  text | string to encrypt and decrypt

{
// std::string text = "Hello world!";
std::cout << "======Test 1 (3x3 key) ======\nOriginal text:\n\t" << text
<< std::endl;
std::pair<matrix<int>, matrix<int>> p =
ciphers::HillCipher::generate_keys(3, 0, 100);
matrix<int> ekey = p.first;
matrix<int> dkey = p.second;
// matrix<int> ekey = {{22, 28, 25}, {5, 26, 15}, {14, 18, 9}};
// std::cout << "Encryption key: \n" << ekey;
std::string gibberish = ciphers::HillCipher::encrypt_text(text, ekey);
std::cout << "Encrypted text:\n\t" << gibberish << std::endl;
// matrix<int> dkey = ciphers::HillCipher::generate_decryption_key(ekey);
// std::cout << "Decryption key: \n" << dkey;
std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey);
std::cout << "Reconstruct text:\n\t" << txt_back << std::endl;
std::ofstream out_file("hill_cipher_test1.txt");
out_file << "Block size: " << ekey.size() << "\n";
out_file << "Encryption Key:\n" << ekey;
out_file << "\nDecryption Key:\n" << dkey;
out_file.close();
assert(txt_back == text);
std::cout << "Passed :)\n";
}
Here is the call graph for this function:

## test2()

void test2 | ( | const std::string & | text | ) |

Self test 2 - using 8x8 randomly generated key.

Parameters

  text | string to encrypt and decrypt

{
// std::string text = "Hello world!";
std::cout << "======Test 2 (8x8 key) ======\nOriginal text:\n\t" << text
<< std::endl;
std::pair<matrix<int>, matrix<int>> p =
ciphers::HillCipher::generate_keys(8, 0, 3);
matrix<int> ekey = p.first;
matrix<int> dkey = p.second;
std::string gibberish = ciphers::HillCipher::encrypt_text(text, ekey);
std::cout << "Encrypted text:\n\t" << gibberish << std::endl;
std::string txt_back = ciphers::HillCipher::decrypt_text(gibberish, dkey);
std::cout << "Reconstruct text:\n\t" << txt_back << std::endl;
std::ofstream out_file("hill_cipher_test2.txt");
out_file << "Block size: " << ekey.size() << "\n";
out_file << "Encryption Key:\n" << ekey;
out_file << "\nDecryption Key:\n" << dkey;
out_file.close();
assert(txt_back.compare(0, text.size(), text) == 0);
std::cout << "Passed :)\n";
}
Here is the call graph for this function:
mov
void mov(tower *From, tower *To)
Definition: tower_of_hanoi.cpp:39
std::srand
T srand(T... args)
main
int main()
Definition: knuth_morris_pratt.cpp:76
main
int main()
Definition: fenwick_tree.cpp:69
ternary_search
void ternary_search(int N, int A[], int target)
Definition: ternary_search.cpp:127
std::floor
T floor(T... args)
test3
void test3()
Definition: smallest_circle.cpp:188
main
int main(void)
Definition: decimal_to_hexadecimal.cpp:11
method2
void method2(int number)
Definition: decimal_to_binary.cpp:27
main
int main()
Definition: exponential_search.cpp:74
std::strlen
T strlen(T... args)
mat_size
ll mat_size
Definition: matrix_exponentiation.cpp:45
main
int main()
Definition: stairs_pattern.cpp:17
hash_search
int hash_search(int key, int *counter)
Definition: hash_search.cpp:76
std::string
STL class.
sorting::shell_sort
void shell_sort(T *arr, size_t LEN)
Definition: shell_sort2.cpp:45
tolowerRoman
std::string tolowerRoman(int n)
Definition: decimal_to_roman_numeral.cpp:24
test_f
void test_f(const int NUM_DATA)
Definition: shell_sort2.cpp:145
string_search
String search algorithms.
Definition: brute_force_string_searching.cpp:13
MAX
#define MAX
Definition: fibonacci_fast.cpp:27
show_data
void show_data(T *arr, size_t LEN)
Definition: shell_sort2.cpp:18
std::list
STL class.
heapSort
void heapSort(T *arr, int n)
Definition: heap_sort.cpp:84
std::clock_t
std::move
T move(T... args)
main
int main()
Definition: binomial_dist.cpp:84
addition_rule_dependent
double addition_rule_dependent(double A, double B, double B_given_A)
Definition: addition_rule.cpp:25
test2
void test2()
Definition: smallest_circle.cpp:173
std::pair
std::vector
STL class.
std::vector::size
T size(T... args)
Point::x
double x
Definition: smallest_circle.cpp:16
main
int main()
Definition: decimal_to_roman_numeral.cpp:90
FenwickTree::sum_range
int sum_range(int l, int r)
Definition: fenwick_tree.cpp:65
test
void test()
Definition: heap_sort.cpp:99
absolutePrecision
#define absolutePrecision
Definition: ternary_search.cpp:22
ans
ll ans(ll n)
Definition: matrix_exponentiation.cpp:91
FenwickTree
Definition: fenwick_tree.cpp:17
print
void print(uint32_t N)
Definition: sieve_of_eratosthenes.cpp:40
sorting::insertionSort
void insertionSort(T *arr, int n)
Insertion Sort Function.
Definition: insertion_sort.cpp:59
HASHMAX
#define HASHMAX
Determines the length of the hash table.
Definition: hash_search.cpp:22
PRIME
#define PRIME
Prime modulus for hash functions.
Definition: rabin_karp.cpp:16
sorting::partition
int partition(int arr[], int low, int high)
Definition: quick_sort.cpp:37
std::distance
T distance(T... args)
binary_s
Type * binary_s(Type *array, size_t size, Type key)
Definition: exponential_search.cpp:34
node
Definition: avltree.cpp:13
Point::y
double y
Definition: smallest_circle.cpp:17
std::search
T search(T... args)
node
struct list node
FindNextGap
int FindNextGap(int gap)
Definition: comb_sort.cpp:29
MAX
#define MAX
Determines how much data.
Definition: hash_search.cpp:21
main
int main()
Definition: pascal_triangle.cpp:52
main
int main()
Definition: bayes_theorem.cpp:26
std::scanf
T scanf(T... args)
multiply
vector< vector< ll > > multiply(const vector< vector< ll >> &A, const vector< vector< ll >> &B)
Definition: matrix_exponentiation.cpp:57
test2
void test2(const std::string &text)
Self test 2 - using 8x8 randomly generated key.
Definition: hill_cipher.cpp:505
std::setfill
T setfill(T... args)
std::reverse
T reverse(T... args)
main
int main(void)
Definition: qr_decomposition.cpp:23
main
int main()
Definition: palindrome_of_number.cpp:19
sorting
Sorting algorithms.
main
int main()
Definition: vector_important_functions.cpp:11
std::queue
STL class.
sorting::merge
void merge(Iterator, Iterator, const Iterator, char[])
merges 2 sorted adjacent segments into a larger sorted segment
Definition: non_recursive_merge_sort.cpp:57
main
int main()
Definition: linear_search.cpp:27
eqd
static float eqd(float y)
Definition: successive_approximation.cpp:17
std::sort
T sort(T... args)
fill
std::string fill(char c, int n)
Definition: decimal_to_roman_numeral.cpp:15
mat_mul
void mat_mul(const std::valarray< std::valarray< double >> &A, const std::valarray< std::valarray< double >> &B, std::valarray< std::valarray< double >> *OUT)
Definition: qr_eigen_values.cpp:54
string_search::create_hash
int64_t create_hash(const std::string &s, int n)
Definition: rabin_karp.cpp:25
std::sqrt
T sqrt(T... args)
stack_idx
int stack_idx
pointer to track stack index
Definition: paranthesis_matching.cpp:23
main
int main(int argc, char *argv[])
Definition: shell_sort2.cpp:183
main
int main()
Definition: interpolation_search2.cpp:32
compare
int compare(const void *a, const void *b)
Definition: shell_sort2.cpp:87
string_search::brute_force
int brute_force(const std::string &text, const std::string &pattern)
Definition: brute_force_string_searching.cpp:21
main
int main()
Definition: buzz_number.cpp:9
std::is_sorted
T is_sorted(T... args)
qr_algorithm
Functions to compute QR decomposition of any rectangular matrix.
FenwickTree::offset
int offset(int x)
Definition: fenwick_tree.cpp:22
create_matrix
void create_matrix(std::valarray< std::valarray< double >> *A)
Definition: qr_eigen_values.cpp:28
main
int main()
Definition: happy_number.cpp:29
query
Definition: mo.cpp:6
main
int main()
Definition: text_search.cpp:15
show
void show(int *arr, int size)
Definition: merge_sort.cpp:96
test_set
const std::vector< std::vector< std::string > > test_set
Definition: brute_force_string_searching.cpp:41
rec_ternary_search
int rec_ternary_search(int left, int right, int A[], int target)
Definition: ternary_search.cpp:90
Node
Definition: linkedlist_implentation_usingarray.cpp:14
std::vector::push_back
T push_back(T... args)
Point::y
int y
Point respect to x coordinate.
Definition: line_segment_intersection.cpp:14
qr_algorithm::eigen_values
std::valarray< double > eigen_values(std::valarray< std::valarray< double >> *A, bool print_intermediates=false)
Definition: qr_eigen_values.cpp:98
std::clock
T clock(T... args)
string_search::recalculate_hash
int64_t recalculate_hash(const std::string &s, int old_index, int new_index, int64_t old_hash, int patLength)
Definition: rabin_karp.cpp:42
ciphers::STRKEY
static const char * STRKEY
Definition: hill_cipher.cpp:73
main
int main()
Definition: smallest_circle.cpp:198
test_int
void test_int(const int NUM_DATA)
Definition: shell_sort2.cpp:105
pascal_triangle
int ** pascal_triangle(int **arr, int n)
Definition: pascal_triangle.cpp:36
main
int main()
Definition: hill_cipher.cpp:532
CombSort
void CombSort(int *arr, int l, int r)
Definition: comb_sort.cpp:42
insert
node * insert(node *root, int item)
Definition: avltree.cpp:66
std::printf
T printf(T... args)
FenwickTree::FenwickTree
FenwickTree(const std::vector< int > &arr)
Definition: fenwick_tree.cpp:28
mergeSort
void mergeSort(int *arr, int l, int r)
Definition: merge_sort.cpp:83
main
int main()
Definition: matrix_exponentiation.cpp:126
main
int main()
Definition: fast_interger_input.cpp:39
std::cout
qr_decompose.h
Library functions to compute QR decomposition of a given matrix.
merge
void merge(int *arr, int l, int m, int r)
Definition: merge_sort.cpp:33
create_random_array
static void create_random_array(T *arr, int N)
Create a random array objecthelper function to create a random array.
Definition: insertion_sort.cpp:101
h
int h(int key)
Definition: hash_search.cpp:45
std::ofstream
STL class.
sorting::non_recursive_merge_sort
void non_recursive_merge_sort(const Iterator first, const Iterator last)
bottom-up merge sort which sorts elements in a non-decreasing order
Definition: non_recursive_merge_sort.cpp:86
FenwickTree::update
void update(int id, int val)
Definition: fenwick_tree.cpp:45
main
int main(int argc, char const *argv[])
Definition: binary_search.cpp:31
tower
Definition: tower_of_hanoi.cpp:11
_target
#define _target
Definition: ternary_search.cpp:27
binary_search
int binary_search(int a[], int r, int key)
Definition: binary_search.cpp:15
opening
char opening(char ch)
Definition: paranthesis_matching.cpp:36
is_happy
bool is_happy(T n)
Definition: happy_number.cpp:14
std::string::compare
T compare(T... args)
string_search::check_if_equal
bool check_if_equal(const std::string &str1, const std::string &str2, int start1, int end1, int start2, int end2)
Definition: rabin_karp.cpp:60
main
int main()
Definition: median_search.cpp:38
main
int main()
Definition: ternary_search.cpp:134
binomial_range_successes
double binomial_range_successes(double n, double p, double lower_bound, double upper_bound)
Definition: binomial_dist.cpp:74
LenghtLine
double LenghtLine(const Point &A, const Point &B)
Definition: smallest_circle.cpp:37
std::qsort
T qsort(T... args)
ciphers::HillCipher::encrypt_text
static const std::string encrypt_text(const std::string &text, const matrix< int > &encrypt_key)
Encrypt a given text using a given key.
Definition: hill_cipher.cpp:445
std::to_string
T to_string(T... args)
ciphers::HillCipher::decrypt_text
static const std::string decrypt_text(const std::string &text, const matrix< int > &decrypt_key)
Decrypt a given text using a given key.
Definition: hill_cipher.cpp:457
string_search::kmp
bool kmp(const std::string &pattern, const std::string &text)
Definition: knuth_morris_pratt.cpp:56
poisson_range_successes
double poisson_range_successes(double expected, double lower, double upper)
Definition: poisson_dist.cpp:54
main
int main()
Definition: tower_of_hanoi.cpp:65
sorting::non_recursive_merge_sort
void non_recursive_merge_sort(const Iterator first, const Iterator last, const size_t n)
bottom-up merge sort which sorts elements in a non-decreasing order
Definition: non_recursive_merge_sort.cpp:25
ll
#define ll
Definition: matrix_exponentiation.cpp:33
std::string::erase
T erase(T... args)
std::valarray
STL class.
binomial_standard_deviation
double binomial_standard_deviation(double n, double p)
Definition: binomial_dist.cpp:36
TriangleArea
double TriangleArea(const Point &A, const Point &B, const Point &C)
Definition: smallest_circle.cpp:54
main
int main()
Definition: brute_force_string_searching.cpp:47
binomial_x_successes
double binomial_x_successes(double n, double p, double x)
Definition: binomial_dist.cpp:65
test2
void test2()
Definition: qr_eigen_values.cpp:210
std::remove
T remove(T... args)
endl
#define endl
Definition: matrix_exponentiation.cpp:36
link
struct list * link
pointer to nodes
comp
void comp(X x, std::vector< int > *s1, std::vector< int > *s2, std::vector< int > *s3)
Definition: median_search.cpp:17
spiralPrint
void spiralPrint(int **a, int r, int c)
Definition: spiral_print.cpp:29
bayes_BgivenA
double bayes_BgivenA(double AgivenB, double A, double B)
Definition: bayes_theorem.cpp:20
fib_b
vector< ll > fib_b
Definition: matrix_exponentiation.cpp:50
poisson_rate
double poisson_rate(double events, double timeframe)
Definition: poisson_dist.cpp:17
list::key
int key
key value for node
Definition: hash_search.cpp:30
main
int main(int argc, char **argv)
Definition: qr_eigen_values.cpp:243
std::ceil
T ceil(T... args)
circle
double circle(const std::vector< Point > &P)
Definition: smallest_circle.cpp:87
eq
static float eq(float y)
Definition: successive_approximation.cpp:12
struzik_search
Type * struzik_search(Type *array, size_t size, Type key)
Definition: exponential_search.cpp:59
main
int main()
Definition: poisson_dist.cpp:65
std::rand
T rand(T... args)
std::swap
T swap(T... args)
std::min
T min(T... args)
binomial_expected
double binomial_expected(double n, double p)
Definition: binomial_dist.cpp:22
main
int main()
Definition: heap_sort.cpp:120
hashtab
node hashtab[HASHMAX]
array of nodes
Definition: hash_search.cpp:35
std::string::substr
T substr(T... args)
it_ternary_search
int it_ternary_search(int left, int right, int A[], int target)
Definition: ternary_search.cpp:48
test1
void test1(const std::string &text)
Self test 1 - using 3x3 randomly generated key.
Definition: hill_cipher.cpp:470
ciphers::HillCipher::generate_keys
static std::pair< matrix< int >, matrix< int > > generate_keys(size_t size, int limit1=0, int limit2=10)
Generate encryption and decryption key pair.
Definition: hill_cipher.cpp:424
jumpSearch
int jumpSearch(int arr[], int x, int n)
Definition: jump_search.cpp:12
data
int data[MAX]
test data
Definition: hash_search.cpp:24
method1
void method1(int number)
Definition: decimal_to_binary.cpp:11
test1
void test1()
Definition: qr_eigen_values.cpp:177
printArray
void printArray(T *arr, int sz)
Definition: heap_sort.cpp:37
std::lower_bound
T lower_bound(T... args)
main
int main()
Definition: hash_search.cpp:99
std::endl
T endl(T... args)
std::left
T left(T... args)
create_list
void create_list(int key)
Definition: hash_search.cpp:55
fact
double fact(double x)
Definition: poisson_dist.cpp:30
std::exp
T exp(T... args)
std::string::begin
T begin(T... args)
std::getline
T getline(T... args)
std
STL namespace.
addition_rule_independent
double addition_rule_independent(double A, double B)
Definition: addition_rule.cpp:14
show
void show(const struct tower *const F, const struct tower *const T, const struct tower *const U)
Definition: tower_of_hanoi.cpp:19
main
int main()
Definition: sparse_matrix.cpp:9
test
void test()
Definition: smallest_circle.cpp:158
compare
Definition: huffman.cpp:28
main
int main()
Definition: spiral_print.cpp:69
MAX
#define MAX
Definition: paranthesis_matching.cpp:16
stack
Definition: stack.h:26
power
vector< vector< ll > > power(const vector< vector< ll >> &A, ll p)
Definition: matrix_exponentiation.cpp:76
main
int main()
Definition: successive_approximation.cpp:20
std::count
T count(T... args)
tests
void tests()
Definition: insertion_sort.cpp:109
LinearSearch
int LinearSearch(int *array, int size, int key)
Definition: linear_search.cpp:16
std::vector::assign
T assign(T... args)
IsPrime
bool IsPrime(int number)
Definition: primality_test.cpp:18
nCr
double nCr(double n, double r)
Definition: binomial_dist.cpp:47
tower::values
int values[10]
Values in the tower.
Definition: tower_of_hanoi.cpp:13
qr_algorithm::qr_decompose
void qr_decompose(const std::valarray< std::valarray< T >> &A, std::valarray< std::valarray< T >> *Q, std::valarray< std::valarray< T >> *R)
Definition: qr_decompose.h:146
main
int main()
Definition: insertion_sort.cpp:150
genArray
void genArray(int **a, int r, int c)
Definition: spiral_print.cpp:12
main
int main()
Definition: comb_sort.cpp:88
main
int main()
Definition: interpolation_search.cpp:37
add
std::string add(std::string a, std::string b)
Definition: string_fibonacci.cpp:24
std::time
T time(T... args)
main
int main()
Definition: addition_rule.cpp:30
toupperRoman
std::string toupperRoman(int n)
Definition: decimal_to_roman_numeral.cpp:58
LIMS
#define LIMS
Definition: qr_eigen_values.cpp:20
std::string::end
T end(T... args)
bayes_AgivenB
double bayes_AgivenB(double BgivenA, double A, double B)
Definition: bayes_theorem.cpp:14
FenwickTree::sum
int sum(int id)
Definition: fenwick_tree.cpp:54
std::setw
T setw(T... args)
main
int main()
Definition: quick_sort.cpp:82
std::max
T max(T... args)
FenwickTree::FenwickTree
FenwickTree(int x)
Definition: fenwick_tree.cpp:39
Point::Point
Point(double a=0.f, double b=0.f)
Definition: smallest_circle.cpp:23
main
int main()
Definition: primality_test.cpp:31
list::next
struct list * next
pointer to next link in the chain
Definition: hash_search.cpp:31
tower::top
int top
top tower ID
Definition: tower_of_hanoi.cpp:15
Point
Definition: line_segment_intersection.cpp:12
TH
void TH(int n, tower *From, tower *Using, tower *To)
Definition: tower_of_hanoi.cpp:52
interpolation_search
int interpolation_search(int arr[], int value, int len)
Definition: interpolation_search.cpp:15
push
void push(char ch)
push byte to stack variable
Definition: paranthesis_matching.cpp:26
main
int main()
Definition: merge_sort.cpp:102
pop
char pop()
pop a byte out of stack variable
Definition: paranthesis_matching.cpp:29
InterpolationSearch
int InterpolationSearch(int A[], int n, int x)
Definition: interpolation_search2.cpp:15
std::cin
poisson_expected
double poisson_expected(double rate, double time)
Definition: poisson_dist.cpp:25
poisson_x_successes
double poisson_x_successes(double expected, double x)
Definition: poisson_dist.cpp:46
main
int main(void)
Definition: rabin_karp.cpp:105
sorting::quickSort
void quickSort(int arr[], int low, int high)
Definition: quick_sort.cpp:63
std::numeric_limits
string_search::getFailureArray
std::vector< int > getFailureArray(const std::string &pattern)
Definition: knuth_morris_pratt.cpp:33
show_pascal
void show_pascal(int **arr, int n)
Definition: pascal_triangle.cpp:18
string_search::rabin_karp
int rabin_karp(const std::string &str, const std::string &pat)
Definition: rabin_karp.cpp:83
get_input
void get_input()
Definition: ternary_search.cpp:36
PointInCircle
bool PointInCircle(const std::vector< Point > &P, const Point &Center, double R)
Definition: smallest_circle.cpp:72
std::getchar
T getchar(T... args)
tests
void tests()
Definition: comb_sort.cpp:73
list
Definition: list_array.cpp:8
std::memset
T memset(T... args)
binomial_variance
double binomial_variance(double n, double p)
Definition: binomial_dist.cpp:29
std::next
T next(T... args)
sorting::shell_sort
void shell_sort(std::vector< T > *arr)
Definition: shell_sort2.cpp:75
fastinput
void fastinput(int *number)
Definition: fast_interger_input.cpp:11
std::pow
T pow(T... args)