Skip to content

Instantly share code, notes, and snippets.

@awnigharbia awnigharbia/Hill-cipher.js
Last active Dec 12, 2018

Embed
What would you like to do?
const plainText = 'ATTACK IS TONIGHT'
const key = [[3, 10, 20], [20, 9, 17], [9, 4, 17]]
let cipherText = ''
const letter = [
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z',
]
// do mod operation on two numbers
const mod = (m, n = 26) => {
return ((m % n) + n) % n
}
// run multiple operation sequential
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x)
// get the number of letters A-Z
const getStringNumber = plainTextArray => {
return plainTextArray.map(item => letter.indexOf(item))
}
// Transform plaintex to array with removing spaces
const trsnformStringToArray = str => Array.from(str).filter(x => x !== ' ')
// divide the array into small chunks with specified length
const chunk = (myArray, chunk_size = 3) => {
let results = []
while (myArray.length) {
results.push(myArray.splice(0, chunk_size))
}
return results
}
// make key ready for multiplication by re-sort it
const transformKey = key => {
let result = []
let j, i
for (i = 0; i < key.length; i++) {
for (j = 0; j < key.length; j++) {
result.push(key[j][i])
}
}
return chunk(result)
}
// divide the string into 3x3 matrix chunks
const chunks = pipe(
trsnformStringToArray,
getStringNumber,
chunk,
)
// multiple two diff arrays
const mupltipleArray = arr1 => arr2 => {
let sum = 0
let result = []
arr1.map(item1 =>
arr2.map(item2 =>
item1.reduce(function(r, a, i) {
sum += a * item2[i]
if (i === 2) {
result.push(sum)
sum = 0
}
return
}, []),
),
)
return result
}
// get the mod for every operation
const getMod = arr => arr.map(item => mod(item))
// get the string that matches the encrypted character
const getString = arr => arr.reduce((acc, cur) => acc + letter[cur], '')
const multipledArr = mupltipleArray(chunks(plainText))(transformKey(key))
const cipher = pipe(
getMod,
getString,
)
console.log(cipher(multipledArr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.