Current area: HOME -> Blogs -> Actor's Blog -> Read Post

File encryption and decryption, Part I

Posted on Saturday, January 19, 2008 at 5:42 PM
The next program is one which appeared in the original Software Tools but not in Software Tools in Pascal. The program is Crypt which encrypts and decrypts a text file.

The algorithm for the encryption is what cryptologists call a "one time pad" (google it). When properly used it is theoretically unbreakable. What we are doing here does not include all the steps entailed in properly using the algorithm but it should prevent the casual snoop from decoding your files.

The algorithm consists of merging the input stream of data with a second stream, the key, to produce an output stream of encrypted data. We extract the ascii codes from each char of input and from each char of the key. A bitwise XOR operation gives us the ascii code for the output which is converted back to a char. Here is the code for Crypt.
Program Crypt ;
{
	Crypt -- encrypt and decrypt
}
var
	Key      :  String ;
	KeyLen   :  Byte ;
	i        :  Byte ;
	Ch       :  Char ;
begin
	if ParamCount > 0 then
		begin
			Key      := ParamStr(1) ;
			KeyLen   := Length(Key) ;
			i := 1 ;
			while NOT eof do begin
				Read(Ch) ;
				Write (Chr(Ord(Ch) XOR Ord(Key[i]))) ;
				i := (i MOD KeyLen) + 1
			end
		end
	else
		WriteLn('usage: crypt key')
end.
The key is a string up to 255 characters long. The input and output files are selected by redirection. E.g.:
crypt keystring < in.txt > out.txt
The elegant property of the XOR operator is that it is its own reciprocal operator. I.e., if
	c = a XOR b
then
	b = a XOR c
This allows us to use the same program for both encryption and decryption by merely switching the source and destination files.

OK! Try the following:
crypt buttermilk > crypt.dat
Now is the time for all good men to come to the aid of their country.
^Z
This should encrypt "Now is the time for all good men to come to the aid of their country." and store it in the file crypt.dat. Now we should be able to get the original text back by using crypt again. However, if we redirect crypt.dat back though crypt we get
	crypt buttermilk < crypt.dat
	N
All we get is the leading N. Why? Clearly there is a bug in the program.

The bug lies in the fact that for text files DOS treats Chr(26) as an end-of-file marker. When the 'u' in 'buttermilk' meets the 'o' in 'Now is the time...' we get
	Chr(Ord('o') XOR Ord('u')) = Chr(26)
In encrypting any file with any key we can expect this condition to surface frequently.

One easy fix for this is to assume that the input will consist only of the standard ascii characters, Chr(0) .. Chr(127). In this case the most significant bit will always be zero. If we make sure that the first bit of the key is one then the resulting encrypted bit will be one. Here is the modified code.
Program Crypt ;
{
	Crypt -- encrypt and decrypt
}
		Function Map (S : String) : String ;
		{
			maps ascii characters onto the extended ascii set         
		}
		Var
			i  :  Byte ;
		
		begin
			for i := 1 to Length(S) do
				if Ord(S[i]) < 128 then
					S[i] := Chr(Ord(S[i]) + 128) ;
			Map := S
		end ;

var
	Key      :  String ;
	KeyLen   :  Byte ;
	i        :  Byte ;
	Ch       :  Char ;
begin
	if ParamCount > 0 then
		begin
			Key      := Map(ParamStr(1)) ;
			KeyLen   := Length(Key) ;
			i := 1 ;
			while NOT eof do begin
				Read(Ch) ;
				Write (Chr(Ord(Ch) XOR Ord(Key[i]))) ;
				i := (i MOD KeyLen) + 1
			end
		end
	else
		WriteLn('usage: crypt key')
end.
Now all the encrypted code is mapped to the extended ascii set. We can still use the same program for both encryption and decryption.

The bug survives but in a more tolerable form. An uncrypted file that contains an extended ascii character could still generate an unexpecgted eof. I doubt that a totally satisfactory solution can be found. For now we'll simply list it as a "known bug."

Comments
uiuy - Posted on Sunday, January 20, 2008 at 11:15 PM by xz116926
??

??

???
ddae - Posted on Sunday, June 08, 2008 at 5:54 AM by kkdai
http://www.blurty.com/users/daiqianwen
http://daiqianwen.iblog.com/
http://daiqianwen.exblog.jp/
http://blog.oricon.co.jp/daiqianwen/
http://daiqianwen.cocolog-nifty.com/
http://daiqianwen.blog.com/
http://daiqianwen.reger.com/
http://blog.qooza.hk/daiqianwen
http://blog.roodo.com/ediedai
http://www.mw.net.tw/user/daiqianwen/
http://ameblo.jp/daiqianwen/
http://plaza.rakuten.co.jp/daiqianwen/
http://www.voiceblog.jp/daiqianwen/
http://look.urs.tw/show.php?BlogID=69747
http://daiqianwen.realog.jp/blog.html
http://blog.udn.com/daiqianwen
http://www.blogkaki.net/?uid-9180
http://blog.xuite.net/daiqianwen/blog
http://blog.dreamhome.com.tw/more.asp?name=daiqianwen&id=14651
http://blog.105life.com/?2227
http://www.hkhostcity.com/?uid-41001
http://ecstart.com/?69896
http://space.mcy.hk/?849679
http://blog.hkmz.net/?9087
http://space.kyohk.net/?440667
http://blogs.albawaba.com/daiqianwen
http://space.sitelala.com/?id=1496
http://blog.youth-online.com/?uid-2543
http://www.wasblog.com/daiqianwen/
http://www.hkheadline.com/blog/list_blog_edit.asp?f=8OSEJ3R77I110122
http://www.debian.org.hk/blog/daiqianwen
http://blog.newsgroup.la/?50445
http://blog.visualmedia.com.hk/?uid-5380
http://360.yahoo.com/sunndaybilly
http://del.icio.us/zoedai


Sponsored links

Build IT Knowledge with Current & Trusted Content
Helps Employees Develop & Hone New Technical Programming Skills. Sign Up & Get Full Access.
Check Out IT Certification Preparation Materials
Sign Up With SkillSoft & Get Access to Training Materials for Over 50 Professional Certifications.
Localize software in three simple steps
Localize .Net, C/C++ & Delphi apps visually. HTML, HTML Help, XML & databases. Try Sisulizer now!
Delphi Localization Tool Sisulizer (WYSIWYG)
Create multilingual Delphi apps in three simple steps. Localize XML, HTML Help ... Try Sisulizer now
Web based bug tracking - AdminiTrack.com
AdminiTrack offers an effective web-based bug tracking system designed for professional software development teams.


Newsletter | Submit Content | About | Advertising | Awards | Contact Us | Link to us |
© 1996-2008 Community Networks Ltd All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Synchron Data - .NET development.