next up previous
Next: Bibliography Up: fsqFsHn sGGousG Previous: The RSA Public key

RSA encoding a file

Now we will write a procedure that uses RSA to encrypt a file, rather than a string. Of course, we could just read in the string and use RSAEncryptString, but in some cases, it makes sense to use a different alphabet for the crypttext. For example, we might want to accept all possible ASCII codes 0-255 as plaintext input, but restrict our encrypted output to use only alphanumeric characters (so that it can be printed or emailed without transcription problems, say).

Below is a procedure which reads the contents of a file, encrypts it with RSA, and writes out the result to another file.

> 
  RSAEncodeFile:=proc(plainfile::string, cryptfile::string, key::list(posint))
    local  k, pf, cf, chunk, chunklen, codenum, crypt, Alen;
    global Alphabet;
  

  Alen := length(Alphabet);   chunklen:= ceil(log[Alen](key[1]));   k := floor(log[256](key[1]));  

  try   pf := fopen(plainfile, READ, BINARY);   cf := fopen(cryptfile, WRITE, TEXT);   chunk := readbytes(pf, k);   while (chunk <> 0) do   codenum := map(RSAEncodeNum,   convert( chunk, base, 256, 256^k),   key);   crypt:=KgraphToString(codenum, chunklen);   writeline(cf, crypt);   chunk := readbytes(pf, k);   od;  

  finally   fclose(cryptfile);   fclose(plainfile);   end try;   RETURN();   end:

> 
  RSADecodeFile:=proc(cryptfile::string, plainfile::string, key::list(posint))
    local  k, pf, cf, chunk, chunklen, plain, crypt, Alen;
    global Alphabet;
  

  Alen := length(Alphabet);   chunklen:= ceil(log[Alen](key[1]));   k:= floor(log[256](key[1]));  

  try   pf := fopen(plainfile, WRITE, BINARY);   cf := fopen(cryptfile, READ, TEXT);   chunk := readline(cf);   while (chunk <> 0) do   plain:= convert(   map(RSAEncodeNum,   StringToKgraph(chunk, chunklen),   key),   base, 256^k, 256);   writebytes(pf, plain);  

  chunk := readline(cf);   od;  

  finally   fclose(cryptfile);   fclose(plainfile);   end try;  

  RETURN();   end:


next up previous
Next: Bibliography Up: fsqFsHn sGGousG Previous: The RSA Public key

Translated from LaTeX by Scott Sutherland
2002-08-29