Last active
August 29, 2015 14:02
-
-
Save sinkuu/a7663481e26580308f82 to your computer and use it in GitHub Desktop.
Using Deimos OpenSSL binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio; | |
import std.exception : enforce; | |
import deimos.openssl.aes; | |
import deimos.openssl.rand; | |
void main() | |
{ | |
auto message = randBytes(100); | |
writeln(message); | |
AES_KEY keyEnc; | |
AES_KEY keyDec; | |
auto userKey = randBytes(32); | |
AES_set_encrypt_key(userKey.ptr, 256, &keyEnc); | |
AES_set_decrypt_key(userKey.ptr, 256, &keyDec); | |
ubyte[AES_BLOCK_SIZE] ivec = randBytes(AES_BLOCK_SIZE); | |
auto ivecOrig = ivec.dup; | |
auto encrypted = new ubyte[](message.length + | |
(message.length % AES_BLOCK_SIZE != 0 | |
? AES_BLOCK_SIZE - (message.length % AES_BLOCK_SIZE) | |
: 0)); | |
AES_cbc_encrypt(message.ptr, encrypted.ptr, message.length, &keyEnc, ivec.ptr, AES_ENCRYPT); | |
auto decrypted = new ubyte[](message.length); | |
AES_cbc_encrypt(encrypted.ptr, decrypted.ptr, message.length, &keyDec, ivecOrig.ptr, AES_DECRYPT); | |
writeln(encrypted); | |
writeln(decrypted); | |
enforce(message == decrypted); | |
} | |
ubyte[] randBytes(int len) { | |
ubyte[] arr; | |
arr.length = len; | |
RAND_bytes(arr.ptr, len); | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment