Skip to content

Instantly share code, notes, and snippets.

@bertrand-lupart
Created July 9, 2019 16:02
Show Gist options
  • Save bertrand-lupart/bb2ff9fcf369b9bdc31e10c2a1eadd0e to your computer and use it in GitHub Desktop.
Save bertrand-lupart/bb2ff9fcf369b9bdc31e10c2a1eadd0e to your computer and use it in GitHub Desktop.
Simple symmetric encryption / decryption using AES CBC, pre-shared 16 bytes key and random 16 bytes initialisation vector
#!/usr/bin/pike
// Pre-shared key. Should be 16 bytes, kept secret
string key = "secret16byteskey";
// Message to encode
string msg_from = "What's your name, James?";
// Initialisation vector. Should be 16 bytes, randomly generated for each iteration
string iv = random_string(16);
int main(int argc, array(string) argv)
{
write("iv : %O\nkey : %O\nmsg : %O\n", iv, key, msg_from);
// encrypt
object encrypter = Crypto.Buffer(Crypto.CBC(Crypto.AES)->set_iv(iv));
encrypter->set_encrypt_key(key);
string cipher_raw = encrypter->crypt(msg_from);
cipher_raw += encrypter->pad();
write("raw : %O\n", cipher_raw);
write("hex : %O\n", String.string2hex(cipher_raw));
write("b64 : %O\n", MIME.encode_base64(cipher_raw));
//decrypt
object decrypter = Crypto.Buffer(Crypto.CBC(Crypto.AES)->set_iv(iv));
decrypter->set_decrypt_key(key);
string msg_to = decrypter->unpad(cipher_raw);
write("msg : %O\n", msg_to);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment