AES CTR

Working on web programs I found a need to exchange encrypted content. On the browser side finding javascript crypto libraries wasn't difficult. After some experimenting, I settled on the AES-CTR "reference implementation" by Chris Veness. [1 ]

The server was harder. I'd written a server in Tcl, but there weren't any Tcl AES-CTR implementations to be found. The tcllib AES handles CBC but not CTR mode. After I modified it to do CTR, the tcllib code would encrypt/decrypt OK. Problem was it wouldn't work with text encrypted by the JS (or another) AES-CTR program.

Therefore I was inspired to build a Tcl version that works with the javascript implementation I was using. The result was a Tcl AES-CTR implementation that decrypts text encrypted with JS in the browser and vice versa.

Pretty straightforward to use. Loading aes.js and aes-ctr.js in the web page allows access to the encrypt/decrypt functions. Sourcing aesctr.tcl in Tcl exposes similar encrypt and decrypt commands.

In Tcl, calling encrypt/decrypt:

  encrypt "This is text to be encrypted" "A password" 256 
  ==> 4ACtkN/r7lRmY/sfmtulg1KSGPu/0E0YSfYzBIIu0otrGOD5

  decrypt 4ACtkN/r7lRmY/sfmtulg1KSGPu/0E0YSfYzBIIu0otrGOD5 "A password" 256
  ==> This is text to be encrypted

In javascript:

  AesCtr.decrypt("4ACtkN/r7lRmY/sfmtulg1KSGPu/0E0YSfYzBIIu0otrGOD5", "A password", 256);
  ==> "This is text to be encrypted"

  AesCtr.encrypt("This is text to be encrypted", "A password", 256);
  ==> "4ACtkN/r7lRmY/sfmtulg1KSGPu/0E0YSfYzBIIu0otrGOD5"

The Tcl AES-CTR commands work correctly but no doubt could be better optimized. As an informal benchmark, on my Surface Pro 2, the Tcl encrypt example above runs in 8.80 millisec. The decrypt command consumed 8.86 millisec. I didn't test other implementations.

## aesctr.tcl

## AES CTR in Tcl.
## (C) 2015 J. Altfas
##
## This Tcl implementation is intended to be compatible with the JS
## version referenced below, that is, text encrypted using JS can be
## decrypted in Tcl and vice versa.  
##
## Usage: 
##      encrypt <input text (string)> <password (string)> 128|192|256
##      decrypt <encryp msg (string)> <password (string)> 128|192|256
## 
## Reference code: aes.js, aes-ctr.js 
##   "AES Counter-mode implementation in JavaScript"
##   (c) Chris Veness 2005-2014 / MIT Licence
##   https://github.com/chrisveness/crypto

set sBox {
    0x63 0x7c 0x77 0x7b 0xf2 0x6b 0x6f 0xc5 0x30 0x01 0x67 0x2b 0xfe 0xd7 0xab 0x76
    0xca 0x82 0xc9 0x7d 0xfa 0x59 0x47 0xf0 0xad 0xd4 0xa2 0xaf 0x9c 0xa4 0x72 0xc0
    0xb7 0xfd 0x93 0x26 0x36 0x3f 0xf7 0xcc 0x34 0xa5 0xe5 0xf1 0x71 0xd8 0x31 0x15
    0x04 0xc7 0x23 0xc3 0x18 0x96 0x05 0x9a 0x07 0x12 0x80 0xe2 0xeb 0x27 0xb2 0x75
    0x09 0x83 0x2c 0x1a 0x1b 0x6e 0x5a 0xa0 0x52 0x3b 0xd6 0xb3 0x29 0xe3 0x2f 0x84
    0x53 0xd1 0x00 0xed 0x20 0xfc 0xb1 0x5b 0x6a 0xcb 0xbe 0x39 0x4a 0x4c 0x58 0xcf
    0xd0 0xef 0xaa 0xfb 0x43 0x4d 0x33 0x85 0x45 0xf9 0x02 0x7f 0x50 0x3c 0x9f 0xa8
    0x51 0xa3 0x40 0x8f 0x92 0x9d 0x38 0xf5 0xbc 0xb6 0xda 0x21 0x10 0xff 0xf3 0xd2
    0xcd 0x0c 0x13 0xec 0x5f 0x97 0x44 0x17 0xc4 0xa7 0x7e 0x3d 0x64 0x5d 0x19 0x73
    0x60 0x81 0x4f 0xdc 0x22 0x2a 0x90 0x88 0x46 0xee 0xb8 0x14 0xde 0x5e 0x0b 0xdb
    0xe0 0x32 0x3a 0x0a 0x49 0x06 0x24 0x5c 0xc2 0xd3 0xac 0x62 0x91 0x95 0xe4 0x79
    0xe7 0xc8 0x37 0x6d 0x8d 0xd5 0x4e 0xa9 0x6c 0x56 0xf4 0xea 0x65 0x7a 0xae 0x08
    0xba 0x78 0x25 0x2e 0x1c 0xa6 0xb4 0xc6 0xe8 0xdd 0x74 0x1f 0x4b 0xbd 0x8b 0x8a
    0x70 0x3e 0xb5 0x66 0x48 0x03 0xf6 0x0e 0x61 0x35 0x57 0xb9 0x86 0xc1 0x1d 0x9e
    0xe1 0xf8 0x98 0x11 0x69 0xd9 0x8e 0x94 0x9b 0x1e 0x87 0xe9 0xce 0x55 0x28 0xdf
    0x8c 0xa1 0x89 0x0d 0xbf 0xe6 0x42 0x68 0x41 0x99 0x2d 0x0f 0xb0 0x54 0xbb 0x16
}

