Crypt
October 28, 2011
In their book Software Tools, Brian Kernighan and P. J. Plauger describe a simple command for encrypting files. It works by xor-ing each byte of a file with a byte of the key, extending the key cyclically until it is the same length as the text. The xor operation is symmetric, so only one program is needed to perform both encryption and decryption. This isn’t a particularly secure encryption algorithm; we showed how to break it in one of our earliest exercises.
Your task is to implement a function that takes a filename and a key and returns the encrypted/decrypted output. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
A Haskell solution: https://gist.github.com/1322212
Another Haskell solution: http://pfcuttle.tumblr.com/post/12032209206/crypt
A factor solution: https://gist.github.com/1325006
Sorry I’ve taken so long to join in; here’s a Python solution:
A javascript solution
function crypt(file,key) {
var key_index = 0,
cont = 0,
end_file_cod = [],
end_file = [],
key_size = key.length;
file_size = file.length;
for (; cont < file_size; cont++) {
var file_cd = (file[cont].charCodeAt(0));
var key_cd = (key[key_index].charCodeAt(0));
end_file_cod.push(file_cd ^ key_cd);
key_index = (key_index == key_size – 1) ? 0 : key_index += 1;
}
for (var j = 0; j < end_file_cod.length; j++) {
end_file.push(String.fromCharCode(end_file_cod[j]));
}
return end_file.join("");
}
function crypt(file,key) {
var key_index = 0,
cont = 0,
end_file_cod = [],
end_file = [],
key_size = key.length;
file_size = file.length;
for (; cont < file_size; cont++) {
var file_cd = (file[cont].charCodeAt(0));
var key_cd = (key[key_index].charCodeAt(0));
end_file_cod.push(file_cd ^ key_cd);
key_index = (key_index == key_size – 1) ? 0 : key_index += 1;
}
for (var j = 0; j < end_file_cod.length; j++) {
end_file.push(String.fromCharCode(end_file_cod[j]));
}
return end_file.join("");
}
javascript solution: http://jsfiddle.net/Klawztro/ESwBc/