Skip to content

Instantly share code, notes, and snippets.

@royhowie
Last active December 3, 2015 04:15
Show Gist options
  • Save royhowie/59916903ddab9d87602e to your computer and use it in GitHub Desktop.
Save royhowie/59916903ddab9d87602e to your computer and use it in GitHub Desktop.
// public key: [23, 55]
// private key: [7, 55]
class Decrypter {
constructor (priv, pub, mod) {
this.private = priv
this.public = pub
this.mod = mod
}
decryptMessage (arr) {
return arr
.map((num) => Decrypter.powerMod(num, this.private, this.mod))
.map(Decrypter.mapToChar)
.join('')
}
encryptMessage (message) {
return message
.split('')
.map(Decrypter.mapFromChar)
.map((num) => Decrypter.powerMod(num, this.public, this.mod))
}
static mapFromChar (char) {
let code = char.toUpperCase().charCodeAt(0)
if (65 <= code && code <= 90) {
return code - 64
}
switch (code) {
case 46: return 27 // 27 is for period
case 32: return 28 // 28 is for space
case 33: return 29 // 29 is for exclamation point!
default: throw new Error('Out of bounds exception!')
}
}
static mapToChar (num) {
if (0 < num && num < 27) {
return String.fromCharCode(num + 64)
}
switch (num) {
case 27: return '.'
case 28: return ' '
case 29: return '!'
default: throw new Error('Out of bounds exception!')
}
}
static powerMod (n, pow, mod) {
if (pow <= 1) return n
let r = Decrypter.powerMod(n, pow >> 1, mod)
if (pow % 2 === 0) {
return (r * r) % mod
} else {
return (n * r * r) % mod
}
}
}
let message = [
25, 17, 1, 49, 11, 39, 7, 51, 20, 2, 7, 23, 15, 1, 2, 49, 14, 49, 13, 7, 1,
8, 20, 21, 25, 7, 1, 8, 39, 25, 2, 1, 27, 25, 7, 52, 1, 25, 17, 15, 52, 1,
25, 14, 27, 39, 48, 17, 1, 33, 15, 7, 1, 7, 13, 2, 15, 1, 25, 7, 12, 14, 49,
25, 15, 2, 7, 8, 2, 15, 1, 11, 24
]
let RSA = new Decrypter(7, 23, 55)
let decryptedMessage = RSA.decryptMessage(message)
let reEncryptedMessage = RSA.encryptMessage(decryptedMessage).join(' ')
console.log(`DECRYPTED MESSAGE:\t${decryptedMessage}`)
console.log('------------')
console.log(`ORIGINAL MESSAGE:\t${reEncryptedMessage}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment