Created
February 17, 2015 07:49
-
-
Save hashbrowncipher/bc1c5e1a85f9bd056a35 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#include <fcntl.h> | |
#include <openssl/conf.h> | |
#include <openssl/evp.h> | |
#include <openssl/err.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <unistd.h> | |
#define BLOCK_SIZE 1024 * 1024 | |
void os_error(const char * msg, char code) { | |
perror(msg); | |
exit(code); | |
} | |
void handleErrors(void) | |
{ | |
ERR_print_errors_fp(stderr); | |
abort(); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
unsigned char key[16]; | |
unsigned char iv[16]; | |
if (argc < 2) { | |
fprintf(stderr, "Usage: %s <keyfile>\n", argv[0]); | |
exit(1); | |
} | |
int keyfd = open(argv[1], O_RDONLY); | |
if (keyfd < 0) { | |
os_error("Failed to open keyfile", 2); | |
} | |
int key_read_bytes = read(keyfd, &key, 16); | |
if (key_read_bytes != 16) { | |
os_error("Failed to read key", 4); | |
} | |
int iv_read_bytes = read(keyfd, &iv, 16); | |
if (iv_read_bytes != 16) { | |
os_error("Failed to read IV", 4); | |
} | |
unsigned char * plaintext = malloc(BLOCK_SIZE); | |
unsigned char * ciphertext = malloc(BLOCK_SIZE); | |
/* Initialise the library */ | |
ERR_load_crypto_strings(); | |
OpenSSL_add_all_algorithms(); | |
OPENSSL_config(NULL); | |
/* Create and initialise the context */ | |
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); | |
if(!ctx) { | |
handleErrors(); | |
} | |
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_128_ctr(), NULL, key, iv)) { | |
handleErrors(); | |
} | |
while(1) { | |
int plaintext_len = read(STDIN_FILENO, plaintext, BLOCK_SIZE); | |
if (plaintext_len < 0) { | |
os_error("Failed reading input", 4); | |
} | |
else if (plaintext_len == 0) { | |
break; | |
} | |
int ciphertext_len; | |
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &ciphertext_len, plaintext, plaintext_len)) { | |
handleErrors(); | |
} | |
int write_len = write(STDOUT_FILENO, ciphertext, ciphertext_len); | |
if(write_len != ciphertext_len) { | |
os_error("Failed writing output", 4); | |
} | |
} | |
/* We don't call finalize, because we're using a stream cipher */ | |
/* Clean up */ | |
EVP_CIPHER_CTX_free(ctx); | |
EVP_cleanup(); | |
ERR_free_strings(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment