Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // aes.d
- // Grabbed these bindings from Deimos
- module aes;
- enum AES_ENCRYPT = 1;
- enum AES_DECRYPT = 0;
- enum AES_MAXNR = 14;
- enum AES_BLOCK_SIZE = 16;
- extern (C):
- struct aes_key_st
- {
- version (AES_LONG)
- {
- c_ulong[4* (AES_MAXNR + 1)] rd_key;
- }
- else
- {
- uint[4* (AES_MAXNR + 1)] rd_key;
- }
- int rounds;
- };
- alias aes_key_st AES_KEY;
- int AES_set_encrypt_key(const(ubyte)* userKey, const int bits, AES_KEY* key);
- int AES_set_decrypt_key(const(ubyte)* userKey, const int bits, AES_KEY* key);
- void AES_ecb_encrypt(const(ubyte)* in_, ubyte* out_, const(AES_KEY)* key, const int enc);
- // encrypt.d
- // compile with dmd -ofencrypt -L-lssl -L-lcrypto encrypt.d aes.d
- import std.stdio;
- void usage()
- {
- writeln("Usage: encrypt [options] string");
- writeln("Options:");
- writeln("-e, --encrypt Encrypt string");
- writeln("-d, --decrypt Decrypt string");
- writeln("-h, --help Display this help");
- writeln("\nEither --encrypt or --decrypt must be specified, but not both");
- }
- // Kill the program
- void end()
- {
- import core.runtime: Runtime;
- import core.stdc.stdlib: exit;
- Runtime.terminate();
- exit(1);
- }
- void main(string[] args)
- {
- import std.getopt;
- import std.string;
- import std.digest.sha;
- import std.conv;
- import std.base64;
- import aes;
- bool encrypt, decrypt, help;
- getopt(args, config.passThrough, "e|encrypt", &encrypt, "d|decrypt", &decrypt, "h|help", &help);
- // Check command line options
- if(args.length != 2 || help || !(encrypt ^ decrypt))
- {
- usage();
- end();
- }
- // The string to be encrypted needs to be converted to an array of ubytes
- ubyte[] inputStr = cast(ubyte[]) args[1];
- // Get password, which is used as the 128-bit key
- write("Password: ");
- ubyte[16] aesKey = readln.chomp.sha256Of.halve();
- if(encrypt)
- {
- AES_KEY encKey;
- auto encOut = new ubyte[inputStr.length];
- // Encrypt and convert to base64
- AES_set_encrypt_key(aesKey.ptr, aesKey.sizeof * 8, &encKey);
- AES_ecb_encrypt(inputStr.ptr, encOut.ptr, &encKey, AES_ENCRYPT);
- writeln(Base64.encode(encOut));
- }
- else
- {
- auto decLength = Base64.decodeLength(inputStr.length);
- AES_KEY decKey;
- auto decB64 = new ubyte[decLength], decOut = new ubyte[decLength];
- // convert back from base64 and decrypt
- decB64 = Base64.decode(inputStr);
- AES_set_decrypt_key(aesKey.ptr, aesKey.sizeof * 8, &decKey);
- AES_ecb_encrypt(decB64.ptr, decOut.ptr, &decKey, AES_DECRYPT);
- writeln(cast(char[]) decOut);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement