A very simple cryptography JavaScript module created for my xmas calendar 2013.
var encryption = function() { | |
// Works with ASCII chars from 32 (space) | |
// to 248 (å). | |
var shiftCharCode = function(code, shift) { | |
if (shift < 0) shift += (248 - 32 + 1) | |
return 32 + (((code - 32) + shift) % (248 - 32 + 1)); | |
}; | |
var shiftString = function(s, shift) { | |
var s2 = ""; | |
for(var i in s) { | |
var char_code = s.charCodeAt(i); | |
var new_char_code = shiftCharCode(char_code, shift); | |
s2 += String.fromCharCode(new_char_code); | |
} | |
return s2; | |
}; | |
var shiftRight = function(s) { | |
return shiftString(s, 1); | |
}; | |
var shiftLeft = function(s) { | |
return shiftString(s, -1); | |
}; | |
var moveRight = function(s) { | |
var lastIndex = s.length - 1; | |
return s[lastIndex] + s.substring(0,lastIndex); | |
}; | |
var moveLeft = function(s) { | |
return s.substring(1) + s[0]; | |
}; | |
var addNoice = function(s) { | |
var randomChar = Math.floor(Math.random()*(122-65+1)) + 65; | |
return s + String.fromCharCode(randomChar); | |
}; | |
var removeNoice = function(s) { | |
return s.substring(0, s.length-1); | |
}; | |
var encrypters = [shiftRight, moveRight, addNoice]; | |
var decrypters = [shiftLeft, moveLeft, removeNoice]; | |
return { | |
shiftLeft : shiftLeft, | |
encrypt: function(text, strength) { | |
var result = { encrypted:text, key:'' }; | |
while (strength-- > 0) { | |
var nextKeyPart = Math.floor(Math.random()*encrypters.length); | |
var nextEncrypter = encrypters[nextKeyPart]; | |
result.encrypted = nextEncrypter(result.encrypted); | |
result.key += nextKeyPart; | |
} | |
return result; | |
}, | |
decrypt: function(text, key) { | |
for(var i=key.length-1; i >= 0 ; i--) { | |
text = decrypters[key[i]](text); | |
} | |
return text; | |
} | |
}; | |
}(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment