## 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.

Pages: 1 2

### 7 Responses to “Crypt”

1. Graham said

Sorry I’ve taken so long to join in; here’s a Python solution:

```from itertools import cycle, imap

def crypt(key, infile, outfile):
kstream = cycle(key)
text_xor = lambda a, b: chr(ord(a) ^ ord(b))
with open(infile) as inf:
with open(outfile, 'w') as outf:
```
2. 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("");
}

3. klawztro said

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("");
}