# rCon == Round Constant (key expansion) 
set rCon { 
    {0x00 0x00 0x00 0x00}
    {0x01 0x00 0x00 0x00}
    {0x02 0x00 0x00 0x00}
    {0x04 0x00 0x00 0x00}
    {0x08 0x00 0x00 0x00}
    {0x10 0x00 0x00 0x00}
    {0x20 0x00 0x00 0x00}
    {0x40 0x00 0x00 0x00}
    {0x80 0x00 0x00 0x00}
    {0x1b 0x00 0x00 0x00}
    {0x36 0x00 0x00 0x00}
}

proc cipher {input w} {
    set Nb 4
    set Nr [- [/ [llength $w] $Nb] 1]    
    set state [lrepeat 4 [lrepeat 4 0]]
    for {set i 0} {$i < [* $Nb 4]} {incr i} {
        lset state [% $i 4] [int [floor [/ $i 4.0]]] [lindex $input $i]
    }
    set state [addRoundKey $state $w 0 $Nb]    
    for {set round 1} {$round < $Nr} {incr round} {
        set state [subBytes $state $Nb]
        set state [shiftRows $state $Nb]
        set state [mixColumns $state $Nb]
        set state [addRoundKey $state $w $round $Nb]
    }   
    set state [subBytes $state $Nb]
    set state [shiftRows $state $Nb]
    set state [addRoundKey $state $w $Nr $Nb]
    
    set output [lrepeat [* 4 $Nb] 0]
    for {set i 0} {$i < [* 4 $Nb]} {incr i} {
        lset output $i [lindex $state [% $i 4] [int [floor [/ $i 4.0]]]]
    }
    return $output
}

proc keyExpansion {key} {
    set Nb 4
    set Nk [/ [llength $key] 4] ;# 4,6,8 for 128,192,256B key
    set Nr [+ $Nk 6]  
    set w [lrepeat [* $Nb [+ $Nr 1]] 0]
    set temp [lrepeat 4 0]
    
    for {set i 0} {$i < $Nk} {incr i} {
        set i4 [* $i 4]
        set r [list [lindex $key $i4] [lindex $key [+ $i4 1]] \
                    [lindex $key [+ $i4 2]] [lindex $key [+ $i4 3]]]
        lset w $i $r
    }   
    for {set i $Nk} {$i < [* $Nb [+ $Nr 1]]} {incr i} {
        lset w $i [lrepeat 4]
        
        for {set t 0} {$t < 4} {incr t} {
            lset temp $t [lindex $w [- $i 1] $t]
        }        
        if {$i % $Nk == 0} {
            set temp [subWord [rotWord $temp]]
            for {set t 0} {$t < 4} {incr t} {
                lset temp $t [^ [lindex $temp $t] [lindex $::rCon [/ $i $Nk] $t]]
            }
        } elseif {$Nk > 6 && $i % $Nk == 4} {
            set temp [subWord $temp]
        }      
        for {set t 0} {$t < 4} {incr t} {
            lset w $i $t [^ [lindex $w [- $i $Nk] $t] [lindex $temp $t]]
        }
    }
    return $w
}

