├── README.md ├── strenc.nimble └── src └── strenc.nim /README.md: -------------------------------------------------------------------------------- 1 | # nim-strenc 2 | string encryption in Nim 3 | -------------------------------------------------------------------------------- /strenc.nimble: -------------------------------------------------------------------------------- 1 | # Package 2 | version = "0.0.1" 3 | author = "Original author removed the code" 4 | description = "A library to automatically encrypt all string constants in your programs" 5 | license = "MIT" 6 | srcDir = "src" 7 | 8 | # Dependencies 9 | requires "nim >= 1.0.0" 10 | -------------------------------------------------------------------------------- /src/strenc.nim: -------------------------------------------------------------------------------- 1 | # Code is based on https://forum.nim-lang.org/t/1305 2 | # and https://forum.nim-lang.org/t/338 3 | import macros, hashes 4 | 5 | type 6 | # Use a distinct string type so we won't recurse forever 7 | estring = distinct string 8 | 9 | # Use a "strange" name 10 | proc gkkaekgaEE(s: estring, key: int): string {.noinline.} = 11 | # We need {.noinline.} here because otherwise C compiler 12 | # aggresively inlines this procedure for EACH string which results 13 | # in more assembly instructions 14 | var k = key 15 | result = string(s) 16 | for i in 0 ..< result.len: 17 | for f in [0, 8, 16, 24]: 18 | result[i] = chr(uint8(result[i]) xor uint8((k shr f) and 0xFF)) 19 | k = k +% 1 20 | 21 | var encodedCounter {.compileTime.} = hash(CompileTime & CompileDate) and 0x7FFFFFFF 22 | 23 | # Use a term-rewriting macro to change all string literals 24 | macro encrypt*{s}(s: string{lit}): untyped = 25 | var encodedStr = gkkaekgaEE(estring($s), encodedCounter) 26 | 27 | template genStuff(str, counter: untyped): untyped = 28 | {.noRewrite.}: 29 | gkkaekgaEE(estring(`str`), `counter`) 30 | 31 | result = getAst(genStuff(encodedStr, encodedCounter)) 32 | encodedCounter = (encodedCounter *% 16777619) and 0x7FFFFFFF 33 | --------------------------------------------------------------------------------