program GENERATE_PASSWORDFILE;
{
 The program encrypts an entered password and saves it
 in the file PASSWORD.DAT.
  Author: Boris Bertelsons
 (c)'95 Data Becker GmbH
 (c)'95 ABACUS Software, Inc
}

Uses Crt;

var password : string;
    pwf : file;
    check : word;
    key : char;

function Encrypt(pasw : string;add : char) : string;
var li : integer;
begin
  for li := 1 to 255 do begin;
    pasw[li] := char(255 xor (ord(pasw[li]) + ord(add)));
  end;
  Encrypt := Pasw;
end;

function Gen_checksum(pasw : string) : word;
var sum : word;
    li : integer;
begin
  sum := 0;
  for li := 1 to ord(pasw[0]) do begin;
    sum := sum + ord(pasw[li]);
  end;
  Gen_checksum := sum;
end;

function Decrypt(pasw : string;add : char) : string;
var li : integer;
begin
  for li := 1 to 255 do begin;
    pasw[li] := char((255 xor ord(pasw[li])) - ord(add));
  end;
  decrypt := Pasw;
end;

function Checksum_Ok(pasw : string; Key: char; sum : word) : boolean;
var tsum : word;
    li : integer;
    h : char;
begin
  tsum := 0;
  for li := 1 to ord(pasw[0]) do begin
    tsum := tsum + ord(pasw[li]);
  end;
  if sum = tsum then
    Checksum_Ok := true
  else
    Checksum_Ok := false;
end;

begin  
  clrscr;
  writeln('Please enter the password to be encrypted !');
  write('Password: ');
  readln(password);
  writeln('Please enter the key (any randomly selected ASCII character)');
  write('Key: ');
  readln(key);
  writeln('Writing information to file ...');
  writeln;

  check := Gen_checksum(password);
  password := encrypt(password, key);

  assign(pwf,'PASSWORD.DAT');
  rewrite(pwf,1);
  blockwrite(pwf,key,1);
  blockwrite(pwf,password,256);
  blockwrite(pwf,check,2);
  close(pwf);

  reset(pwf,1);
  blockread(pwf,key,1);
  blockread(pwf,password,256);
  blockread(pwf,check,2);
  close(pwf);

  writeln('Rereading Information for verification ...');
  writeln('Encrypted : ',password);
  writeln('Key: ',key);

  Password := decrypt(password,key);
  writeln('Verify  : ',password);
  If Checksum_Ok(password,key,check) then
    writeln('Checksum O.K.')
  else
    writeln('WARNING! Checksum not correct !');

  repeat until keypressed; readkey;
end.