#
# $Source: /home/nlfm/Working/Zircon/Released/plugins/Sed/RCS/decrypt.tcl,v $
# $Date: 1999/11/26 09:34:49 $
# $Revision: 1.18.1.2 $
#
package provide Sed 1.18.1
#
switch -glob -- [info tclversion] 7.* {
proc decrypt {string key} {
    switch {} $key {return {<ENCRYPTED TEXT>}}
    global zircon
    return [exec $zircon(lib)/plugins/Sed/crypt D "$string" "$key"]
}
#
proc encrypt {string key} {
    global zircon
    return "\001SED [exec $zircon(lib)/plugins/Sed/crypt E "$string" "$key"]\001"
}
#
} default {
#
proc debin {val} {
    return [string index "\001\000\n\r\\" $val]
}
#
proc decrypt {string key} {
    if {[set klen [string length $key]] == 0} {return {<ENCRYPTED TEXT>}}
    regsub -all {\$} $string "\\\$" string
    regsub -all {\[} $string "\\\[" string
    regsub -all {\\\\} $string {[debin 4]} string
    regsub -all {\\a} $string {[debin 0]} string
    regsub -all {\\0} $string {[debin 1]} string
    regsub -all {\\n} $string {[debin 2]} string
    regsub -all {\\r} $string {[debin 3]} string
    set vern 0
    set cycle 0
    foreach x [split $key {}] {
    	binary scan $x c1 gx
    	lappend knx $gx
    }
    foreach x [split [subst $string] {}] {
    	binary scan $x c1 gx
	set vl [expr {$vern ^ $gx ^ [lindex $knx $cycle]}]
	append str [binary format c1 $vl]
	set vern [expr {$vern ^ $vl}]
	set cycle [expr {($cycle + 1) % $klen}]
    }
    return $str
}
#
proc encrypt {string key} {
    if {[set klen [string length $key]] == 0} {return "<ENCRYPTED TEXT>"}
    set vern 0
    set cycle 0
    foreach x [split $key {}] {
    	binary scan $x c1 gx
    	lappend knx $gx
    }
    set str {}
    foreach x [split $string {}] {
    	binary scan $x c1 gx
	set vl [expr {$vern ^ $gx ^ [lindex $knx $cycle]}]
	append str [binary format c1 $vl]
	set vern [expr {$vern ^ $gx}]
	set cycle [expr {($cycle + 1) % $klen}]
    }
    regsub -all {\\} $str {\\\\} str
    regsub -all "\001" $str "\\a" str
    regsub -all "\000" $str {\\0} str
    regsub -all "\n" $str {\\n} str
    regsub -all "\r" $str {\\r} str
    return "\001SED $str\001"
}
}
