Version 0 of Encryption and Decryption

Updated 2001-02-12 06:26:12

From a news:comp.lang.tcl posting by mailto:[email protected]

In case anyone is interested, attached is what I use to encrypt/decrypt data files. Since I am trying to keep my program small, I decided to write my own functions instead of including another whole package like Trf.

I haven't looked at them in a while, so they might not be as cleaned up as possible.

I included a function I use to wrap it, but no full example code (too lazy), but it should be fairly easy to write :).

Please let me know any suggestions/comments.

Ryan

 global enc_string
 global enc_idx

 proc {encrypt} {str} {
 #
  global enc_string
  global enc_idx
  set crypt_str ""
  for {set i 0} {$i < [string length $str]} {incr i 1} {
    set curnum [expr {[to_ascii [string index $str $i]] + [to_ascii [string index $enc_string $enc_idx]]}]
    if {$curnum > 255} {set curnum [expr {$curnum - 256}]}
    set crypt_char [format %c $curnum]
    set crypt_str "$crypt_str$crypt_char"
    set enc_idx [incr enc_idx 1]
    if {$enc_idx == [string length $enc_string]} {set enc_idx 0}
  }
  return $crypt_str
 }

 proc {decrypt} {str} {
 #
  global enc_string
  global enc_idx
  set crypt_str ""
  set strlen [string length $str]
  if {$strlen == 0} {return}
  for {set testx 0} {$testx < $strlen} {incr testx 1} {
    set curnum [expr {[to_ascii [string index $str $testx]]-[to_ascii [string index $enc_string $enc_idx]]}]
    if {$curnum < 0} {set curnum [expr {$curnum + 256}]}
    set crypt_str "$crypt_str[format %c $curnum]"
    set enc_idx [incr enc_idx 1]
    if {$enc_idx == [string length $enc_string]} {set enc_idx 0}
  }
  return $crypt_str
 }

 proc {readFile} {filename} {
  set ::enc_idx 0
  set fp [open $filename r]
  fconfigure $fp -encoding identity
  set data [split [read $fp $size] \n]
  foreach line $data {
    puts [decrypt $line]
  }
  close $fp
 }

 proc {writeFile} {filename} {
  set enc_string "password"
  set enc_idx 0
  set fp [open $filename r]
  fconfigure $fp -encoding identity

  # Write out your information using "puts $fp [encrypt XXXXX]"

  close $fp
 }