proc subBytes {s Nb} {
    for {set r 0} {$r < 4} {incr r} {
        for {set c 0} {$c < $Nb} {incr c} {
            lset s $r $c [lindex $::sBox [lindex $s $r $c]]
        }
    }
    return $s
}

proc shiftRows {s Nb} {
    set t [lrepeat 4 0]
    for {set r 1} {$r < 4} {incr r} {
        for {set c 0} {$c < 4} {incr c} {
            lset t $c [lindex $s $r [% [+ $c $r] $Nb]]
        }
        for {set c 0} {$c < 4} {incr c} {
            lset s $r $c [lindex $t $c]
        }
    }
    return $s
}

proc mixColumns {s Nb} {
    for {set c 0} {$c < 4} {incr c} {
        set a [lrepeat 4 0]
        set b [lrepeat 4 0]
        for {set i 0} {$i < 4} {incr i} {
            set ndx_i_c [lindex $s $i $c]
            lset a $i $ndx_i_c
            set ndx_L1 [<< $ndx_i_c 1]
            lset b $i [expr {[& $ndx_i_c 0x80] ? [^ $ndx_L1 0x011b] : 
                                                 $ndx_L1}]
        }        
        lset s 0 $c [^ [lindex $b 0] [lindex $a 1] [lindex $b 1] [lindex $a 2] [lindex $a 3] ]
        lset s 1 $c [^ [lindex $a 0] [lindex $b 1] [lindex $a 2] [lindex $b 2] [lindex $a 3] ]
        lset s 2 $c [^ [lindex $a 0] [lindex $a 1] [lindex $b 2] [lindex $a 3] [lindex $b 3] ]
        lset s 3 $c [^ [lindex $a 0] [lindex $b 0] [lindex $a 1] [lindex $a 2] [lindex $b 3] ]
    }
    return $s
}

## state is list of 4 lists of 4 elem: {{r0c0 r0c1 ...} {r1c0 ...} ...}
proc addRoundKey {state w rnd Nb} {
    for {set r 0} {$r < 4} {incr r} {
        for {set c 0} {$c < $Nb} {incr c} {
            ## state[r][c] ^= w[rnd*4+c][r]
            lset state $r $c [^ [lindex $state $r $c] \
                                [lindex $w [+ [* $rnd 4] $c] $r]]
        }
    }
    return $state
}

# Apply SBox to 4-byte word w4
proc subWord {w4} {
    for {set i 0} {$i < 4} {incr i} {
        lset w4 $i [lindex $::sBox [lindex $w4 $i]];
    }
    return $w4
}

proc rotWord {w4} {
    set tmp [lindex $w4 0]
    for {set i 0} {$i < 3} {incr i} {
        lset w4 $i [lindex $w4 [+ $i 1]]
    }
    lset w4 3 $tmp
    return $w4
}

proc str->bytes {str {keysz 0}} {
    set keysz [expr {!$keysz ? [string length $str] : $keysz}] 
    concat [lmap c [lrange [split $str ""] 0 $keysz-1] {
        scan $c %c
    }] [expr {$keysz > [string length $str] ?
           [lrepeat [- $keysz [string length $str]] 0] : {} }]
}

