Skip to content

Instantly share code, notes, and snippets.

@scriptype
Last active November 18, 2016 18:26
Show Gist options
  • Save scriptype/3584b4e70533adfb254502b8e16e3417 to your computer and use it in GitHub Desktop.
Save scriptype/3584b4e70533adfb254502b8e16e3417 to your computer and use it in GitHub Desktop.
Encryption with XOR and non-secure PRNG
function toBinary(plainText) {
return plainText.split('').map(c => {
return ('0'.repeat(BIT_COUNT) + c.charCodeAt(0).toString(2)).slice(-BIT_COUNT)
})
}
function generateKey(len) {
return ' '.repeat(len * BIT_COUNT).split('').reduce(p => p + ~~(Math.random() * 2), '')
}
function encrypt(binary, key) {
return binary.reduce((prev, bin, index) => {
return prev + bin.split('').reduce((p, b, i) => {
return p + (+b ^ +key[index + i]).toString(2)
}, '')
}, '')
}
function decrypt(binary, key) {
return binary.match(new RegExp(`.{1,${BIT_COUNT}}`, 'g')).reduce((prev, bin, index) => {
return prev + String.fromCharCode(parseInt(bin.split('').reduce((p, b, i) => {
return p + (+b ^ +key[index + i])
}, ''), 2))
}, '')
}
var valueRangeLimit = 1024 // Assuming that we won't need charCodes greater than 1024
var BIT_COUNT = Math.log2(valueRangeLimit)
var str = 'merhaba dünya'
var plainBinary = toBinary(str)
var key = generateKey(plainBinary.length)
var encrypted = encrypt(plainBinary, key)
var decrypted = decrypt(encrypted, key)
console.log(encrypted)
console.log(decrypted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment