Pull out openssl code into separate crypto-openssl.cpp file

This will allow the use of different crypto libraries in the future.

Modified-by: Andrew Ayer <agwa@andrewayer.name>

  * Don't include openssl/err.h from git-crypt.cpp
  * Fix whitespace and other style to conform to project conventions
  * Remove unnecessary operators from Aes_ctr_encryptor
  * Rename crypto_init to init_crypto, for consistency with init_std_streams()
This commit is contained in:
Jon Sailor
2014-07-06 02:33:35 -07:00
committed by Andrew Ayer
parent f6e3b63a93
commit 66a2266968
5 changed files with 154 additions and 59 deletions

View File

@@ -30,22 +30,11 @@
#include "crypto.hpp"
#include "util.hpp"
#include <openssl/aes.h>
#include <openssl/sha.h>
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <sstream>
#include <cstring>
#include <cstdlib>
Aes_ctr_encryptor::Aes_ctr_encryptor (const unsigned char* raw_key, const unsigned char* arg_nonce)
: ecb(raw_key)
{
if (AES_set_encrypt_key(raw_key, KEY_LEN * 8, &key) != 0) {
throw Crypto_error("Aes_ctr_encryptor::Aes_ctr_encryptor", "AES_set_encrypt_key failed");
}
std::memcpy(nonce, arg_nonce, NONCE_LEN);
byte_counter = 0;
std::memset(otp, '\0', sizeof(otp));
@@ -64,7 +53,7 @@ void Aes_ctr_encryptor::process (const unsigned char* in, unsigned char* out, si
store_be32(ctr + NONCE_LEN, byte_counter / BLOCK_LEN);
// Generate a new OTP
AES_encrypt(ctr, otp, &key);
ecb.encrypt(ctr, otp);
}
// encrypt one byte
@@ -76,28 +65,6 @@ void Aes_ctr_encryptor::process (const unsigned char* in, unsigned char* out, si
}
}
Hmac_sha1_state::Hmac_sha1_state (const unsigned char* key, size_t key_len)
{
HMAC_Init(&ctx, key, key_len, EVP_sha1());
}
Hmac_sha1_state::~Hmac_sha1_state ()
{
HMAC_cleanup(&ctx);
}
void Hmac_sha1_state::add (const unsigned char* buffer, size_t buffer_len)
{
HMAC_Update(&ctx, buffer, buffer_len);
}
void Hmac_sha1_state::get (unsigned char* digest)
{
unsigned int len;
HMAC_Final(&ctx, digest, &len);
}
// Encrypt/decrypt an entire input stream, writing to the given output stream
void Aes_ctr_encryptor::process_stream (std::istream& in, std::ostream& out, const unsigned char* key, const unsigned char* nonce)
{
@@ -111,16 +78,3 @@ void Aes_ctr_encryptor::process_stream (std::istream& in, std::ostream& out, con
}
}
void random_bytes (unsigned char* buffer, size_t len)
{
if (RAND_bytes(buffer, len) != 1) {
std::ostringstream message;
while (unsigned long code = ERR_get_error()) {
char error_string[120];
ERR_error_string_n(code, error_string, sizeof(error_string));
message << "OpenSSL Error: " << error_string << "; ";
}
throw Crypto_error("random_bytes", message.str());
}
}