Crypt
October 28, 2011
Our solution uses a do
with two variables that are stepped in parallel: key
cycles through the characters of the key and char
indexes through the input file:
(define (crypt key infile outfile)
(define (last-pair xs) (if (null? (cdr xs)) xs (last-pair (cdr xs))))
(define (cycle xs) (set-cdr! (last-pair xs) xs) xs)
(with-input-from-file infile (lambda ()
(with-output-to-file outfile (lambda ()
(do ((key (cycle (map char->integer (string->list key))) (cdr key))
(char (read-char) (read-char)))
((eof-object? char))
(display (integer->char (logxor (car key) (char->integer char))))))))))
The xor function has been called logxor
since the early days of Lisp, and though it’s not part of R5RS Scheme, most Scheme interpreters provide it; if yours doesn’t, there is a portable version in the Standard Prelude. R6RS Scheme broke compatibility with the past, as it did in so many needless ways, by calling the function bitwise-xor
.
You can see the program at http://programmingpraxis.codepad.org/SUkyyUpu.
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/