next up previous
Next: Affine enciphering Up: fsqFsHn sGGousG Previous: Improved Caesar-like ciphers

Reading and Writing from a file

While none of the methods we have covered yet are secure enough to foil a good cryptanalyst, the OneTimePad procedure of §5.2 is good enough for household use (unless you live with cryptanalysts!) Should we want to really use it, however, we would find it extremely tedious to type in our message each time, and then copy the encrypted text from the worksheet.

Fortunately, Maple is able to read and write data from a file, using readline and writeline. These read (or write) a single line of data from a specified file.4.22. When reading from a file, readline returns either a line of data, or 0 when the end of the file is reached.

Although it is not strictly necessary, it is a good idea to explicitly open the file before dealing with it, and close it when you are done. In addition to being good practice (like explicitly declaring variables), it also allows you to specify certain options, like whether you intend to read or write to the file. In fact, I recommend using fopen, which also allows you to specify whether the file should be treated as text or binary.4.23 Below is a small example of a procedure which encrypts a file one line at a time using a procedure EncryptLine. We have never given such a procedure, but it should be clear how to modify it to use your favorite encryption routine instead.

> 
  Cryptfile := proc(plainfilename,cryptfilename,key)
    local line, cline, file, cryptf;
  

  file :=fopen(plainfilename,READ,TEXT);   cryptf:=fopen(cryptfilename,WRITE,TEXT);  

  line :=readline(file);   while (line <> 0) do   writeline(cryptf,EncryptLine(line,key));   line :=readline(file);   od;   close(file);   close(cryptf);   end:



Footnotes

... file.4.22
If you are treating a newline as a character, you will need to deal with the file on a byte-by-byte basis, using readbytes and writebytes
... binary.4.23
On several operating systems, including MS-Windows and MacOS (but not Unix or Linux), files may be treated as containing text or binary data. When dealing with a text file, some control characters (such as the end-of-line marker) are translated to a format more suitable for use. When opening the file, we can tell Maple whether it should be dealt with as text or binary. If you neglect to specify which, you may find your file has one very long line if you open it in a text editor. Under Unix, text and binary files are the same, so no translation is necessary, but there is no harm in specifying the file type.

next up previous
Next: Affine enciphering Up: fsqFsHn sGGousG Previous: Improved Caesar-like ciphers

Translated from LaTeX by Scott Sutherland
2002-08-29