Does anyone have example encryption/decryption functions that I can explore please? Not looking for NSA-proof protection, but a nice way to secure well a string based on a password I enter, and then to be able to decrypt that string by providing the same password on a different computer/OS using XOJO.
The strings will never be more than 32kb in total size, and likely around 5kb at the most.
I am trying to understand the documentation but not getting very far. Also, as I am learning, I would rather not import some huge class or library for this!
You will need a key of 32 or 64 bytes, and ideally an Initialization Vector.
You should keep the password separate but the IV can be stored alongside the encrypted text, however you want to do that.
Here is some sample code:
var pw as string = "MyPassword"
var key as string = Crypto.SHA2_256( pw ) // Will trigger AES 256
var iv as MemoryBlock = Crypto.GenerateRandomBytes( 16 )
var data as string = "something to encrypt"
var encrypted as string = Crypto.AESEncrypt( key, data, Crypto.BlockModes.CBC, iv )
var storeEncrypted as string = EncodeHex( encrypted )
var storeIV as string = EncodeHex( iv )
// You can store these, and later...
encrypted = DecodeHex( storeEncrypted )
iv = DecodeHex( storeIV )
var decrypted as string = Crypto.AESDecrypt( key, encrypted, Crypto.BlockModes.CBC, iv )
2 Likes
Thanks for the quick reply! I have tried putting this into a function:
var pw as string = "12345"
var key as string = Crypto.SHA2_256( pw ) // Will trigger AES 256
var iv as MemoryBlock = Crypto.GenerateRandomBytes( 16 )
//var data as string = RawText
var encrypted as string = Crypto.AESEncrypt( key, RawText, Crypto.BlockModes.CBC, iv )
Return EncodeHex( encrypted )
Is this correct? And what did you mean in your code about storing the IV for later?
The Initial Vector (IV) is used to “scramble” the data before encryption. It changes the bytes of the first block encrypts that, then uses that block to change the bytes of the second block, and so on. Every time you encrypt, you should choose a new IV so there is no way to tell if two encrypted strings are actually the same.
To decrypt, you will need to use the same IV used to encrypt so you should store it alongside the encrypted string.
I gave a talk on this at XDC that outlines the basics of encryption. It might be worth a look:
8 Likes
thank you, this is perfect!
1 Like