Skip to content

Instantly share code, notes, and snippets.

@awnigharbia
Last active December 12, 2018 20:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awnigharbia/5ab0dda6840d94d98a9fe1cd0b1541ca to your computer and use it in GitHub Desktop.
Save awnigharbia/5ab0dda6840d94d98a9fe1cd0b1541ca to your computer and use it in GitHub Desktop.
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