all repos — min @ 48eee1341d8e9a7f6b6f3bbfa98495675d24f672

A small but practical concatenative programming language.

lib/min_crypto.nim

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
import
  md5,
  base64,
  strutils,
  times
import
  ../core/parser, 
  ../core/value, 
  ../core/interpreter, 
  ../core/utils
import
  ../packages/sha1/sha1,
  ../packages/nimSHA2/nimSHA2,
  ../packages/nimAES/nimAES

proc crypto_module*(i: In)=
  let def = i.define()

  def.symbol("md5") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    i.push s.getString.getMD5.newVal

  def.symbol("sha1") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    i.push compute(s.getString).toHex.newVal

  def.symbol("sha224") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    i.push computeSHA224(s.getString).hex.toLowerAscii.newVal

  def.symbol("sha256") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    i.push computeSHA256(s.getString).hex.toLowerAscii.newVal

  def.symbol("sha384") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    i.push computeSHA384(s.getString).hex.toLowerAscii.newVal

  def.symbol("sha512") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    i.push computeSHA512(s.getString).hex.toLowerAscii.newVal

  def.symbol("encode") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    i.push s.getString.encode.newVal
    
  def.symbol("decode") do (i: In):
    let vals = i.expect("'sym")
    let s = vals[0]
    i.push s.getString.decode.newVal

  def.symbol("aes") do (i: In):
    let vals = i.expect("'sym", "'sym")
    let k = vals[0]
    let s = vals[1]
    var ctx: AESContext
    var text = s.getString
    var length = text.len
    if length div 16 == 0:
      text &= " ".repeat(16 - length)
    elif length mod 16 != 0 and length div 16 >= 1:
      text &= " ".repeat((length div 16 + 1) * 16 - length)
    var key = k.getString.compute.toHex # SHA1 of key, to make sure it's long enough
    var nonce = key[0..15]
    i.push ctx.cryptOFB(nonce, text).newVal

  def.finalize("crypto")