Recently, I have been interested in creating a quick one-way encryption method. After playing around with a lot of different variations, I settled on the following:
function encrypt(message, length) {
// If the message is the empty string, return the empty string.
if(message == "") {
return "";
}
// Calculate the offset of the first character.
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
for(var last = 0, i = 0, len = message.length; i < len; i++) {
last = (message.charCodeAt(i) + 31 * last) % 59;
}
// Adjust for the specified length if it was given.
length = length || message.length;
while(len < length) {
message += message;
len += len;
}
message = message.slice(0, length);
// Generate the encrypted string.
for(var ret = "", i = 0; i < length; i++) {
ret += chars[last = (i + last + message.charCodeAt(i)) % 64];
}
return ret;
}
One nice thing about this function is the fact that you can restrict the encrypted message to a certain length. Another interesting thing is that, the ordering of the characters in the string matters. One last thing that I find interesting is that it truly acts as a one-way encryption method as long as there is more than one character (meaning you can’t decrypt the message once it is encrypted).
The main reason I created this function was to encrypt strings used to verify that a person is who they say they are (kind of like a password, but not exactly in my case
). All I have to say is, if you think you can break this encryption for string longer than one character, please let me know!