Created
October 5, 2016 06:53
-
-
Save t3h2mas/0bc51e4a4c3ed69c7fb64720cfe385ae to your computer and use it in GitHub Desktop.
cryptopals set 1 challenge 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const xor = (str, key) => | |
Buffer.from(str, 'hex').map(byte => byte ^ key); | |
const getFreq = (str) => | |
str.toLowerCase().split('').reduce((result, item) => {result[item] = (result[item] || 0) + 1; return result}, {}); | |
const weightFreq = (str) => { | |
const letterWeights = { | |
e: 12.702, | |
t: 9.056, | |
a: 8.167, | |
o: 7.507, | |
i: 6.966, | |
n: 6.749, | |
s: 6.327, | |
h: 6.094, | |
r: 5.987, | |
d: 4.253, | |
l: 4.025, | |
u: 2.758 | |
}; | |
const tokens = str.toLowerCase().split(''); // this doesn't account for nonvalid tokens (whitespace / symbols / etc) | |
const len = tokens.length; | |
let weight = 0; | |
for (let i=0; i < len; i++) { | |
let token = tokens[i]; | |
weight += letterWeights[token] || 0; // rewrite w/ reduce | |
} | |
return len / weight; | |
} | |
const findMessage = (msg) => { | |
let start = 'a'.charCodeAt(0); | |
let end = 'z'.charCodeAt(0); | |
for (let i = start; i < (end + 1); i++) { | |
console.log(i.toString() + ' (' + String.fromCharCode(i) + ')'); | |
// console.log(xor(msg, i)); // hex | |
let msgStr = xor(msg, i).toString(); | |
console.log(weightFreq(msgStr)); | |
//console.log(xor(msg, i).toString()); | |
} | |
} | |
const msg = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'; | |
findMessage(msg); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment