I tried with this code but the result is not as expected, maybe I am wrong somewhere, please help.
gcrypt.vapi from: https://gitlab.gnome.org/GNOME/vala-extra-vapis
using GCrypt;
using Posix;
void main () {
GCrypt.Cipher.Cipher cipher;
GCrypt.Error err = GCrypt.Cipher.Cipher.open(out cipher, Cipher.Algorithm.AES128, Cipher.Mode.CBC, Cipher.Flag.SECURE);
if (err != 0) {
print("Error: %s\n", err.to_string());
Process.exit(EXIT_FAILURE);
}
string iv = "1111111111111111";
string key = "2222222222222222";
err = cipher.set_key(key.data);
if (err != 0) {
print("Error key: %s\n", err.to_string());
Process.exit(EXIT_FAILURE);
}
err = cipher.set_iv(iv.data);
if (err != 0) {
print("Error iv: %s\n", err.to_string());
Process.exit(EXIT_FAILURE);
}
string str = "Hello World!!!!!";
uchar[] ary = new uchar[str.length];
print("ary: %d\n", ary.length);
err = cipher.encrypt(ary, str.data);
if (err != 0) {
print("Error encrypt: %s\n", err.to_string());
Process.exit(EXIT_FAILURE);
}
string result = Base64.encode(ary);
print("ary: %d\n", ary.length);
print("result: %s\n", result); // tus0150r+OSFg63kxluXpg==
// expect result: tus0150r+OSFg63kxluXpmlrUQOsLMbbgx51GhLZats=
cipher.close();
Process.exit(EXIT_SUCCESS);
}
Your output buffer
aryis sized too small so you're losing data.You can't assume that the encrypted output will be the same size as the input data:Edit: I was incorrect, since AES is a block cipher the size will be the same, however the padding scheme must be considered
Here's an example of creating an output buffer of the correct size (granted it's for AES256, not AES128, so you'll need to make some adjustment): https://github.com/JCWasmx86/LFinance/blob/e6057b38a594ecbef728b212d9aa7df8cd8e869b/src/crypto/encryption.vala
That code has a link out to another Stack Overflow post about determining the correct size: Size of data after AES/CBC and AES/ECB encryption
Unfortunately I don't know enough about AES to provide the exact size that you'll need, but hopefully this gets you going in the right direction!