proc encrypt {plaintxt passwd nBits} {
    set blockSize 16
    if {[ni $nBits {128 192 256}]} {
        return ""
    }
    set plain [encoding convertto utf-8 $plaintxt]
    set pw [encoding convertto utf-8 $passwd]    
    set nBytes [/ $nBits 8]
    set pwBytes [str->bytes $pw $nBytes]
    
    set key [cipher $pwBytes [keyExpansion $pwBytes]]
    lappend key {*}[lrange $key 0 [- $nBytes 16]]
    
    set counterBlock [lrepeat $blockSize 0]   
    set nonce [clock milliseconds]
    set nonceMs [% $nonce 1000]
    set nonceSec [int [/ $nonce 1000]]
    set nonceRnd [int [* [rand] 0xffff]]
    
    for {set i 0} {$i < 2} {incr i} {
        lset counterBlock $i [& [>> $nonceMs [* $i 8]] 0xff]
    }
    for {set i 0} {$i < 2} {incr i} {
        lset counterBlock [+ $i 2] [& [>> $nonceRnd [* $i 8]] 0xff]
    }
    for {set i 0} {$i < 4} {incr i} {
        lset counterBlock [+ $i 4] [& [>> $nonceSec [* $i 8]] 0xff]
    }
    
    ## save 1st 8 bytes of counterBlock as text--used in output
    set ctrTxt [join [lmap x [lrange $counterBlock 0 7] {
        format %c $x
    }] ""]  
    set keySchedule [keyExpansion $key]    
    set blockCount [int [ceil [/ [double [string length $plain]] $blockSize]]]
    set ciphertxt [lrepeat $blockCount 0]
    
    for {set b 0} {$b < $blockCount} {incr b} {
        for {set c 0} {$c < 4} {incr c} {
            lset counterBlock [- 15 $c] [& [>> $b [* $c 8]] 0xff]
        }
        for {set c 0} {$c < 4} {incr c} {
            lset counterBlock [- 15 $c 4] [>> [/ $b 0x100000000] [* $c 8]]
        }      
        set cipherCntr [cipher $counterBlock $keySchedule]        
        set blockLength [expr {$b < ($blockCount - 1) ? $blockSize - 1 :
                    (([string length $plain] - 1) % $blockSize)}]       
        set st [* $b $blockSize] ;# start of plaintext segment
        
        ## xor chars from plaintext segment and cipherCntr  
        set cipherChar [
          lmap p [split [string range $plain $st $st+$blockLength] ""] \
               ciph [lrange $cipherCntr 0 $blockLength] {
            format %c [^ $ciph [scan $p %c]]
        }]   
        lset ciphertxt $b [join $cipherChar ""]
    }   
    ## prepend saved counterBlock text, needed for decryption
    binary encode base64 [string cat $ctrTxt [join $ciphertxt ""]]
}
          
proc decrypt {ciphertext passwd nBits} {
    set blockSize 16
    if {[ni $nBits {128 192 256}]} {
        return ""
    }   
    set ciphertext [binary decode base64 $ciphertext]
    set pw [encoding convertto utf-8 $passwd]    
    set nBytes [/ $nBits 8]
    set pwBytes [str->bytes $pw $nBytes]
    
    set key [cipher $pwBytes [keyExpansion $pwBytes]]
    lappend key {*}[lrange $key 0 [- $nBytes 16]]
    
    set ctrTxt [string range $ciphertext 0 8]
    set counterBlock [lrepeat 16 0]
    for {set i 0} {$i < 8} {incr i} {
        lset counterBlock $i [scan [string index $ctrTxt $i] %c]
    } 
    set keySchedule [keyExpansion $key]
    
    ## re: ceil: using 8.0 to make sure result is double
    set nBlocks [int [ceil [/ [- [string length $ciphertext] 8.0] \
                              $blockSize]]]                         
    set ct [lrepeat $nBlocks 0]
    for {set b 0} {$b < $nBlocks} {incr b} {
        set pos [+ 8 [* $b $blockSize]]
        lset ct $b [string range $ciphertext $pos [+ $pos $blockSize -1]]
    }    
    set ciphertext $ct
    set plaintxt [lrepeat [llength $ciphertext] 0]
    
    for {set b 0} {$b < $nBlocks} {incr b} {
        for {set c 0} {$c < 4} {incr c} {
            lset counterBlock [- 15 $c] [& [>> $b [* $c 8]] 0xff]
        }
        for {set c 0} {$c < 4} {incr c} {
            lset counterBlock [- 15 $c 4] \
              [& 0xff [>> [- [int [ceil [/ [+ $b 1.0] 0x100000000]]] 1] \
                          [* $c 8]]]
            # This [expr ...] is equiv to the above prefix format.  
            # AFAICT performance is about the same. (Expected expr to
            # be faster--seems it isn't.)
            # [expr {
            #     ((int(ceil(($b+1.0)/0x100000000))-1) >> $c*8) & 0xff
            # }]
        }
        set cipherCntr [cipher $counterBlock $keySchedule]
        set ctstr [lindex $ciphertext $b] ;# <= 16 bytes
                    
        set plaintxtByte [lmap \
                ciph [lrange $cipherCntr 0 [string length $ctstr]-1] \
                t [str->bytes $ctstr ] {
            format %c [^ $ciph $t]
        }]
        lset plaintxt $b [join $plaintxtByte ""]
    }
    encoding convertfrom utf-8 [join $plaintxt ""]    
}