I'm trying to learn (cryptography) encryption in Nim but it turns out none of the code publicly available on encryption works. I just got bunch of errors. For example here is an example I found. link: https://compile7.org/encryption-decryption/how-to-use-aes-256-to-encrypt-and-decrypt-in-nim/#setting-up-your-nim-environment-for-aes-256
I did manage to get rid of an error but the errors at newAES256(key) and cipher.encrypt remain. Not sure how to fix it. When it comes to hashing (sha-256), I had no errors since there is no reversing. As you know, there is no decryption. I spend lot of time on encryption, but can't find a single source that run the code without errors. Any help is appreciated!
import nimcrypto
# Function to encrypt data
proc encryptData(key: string, plaintext: string): string =
var cipher = newAES256(key)
result = cipher.encrypt(plaintext)
return result
# Example usage
let key = "thisisaverystrongkey1234567890" # 32 bytes for AES-256
let plaintext = "Hello, this is a secret message."
let encryptedData = encryptData(key, plaintext)
echo "Encrypted Data: ", encryptedDataThe tests are always a good place to start - there, you'll find examples of how to encrypt and decrypt.
import nimcrypto
var key = fromHex("c47b0294dbbbee0fec4757f22ffeee3587ca4730c3d33b691df38bab076bc558")
var data: array[aes256.sizeBlock, byte]
data[0] = 1
echo "unencrypted: ", data.toHex()
var ctx: aes256
ctx.init(key)
ctx.encrypt(data, data)
echo "encrypted: ", data.toHex()
ctx.decrypt(data, data)
echo "unencrypted: ", data.toHex()
Note that AES is a block cipher meaning that it is only capable of encrypting messages of a fixed block size - to encrypt arbitrary-length data you pair it with a mode: https://www.geeksforgeeks.org/ethical-hacking/block-cipher-modes-of-operation/ - which mode you choose depends on many things but above all, you have to agree with whoever decrypts it which mode you're using - for example you browser is likely to use AES256-GCM.
Or, if you don't mind using a third party library, you can use the e2ee package, which is a Nim wrapper around the Monocypher lib. So, you will have to stick to the supported algorithms. You will need to link the library by yourself at your project level (statically or dynamically) and then you can use it.
You have C-style API, and Nim-style high-level API that is way easier to use. The high-level API is not perfect but it works! Check the tests and the generated docs for more details.
I have plans to add more features and also support for the crypto_wipe function.
Thanks for reminding me, I made a pull request to nimble packages, so for now you can try it out by installing the pkg using the github url.
Happy to accept contributions and suggestions!