Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Encryption.nim
- import nimcrypto
- import nimcrypto/sysrand
- var buf: array[8, byte] = [byte 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41]
- when isMainModule:
- var
- data = buf
- envkey: string = "RANDOMKEY"
- ectx, dctx: CTR[aes256]
- key: array[aes256.sizeKey, byte]
- iv: array[aes256.sizeBlock, byte]
- plaintext = newSeq[byte](len(data))
- enctext = newSeq[byte](len(data))
- dectext = newSeq[byte](len(data))
- # create random iv
- discard randomBytes(addr iv[0], 16)
- # do not need to pad data, CTR mode works byte by byte
- copyMem(addr plaintext[0], addr data[0], len(data))
- # expand key to 32 bytes using sha256 as the kdf
- var expandedKey = sha256.digest(envkey)
- copyMem(addr key[0], addr expandedKey.data[0], len(expandedKey.data))
- # create encryption context
- ectx.init(key, iv)
- ectx.encrypt(plaintext, enctext)
- ectx.clear()
- dctx.init(key, iv)
- dctx.decrypt(enctext, dectext)
- dctx.clear()
- echo "IV: ", iv
- echo "KEY: ", key
- echo "ENCRYPTED TEXT: ", enctext
- echo "DECRYPTED TEXT: ", dectext
- # OUTPUT:
- IV: [231, 153, 185, 13, 155, 130, 79, 45, 19, 111, 11, 28, 250, 5, 52, 252]
- KEY: [246, 215, 109, 82, 228, 30, 121, 45, 105, 211, 137, 142, 245, 112, 196, 97, 55, 90, 240, 2, 53, 192, 167, 177, 149, 204, 89, 124, 45, 145, 200, 91]
- ENCRYPTED TEXT: @[130, 65, 75, 33, 31, 237, 85, 32]
- DECRYPTED TEXT: @[65, 65, 65, 65, 65, 65, 65, 65]
- # Decryption.nim
- when isMainModule:
- var data = [130, 65, 75, 33, 31, 237, 85, 32]
- var key = [246, 215, 109, 82, 228, 30, 121, 45, 105, 211, 137, 142, 245, 112, 196, 97, 55, 90, 240, 2, 53, 192, 167, 177, 149, 204, 89, 124, 45, 145, 200, 91]
- var iv = [231, 153, 185, 13, 155, 130, 79, 45, 19, 111, 11, 28, 250, 5, 52, 252]
- var
- ectx, dctx: CTR[aes256]
- enctext = newSeq[byte](len(data))
- dectext = newSeq[byte](len(data))
- # copy data to enctext
- copyMem(addr enctext[0], addr data[0], len(data))
- # convert key int array to byte array
- var keyB: array[key.len, byte]
- for i in low(key) .. high(key):
- keyB[i] = key[i].byte
- # convert iv int array to byte array
- var ivB: array[iv.len, byte]
- for i in low(iv) .. high(iv):
- ivB[i] = iv[i].byte
- ectx.init(keyB, ivB)
- ectx.clear()
- dctx.init(keyB, ivB)
- dctx.decrypt(enctext, dectext)
- dctx.clear()
- var out: array[data.len, byte]
- for i in low(dectext) .. high(dectext):
- sc[i] = dectext[i].byte
- echo out
- # OUTPUT
- [65, 0, 10, 96, 94, 172, 20, 97]
Advertisement
Add Comment
Please, Sign In to add comment