-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnimCrypter.nim
88 lines (65 loc) · 2.36 KB
/
nimCrypter.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import nimcrypto
import nimcrypto/sysrand
import base64
import os
import strformat
import strutils
import std/parseopt # option parser
const iv: array[aes256.sizeBlock, byte]= [byte 148, 181, 90, 151, 26, 242, 253, 114, 7, 217, 24, 204, 125, 203, 26, 167]
const envkey: string = "verysecretpass"
var version="1.6"
func toByteSeq*(str: string): seq[byte] {.inline.} =
# Converts a string to the corresponding byte sequence
@(str.toOpenArrayByte(0, str.high))
when isMainModule:
var inFile: string =""
var operation: string = ""
var passkeystr:string=envkey# default key to our constant
var helpMsg: string="nimCrypter.exe [-d|-e] [-k] file.txt" # help msg
var debug: bool=false # to enable/disable debug mode
# OUR OPTION PARSER
var parser = initOptParser()
while true:
parser.next()
case parser.kind
of cmdEnd:
break
of cmdShortOption, cmdLongOption:
if parser.val == "": #just options "-x"
if parser.key=="d": # decrypt option
operation="decrypt"
if parser.key=="e": # encrypt option
operation="encrypt"
elif parser.key=="D": # debug option
debug=true
elif parser.key=="h": # help option
echo helpMsg
quit(QuitSuccess)
else: # have value
if parser.key=="k": # key option
passkeystr=parser.val
of cmdArgument:
inFile=parser.key # argument input file
if inFile=="" or operation=="":
quit()
let inFileContents: string = readFile(inFile)
var
data: seq[byte] = toByteSeq(inFileContents)
ectx: CTR[aes256]
key: array[aes256.sizeKey, byte]
plaintext = newSeq[byte](len(data))
transformedText = newSeq[byte](len(data))
copyMem(addr plaintext[0], addr data[0], len(data))
# Expand key to 32 bytes using SHA256 as the KDF
var expandedkey = sha256.digest(passkeystr)
copyMem(addr key[0], addr expandedkey.data[0], len(expandedkey.data))
ectx.init(key, iv)
if operation=="encrypt":
ectx.encrypt(plaintext, transformedText)
writeFile(inFile&"_enc.txt", transformedText)
elif operation=="decrypt":
ectx.decrypt(plaintext, transformedText)
writeFile(inFile&"_dec.txt", transformedText)
else:
ectx.clear()
system.quit()