diff --git a/src/lib/utils/crypto/AlgoType.h b/src/lib/utils/crypto/AlgoType.h new file mode 100644 index 000000000..0f6680b11 --- /dev/null +++ b/src/lib/utils/crypto/AlgoType.h @@ -0,0 +1,18 @@ +#pragma once + +namespace bts +{ +namespace crypto +{ + +class AlgoType +{ +public: + enum type + { + RSA = 0 + }; +}; + +} +} diff --git a/src/lib/utils/crypto/CipherType.cpp b/src/lib/utils/crypto/CipherType.cpp new file mode 100644 index 000000000..e54cbe7af --- /dev/null +++ b/src/lib/utils/crypto/CipherType.cpp @@ -0,0 +1,12 @@ +#include "CipherType.h" + +namespace bts +{ +namespace crypto +{ + +const char* CipherType::name[] = { "None", "DES-EDE3-CBC", "3des", "idea", "aes128" }; + +} +} + diff --git a/src/lib/utils/crypto/CipherType.h b/src/lib/utils/crypto/CipherType.h new file mode 100644 index 000000000..6447c19b5 --- /dev/null +++ b/src/lib/utils/crypto/CipherType.h @@ -0,0 +1,20 @@ +#pragma once + +namespace bts +{ +namespace crypto +{ + +class CipherType +{ +public: + static const char *name[]; + enum type + { + None = 0, DES = 1, TripleDES = 2, IDEA = 3, AES128 = 4 + }; + +}; + +} +} diff --git a/src/lib/utils/crypto/CryptoInit.cpp b/src/lib/utils/crypto/CryptoInit.cpp new file mode 100644 index 000000000..d1fdd9882 --- /dev/null +++ b/src/lib/utils/crypto/CryptoInit.cpp @@ -0,0 +1,55 @@ +#include "CryptoInit.h" + +#include + +namespace openssl +{ +#include +#include +#include +#include +#include +} + +namespace bts +{ +namespace crypto +{ + +static const char rnd_seed[] = "string to make the random number generator think it has entropy"; +bool CryptoInit::init = false; + +tbb::spin_mutex _lock; + +void CryptoInit::initialize() +{ + if(!init) + { + tbb::spin_mutex::scoped_lock lock(_lock); + if(!init) + { + openssl::OpenSSL_add_all_algorithms(); + openssl::OpenSSL_add_all_ciphers(); + openssl::OpenSSL_add_all_digests(); + openssl::RAND_seed(rnd_seed, sizeof rnd_seed); + init = true; + } + } +} +void CryptoInit::cleanup() +{ + if(init) + { + tbb::spin_mutex::scoped_lock lock(_lock); + if(init) + { + //openssl::EVP_cleanup(); + init = false; + } + } +} + + +} +} + diff --git a/src/lib/utils/crypto/CryptoInit.h b/src/lib/utils/crypto/CryptoInit.h new file mode 100644 index 000000000..06e4c5b1a --- /dev/null +++ b/src/lib/utils/crypto/CryptoInit.h @@ -0,0 +1,20 @@ +#pragma once + +#include "lib/utils/bts_no_copy.h" + +namespace bts +{ +namespace crypto +{ + +struct CryptoInit +{ + BTS_NO_COPY(CryptoInit); + static bool init; + static void initialize(); + static void cleanup(); +}; + +} +} + diff --git a/src/lib/utils/crypto/Digest.cpp b/src/lib/utils/crypto/Digest.cpp new file mode 100644 index 000000000..147fd0c94 --- /dev/null +++ b/src/lib/utils/crypto/Digest.cpp @@ -0,0 +1,66 @@ +#include "Digest.h" + +#include "PrivateKey.h" +#include "lib/utils/bts_assert.h" + +namespace openssl +{ +#include +#include +} + +namespace bts +{ +namespace crypto +{ + +const std::string digest_algo = "sha256"; + +void Digest::allocate_array(unsigned char** out_digest, unsigned int* out_len) +{ + *out_len = EVP_MAX_MD_SIZE; + *out_digest = new unsigned char[*out_len]; + +} + +void Digest::deallocate_array(unsigned char* out_digest) +{ + delete[] out_digest; +} + +void Digest::compute_digest(const unsigned char* data, unsigned long size, unsigned char* out_digest, unsigned int* out_len) +{ + bts_assert(*out_len >= EVP_MAX_MD_SIZE); + const openssl::EVP_MD* md = openssl::EVP_get_digestbyname(digest_algo.c_str()); + bts_assert(md); + + openssl::EVP_MD_CTX* mdctx = openssl::EVP_MD_CTX_create(); + openssl::EVP_DigestInit_ex(mdctx, md, NULL); + openssl::EVP_DigestUpdate(mdctx, data, size); + openssl::EVP_DigestFinal_ex(mdctx, out_digest, out_len); + openssl::EVP_MD_CTX_destroy(mdctx); +} + +void Digest::compute_digest(const std::string& data, std::string* out_digest) +{ + unsigned int len = EVP_MAX_MD_SIZE; + unsigned char ret[EVP_MAX_MD_SIZE]; + char str[EVP_MAX_MD_SIZE+1]; + compute_digest(reinterpret_cast(data.c_str()), data.size(), &ret[0], &len); + for(size_t i = 0; i < len; i++) + sprintf(&str[i*2], "%02x", ret[i]); + std::string val(str, len*2); + *out_digest = val; +} + +std::string Digest::compute_digest(const std::string& data) +{ + std::string ret; + compute_digest(data, &ret); + return ret; +} + + +} +} + diff --git a/src/lib/utils/crypto/Digest.h b/src/lib/utils/crypto/Digest.h new file mode 100644 index 000000000..36cb5aefd --- /dev/null +++ b/src/lib/utils/crypto/Digest.h @@ -0,0 +1,24 @@ +#pragma once + +#include "lib/utils/bts_no_copy.h" + +#include + +namespace bts +{ +namespace crypto +{ + +class Digest +{ +public: + static void allocate_array(unsigned char** out_digest, unsigned int* out_len); + static void deallocate_array(unsigned char* out_digest); + + static void compute_digest(const unsigned char* data, unsigned long size, unsigned char* out_digest, unsigned int* out_len); + static void compute_digest(const std::string& data, std::string* out_digest); + static std::string compute_digest(const std::string& data); +}; + +} +} diff --git a/src/lib/utils/crypto/PasswordCallback.cpp b/src/lib/utils/crypto/PasswordCallback.cpp new file mode 100644 index 000000000..62dfacd03 --- /dev/null +++ b/src/lib/utils/crypto/PasswordCallback.cpp @@ -0,0 +1,63 @@ +#include "PasswordCallback.h" + +#include +#include + +namespace bts +{ +namespace crypto +{ + +PasswordCallback::PasswordCallback() : _callback(0) +{ +} + +PasswordCallback::PasswordCallback(password_callback cb) : _callback(cb) +{ +} + +PasswordCallback::~PasswordCallback() +{ +} + +void PasswordCallback::prompt(const std::string& user_info, std::string& password) +{ + if(user_info == "") + std::cout << "Enter Private Key Passphrase:"; + else + std::cout << "Enter Private Key Passphrase (" + user_info + "): "; + std::cin >> password; +} + +void PasswordCallback::request_password(const std::string& user_info, std::string& password) const +{ + if(_callback) + _callback(user_info, password); + else + { + prompt(user_info, password); + } +} + +CachedPassword::CachedPassword() : _pass() +{ + PasswordCallback::prompt("", _pass); +} + +CachedPassword::CachedPassword(const std::string& pass) : _pass(pass) +{ + if(pass == "") + PasswordCallback::prompt("", _pass); +} + +CachedPassword::~CachedPassword() +{ +} + +void CachedPassword::request_password(const std::string& , std::string& password) const +{ + password = _pass; +} + +} +} diff --git a/src/lib/utils/crypto/PasswordCallback.h b/src/lib/utils/crypto/PasswordCallback.h new file mode 100644 index 000000000..ff85fbb21 --- /dev/null +++ b/src/lib/utils/crypto/PasswordCallback.h @@ -0,0 +1,45 @@ +#pragma once + +#include "lib/utils/bts_no_copy.h" + +#include + +namespace bts +{ +namespace crypto +{ + +class PasswordCallback +{ + BTS_NO_COPY(PasswordCallback); +public: + typedef void password_callback (const std::string& user_info, std::string& password); +public: + PasswordCallback(); + PasswordCallback(password_callback cb); + virtual ~PasswordCallback(); + + static void prompt(const std::string& user_info, std::string& password); + virtual void request_password(const std::string& user_info, std::string& password) const; + + static void prerequest_password(const std::string& user_info, std::string& password); +protected: + password_callback* _callback; +}; + +class CachedPassword : public PasswordCallback +{ + BTS_NO_COPY(CachedPassword); +public: + CachedPassword(); + CachedPassword(const std::string&); + virtual ~CachedPassword(); + virtual void request_password(const std::string& user_info, std::string& password) const; + +protected: + std::string _pass; +}; + + +} +} diff --git a/src/lib/utils/crypto/PrivateKey.cpp b/src/lib/utils/crypto/PrivateKey.cpp new file mode 100644 index 000000000..b9566f91a --- /dev/null +++ b/src/lib/utils/crypto/PrivateKey.cpp @@ -0,0 +1,287 @@ +#include "PrivateKey.h" + +#include "PublicKey.h" +#include "CryptoInit.h" +#include "iostreambio.h" +#include "lib/logging/logging.h" +#include +#include + +namespace openssl +{ +#include +#include +#include +#include +#include +} + +namespace bts +{ +namespace crypto +{ + +struct PrivateKey::Pimp +{ + BTS_NO_COPY(Pimp); + + const PasswordCallback* password; + PasswordCallback default_password; + PublicKeyPtr public_key; + + Pimp(const PasswordCallback* pass) : password(pass), default_password(), public_key() + { + initialize(); + if(!password) + password = &default_password; + } + + ~Pimp() + { + } + static void initialize() + { + CryptoInit::initialize(); + } +}; + +int password_callback(char *buf, int size, int rwflag, void *u) +{ + UNUSED(rwflag); + std::string data; + if(u) + { + PasswordCallback* pwd = reinterpret_cast(u); + pwd->request_password(data, data); + } + else + { + PasswordCallback ddefault; + ddefault.request_password(data, data); + } + int sz = data.size(); + if((int)data.size() > size) + sz = size; + + std::memcpy(buf, data.c_str(), sz); + return sz; +} + +const PublicKeyPtr PrivateKey::public_key() const +{ + if(!me->public_key) + me->public_key = PublicKey::create(*this); + return me->public_key; +} + + +const PrivateKeyPtr PrivateKey::create(int bits, AlgoType::type at, const PasswordCallback* pass) +{ + openssl::EVP_PKEY* key = openssl::EVP_PKEY_new(); + if(at == AlgoType::RSA) + { + openssl::RSA* rsa = openssl::RSA_new(); + openssl::BIGNUM* bn = openssl::BN_new(); + openssl::BN_set_word(bn, RSA_F4); + int keyok = openssl::RSA_generate_key_ex(rsa, bits, bn, 0); + openssl::BN_free(bn); + bts_assert_msg(keyok != -1, "Unable to create key"); + int i = openssl::EVP_PKEY_assign_RSA(key, rsa); + bts_assert_msg(1 == i, "Unable to create key"); + } + else + bts_assert_msg(false, "only support RSA"); + return PrivateKeyPtr(new PrivateKey(key, pass)); +} + + +const PrivateKeyPtr PrivateKey::read_file(const std::string& filename, const PasswordCallback* pass) +{ + PrivateKey::Pimp::initialize(); + PrivateKeyPtr ret; + openssl::BIO* bio = openssl::BIO_new_file(filename.c_str(), "r"); + bts_assert_msg(bio, "can't load keyfile"); + openssl::EVP_PKEY* key = openssl::PEM_read_bio_PrivateKey(bio, 0, password_callback, (void*)pass); + if(!key) + //LOG(Error, Config) << "Invalid private key passphrase"; + else + ret.reset(new PrivateKey(key, pass)); + return ret; +} + +const PrivateKeyPtr PrivateKey::read_stream(const std::istream& stream, const PasswordCallback* pass) +{ + PrivateKey::Pimp::initialize(); + PrivateKeyPtr ret; + const_cast(stream).seekg(0, std::ios::end); + int length = const_cast(stream).tellg(); + const_cast(stream).seekg(0, std::ios::beg); + + char* data = new char[length]; + const_cast(stream).read(data, length); + openssl::BIO* bio = openssl::BIO_new(openssl::BIO_s_mem()); + BIO_write(bio, data, length); + delete[] data; + + openssl::EVP_PKEY* key = openssl::PEM_read_bio_PrivateKey(bio, 0, password_callback, (void*)pass); + if(!key) + //LOG(Error, Config) << "Invalid private key passphrase"; + else + ret.reset(new PrivateKey(key, pass)); + return ret; +} + + +PrivateKey::PrivateKey(openssl::EVP_PKEY* key, const PasswordCallback* pass) : me(new Pimp(pass)), _key(key) +{ +} + +PrivateKey::~PrivateKey() +{ + if(_key) + EVP_PKEY_free(_key); +} + +typedef int encrypt_decrypt_init(openssl::EVP_PKEY_CTX *ctx); +typedef int encrypt_decrypt(openssl::EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen); + + +bool encrypt_decrypt_function(const std::iostream& in_dat, std::iostream& out_data, + encrypt_decrypt_init* init_function, encrypt_decrypt* function, + openssl::EVP_PKEY* key, bool encrypt) +{ + openssl::EVP_PKEY_CTX* ctx = openssl::EVP_PKEY_CTX_new(key, 0); + bts_assert(ctx); + if(init_function) + bts_assert(init_function(ctx)); + bts_assert(openssl::EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING)); + + + char *name, *header; + unsigned char *in, *out; long inlen; size_t outlen; int i = 0; + iostreambio biostream(const_cast(&in_dat)); + if(!encrypt) + i = openssl::PEM_read_bio(biostream.getBIO(), &name, &header, &in, &inlen); + else + { + std::iostream seeker(in_dat.rdbuf()); + seeker.seekg(0, std::ios::end); + inlen = seeker.tellg(); + seeker.seekg(0, std::ios::beg); + + in = new unsigned char[inlen]; + i = openssl::BIO_read(biostream.getBIO(), in, inlen); + } + //BIO_flush(biostream.getBIO()); + BIO_free(biostream.getBIO()); + + bts_assert_msg(i > 0, "file not read, too short?"); + bts_assert(function(ctx, NULL, &outlen, in, inlen)); //to get size + out = new unsigned char[outlen]; + bts_assert(function(ctx, out, &outlen, in, inlen)); + //if(encrypt) + // delete[] in; + + std::string header_name = "BTS", header_header = ""; + iostreambio biostream_out(const_cast(&out_data)); + if(encrypt) + i = openssl::PEM_write_bio(biostream_out.getBIO(), header_name.c_str(), const_cast(header_header.c_str()), out, outlen); + else + i = openssl::BIO_write(biostream_out.getBIO(), out, outlen); + //BIO_flush(biostream_out.getBIO()); + BIO_free(biostream_out.getBIO()); + //delete[] out; + + return (i > 0); +} + +int private_encrypt_func(openssl::EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen) +{ + openssl::EVP_PKEY *pk = openssl::EVP_PKEY_CTX_get0_pkey(ctx); + if(out == 0) + { + *outlen = openssl::RSA_size(pk->pkey.rsa); + return -1; + } + else + { + return RSA_private_encrypt(inlen, const_cast(in), out, pk->pkey.rsa, RSA_PKCS1_PADDING); + } +} + +int public_decrypt_func(openssl::EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen) +{ + openssl::EVP_PKEY *pk = openssl::EVP_PKEY_CTX_get0_pkey(ctx); + if(out == 0) + { + *outlen = openssl::RSA_size(pk->pkey.rsa); + return -1; + } + else + { + int i = RSA_public_decrypt(inlen, const_cast(in), out, pk->pkey.rsa, RSA_PKCS1_PADDING); + out[i] = '\0'; + *outlen = i; + return i; + } +} + +bool PrivateKey::private_encrypt(const std::iostream& in_data, std::iostream& out_data) const +{ + return encrypt_decrypt_function(in_data, out_data, 0, private_encrypt_func, _key, true); +} + +bool PrivateKey::private_decrypt(const std::iostream& in_data, std::iostream& out_data) const +{ + return encrypt_decrypt_function(in_data, out_data, openssl::EVP_PKEY_decrypt_init, openssl::EVP_PKEY_decrypt, _key, false); +} + +bool PrivateKey::public_encrypt(const std::iostream& in_data, std::iostream& out_data) const +{ + return encrypt_decrypt_function(in_data, out_data, openssl::EVP_PKEY_encrypt_init, openssl::EVP_PKEY_encrypt, _key, true); +} + +bool PrivateKey::public_decrypt(const std::iostream& in_data, std::iostream& out_data) const +{ + return encrypt_decrypt_function(in_data, out_data, 0, public_decrypt_func, _key, false); +} + + +bool PrivateKey::encrypt(const std::iostream& in_data, std::iostream& out_data) const +{ + return private_encrypt(in_data, out_data); +} + +bool PrivateKey::decrypt(const std::iostream& in_data, std::iostream& out_data) const +{ + return private_decrypt(in_data, out_data); +} + +void PrivateKey::write(openssl::BIO* bio, CipherType::type cipher_type) const +{ + //see rsa.c ln 213 + const openssl::EVP_CIPHER* ciph = openssl::EVP_get_cipherbyname(CipherType::name[(int)cipher_type]); + bts_assert_msg(cipher_type == CipherType::None || ciph, "unknown cipher type"); + int nbytes = openssl::PEM_write_bio_PKCS8PrivateKey(bio, _key, ciph, 0, 0, password_callback, (void*)me->password); + UNUSED(nbytes); + int err = BIO_flush(bio); + UNUSED(err); +} + +void PrivateKey::write_file(const std::string& filename, CipherType::type cipher_type) const +{ + openssl::BIO* bio = openssl::BIO_new_file(filename.c_str(), "w+"); + write(bio, cipher_type); + BIO_free(bio); +} + + +void PrivateKey::write_stream(std::iostream& stream, CipherType::type cipher_type) const +{ + iostreambio biostream_out(&stream); + write(biostream_out.getBIO(), cipher_type); + BIO_free(biostream_out.getBIO()); +} + +} +} diff --git a/src/lib/utils/crypto/PrivateKey.h b/src/lib/utils/crypto/PrivateKey.h new file mode 100644 index 000000000..dbae5eb4d --- /dev/null +++ b/src/lib/utils/crypto/PrivateKey.h @@ -0,0 +1,70 @@ +#pragma once + +#include "lib/utils/bts_no_copy.h" + +#include "AlgoType.h" +#include "CipherType.h" +#include "PasswordCallback.h" + #include + +#include +#include + +namespace openssl +{ + struct evp_pkey_st; + typedef evp_pkey_st EVP_PKEY; + struct bio_st; + typedef struct bio_st BIO; +} + +namespace bts +{ +namespace crypto +{ + +class PrivateKey; +class PublicKey; +typedef std::shared_ptr PrivateKeyPtr; +typedef std::shared_ptr PublicKeyPtr; + +class PrivateKey +{ + BTS_NO_COPY(PrivateKey); +public: + virtual ~PrivateKey(); + static const PrivateKeyPtr create(int bits, AlgoType::type, const PasswordCallback* pass = 0); + static const PrivateKeyPtr read_file(const std::string& filename, const PasswordCallback* pass = 0); + static const PrivateKeyPtr read_stream(const std::istream& stream, const PasswordCallback* pass = 0); + +public: + virtual void write_file(const std::string& filename, CipherType::type cipher_type = CipherType::None) const; + virtual void write_stream(std::iostream& stream, CipherType::type cipher_type = CipherType::None) const; + + virtual bool encrypt(const std::iostream& in_dat, std::iostream& out_data) const; + virtual bool decrypt(const std::iostream& in_dat, std::iostream& out_data) const; + + + const PublicKeyPtr public_key() const; +protected: + friend class PublicKey; + friend int password_callback(char *buf, int size, int rwflag, void *u); + PrivateKey(openssl::EVP_PKEY* key = 0, const PasswordCallback* pass = 0); + virtual void write(openssl::BIO* bio, CipherType::type cipher_type) const; + + bool private_encrypt(const std::iostream& in_dat, std::iostream& out_data) const; + bool private_decrypt(const std::iostream& in_dat, std::iostream& out_data) const; + bool public_encrypt(const std::iostream& in_dat, std::iostream& out_data) const; + bool public_decrypt(const std::iostream& in_dat, std::iostream& out_data) const; + +protected: + struct Pimp; + std::shared_ptr me; + + openssl::EVP_PKEY* _key; +}; + + +} +} + diff --git a/src/lib/utils/crypto/PublicKey.cpp b/src/lib/utils/crypto/PublicKey.cpp new file mode 100644 index 000000000..16ae2adfa --- /dev/null +++ b/src/lib/utils/crypto/PublicKey.cpp @@ -0,0 +1,121 @@ +#include "PublicKey.h" + +#include "lib/logging/logging.h" +#include "lib/utils/crypto/iostreambio.h" + +namespace openssl +{ +#include +#include +#include +#include +#include +} + +namespace bts +{ +namespace crypto +{ + +PublicKey::PublicKey(openssl::EVP_PKEY* key) : PrivateKey(key) +{ +} + +PublicKey::PublicKey(const PrivateKey& key) : PrivateKey() +{ + //I don't know how to do this another way + openssl::BIO* bio = openssl::BIO_new(openssl::BIO_s_mem()); + // int i = openssl::PEM_write_bio_PUBKEY(bio, key._key); + //int err = BIO_flush(bio); + //UNUSED(i); + //UNUSED(err); + + openssl::EVP_PKEY* k = openssl::PEM_read_bio_PUBKEY(bio, 0, 0, 0); + BIO_free(bio); + //bts_assert(k); + this->_key = k; +} + +PublicKey::~PublicKey() +{ +} + +const PublicKeyPtr PublicKey::create(const PrivateKey& private_key) +{ + PublicKeyPtr ret(new PublicKey(private_key)); + return ret; +} + +const PublicKeyPtr PublicKey::read_file(const std::string& filename) +{ + PublicKeyPtr ret; + openssl::BIO* bio = openssl::BIO_new_file(filename.c_str(), "r"); + bts_assert_msg(bio, "can't load keyfile"); + openssl::EVP_PKEY* key = openssl::PEM_read_bio_PUBKEY(bio, 0, 0, 0); + if(!key) + //LOG(Error, Config) << "Invalid public key read"; + else + ret.reset(new PublicKey(key)); + return ret; +} + + +const PublicKeyPtr PublicKey::read_string(const std::string& public_key) +{ + PublicKeyPtr ret; + std::stringstream oss; + oss << public_key; + bts::crypto::iostreambio biostream(&oss); + openssl::EVP_PKEY* key = openssl::PEM_read_bio_PUBKEY(biostream.getBIO(), 0, 0, 0); + if(!key) + //LOG(Error, Config) << "Invalid public key read"; + else + ret.reset(new PublicKey(key)); + return ret; +} + +const PublicKeyPtr PublicKey::read_stream(std::istream& stream) +{ + PublicKeyPtr ret; + stream.seekg(0, std::ios::end); + int length = stream.tellg(); + stream.seekg(0, std::ios::beg); + + char* data = new char[length]; + stream.read(data, length); + openssl::BIO* bio = openssl::BIO_new(openssl::BIO_s_mem()); + BIO_write(bio, data, length); + delete[] data; + + openssl::EVP_PKEY* key = openssl::PEM_read_bio_PUBKEY(bio, 0, 0, 0); + if(!key) + // LOG(Error, Config) << "Invalid public key read"; + else + ret.reset(new PublicKey(key)); + return ret; +} + +void PublicKey::write(openssl::BIO* bio, CipherType::type) const +{ + //const openssl::EVP_CIPHER* ciph = openssl::EVP_get_cipherbyname(CipherType::name[(int)cipher_type]); + //bts_assert_msg(ciph, "unknown cipher type"); + int nbytes = openssl::PEM_write_bio_PUBKEY(bio, _key); + UNUSED(nbytes); + int err = BIO_flush(bio); + UNUSED(err); +} + +bool PublicKey::encrypt(const std::iostream& in_data, std::iostream& out_data) const +{ + return public_encrypt(in_data, out_data); +} + +bool PublicKey::decrypt(const std::iostream& in_data, std::iostream& out_data) const +{ + return public_decrypt(in_data, out_data); +} + + +} +} + diff --git a/src/lib/utils/crypto/PublicKey.h b/src/lib/utils/crypto/PublicKey.h new file mode 100644 index 000000000..4650aae86 --- /dev/null +++ b/src/lib/utils/crypto/PublicKey.h @@ -0,0 +1,37 @@ +#pragma once + +#include "lib/utils/bts_no_copy.h" + +#include "PrivateKey.h" + +namespace bts +{ +namespace crypto +{ + +class PublicKey : public PrivateKey +{ + BTS_NO_COPY(PublicKey); +public: + PublicKey(const PrivateKey&); + virtual ~PublicKey(); + + virtual bool encrypt(const std::iostream& in_dat, std::iostream& out_data) const; + virtual bool decrypt(const std::iostream& in_dat, std::iostream& out_data) const; + + static const PublicKeyPtr create(const PrivateKey& private_key); + static const PublicKeyPtr read_file(const std::string& filename); + static const PublicKeyPtr read_stream(std::istream& stream); + static const PublicKeyPtr read_string(const std::string& public_key); + + +protected: + virtual void write(openssl::BIO* bio, CipherType::type cipher_type) const; +protected: + PublicKey(openssl::EVP_PKEY*); + +}; + +} +} + diff --git a/src/lib/utils/crypto/iostreambio.cpp b/src/lib/utils/crypto/iostreambio.cpp new file mode 100644 index 000000000..9b221a04f --- /dev/null +++ b/src/lib/utils/crypto/iostreambio.cpp @@ -0,0 +1,219 @@ +#include "iostreambio.h" + +#include "lib/logging/logging.h" + +namespace openssl +{ +#include +} + +using namespace std; +using namespace openssl; + +namespace bts +{ +namespace crypto +{ + +const char * const iostreambio::name = "iostreambio"; +const int iostreambio::type = BIO_TYPE_SOURCE_SINK; + +/* callback functions for openssl */ +static int bwrite(BIO *bio, const char *buf, int len); +static int bread(BIO *bio, char *buf, int len); +//static int bputs(BIO *bio, const char *); +static int bgets(BIO *bio, char *, int); +static long ctrl(BIO *bio, int cmd, long num, void *ptr); +static int create(BIO *bio); +//static int destroy(BIO *bio); +//static long (*callback_ctrl)(BIO *, int, bio_info_cb *); + +// the new way of producing the BIO_Method is with BIO_meth_new() +// https://www.openssl.org/docs/man1.1.1/man3/BIO_get_new_index.html +// int bio_type = BIO_get_new_index(void); +// static BIO_METHOD iostream_method = BIO_meth_new(bio_type, "iostream_method"); + +// static BIO_METHOD iostream_method = +// { +// iostreambio::type, +// iostreambio::name, +// bwrite, +// bread, +// NULL,//bputs +// bgets,//bgets +// ctrl, +// create, +// NULL,//destroy, +// NULL//callback_ctrl +// }; + +// iostreambio::iostreambio(iostream *stream) : _bio(0) +// { +// //_bio = BIO_new(&iostream_method); +// //bts_assert(_bio); +// //_bio->ptr = stream; +// } + +// BIO* iostreambio::getBIO() +// { +// //return _bio; +// } + +static int create(BIO *bio) +{ + bio->ptr = NULL; + /* (from openssl memory bio) */ + bio->shutdown=1; + bio->init=1; + /* from bss_mem.c (openssl): + * bio->num is used to hold the value to return on 'empty', if it is + * 0, should_retry is not set + * + * => -1 means the caller can retry, 0: retry is useless + * it is set to 0 since the underlying stream is blocking + */ + bio->num= 0; + + return 1; +} + + + +static long ctrl(BIO *bio, int cmd, long num, void *ptr) +{ + UNUSED(ptr); + long ret; + iostream *stream = reinterpret_cast(bio->ptr); + + //LOG(Error, Config) << "iostreambio: ctrl called, cmd: " << cmd << ", num: " << num << "." ; + + switch(cmd){ + case BIO_CTRL_PUSH: + case BIO_CTRL_POP: + ret = 0; + break; + // case BIO_CTRL_GET_CLOSE: + // ret = bio->shutdown; + // break; + // case BIO_CTRL_SET_CLOSE: + // bio->shutdown = (int)num; + // ret = 1; + // break; + case BIO_CTRL_FLUSH: + /* try to flush the underlying stream */ + ret = 1; + try{ + stream->flush(); + } catch(ios_base::failure &){ + /* ignore, the badbit is checked instead */ + } + // catch(ConnectionClosedException &ex){ + // throw; + // } + if(stream->bad()){ + //LOG(Error, Config) << "iostreambio: underlying Stream went bad while flushing." ; + ret = 0; + } + break; + default: + // LOG(Warn, Config) << "iostreambio: ctrl called with unhandled cmd: " << cmd << "." ; + ret = 0; + break; + } + + return ret; +} + + + +static int bread(BIO *bio, char *buf, int len) +{ + iostream *stream = reinterpret_cast(bio->ptr); + streamsize num_bytes = bio->num; + try + { + /* make sure to read at least 1 byte and then read as much as we can */ + //num_bytes = stream->read(buf, 1).readsome(buf+1, len-1) + 1; + int i = 0; + while(stream->good() && i < len) + { + buf[i++] = stream->get(); + } + num_bytes = i; + } + catch(ios_base::failure &) + { + } + return num_bytes; +} + +static int bgets(BIO *bio, char *buf, int len) +{ + iostream *stream = reinterpret_cast(bio->ptr); + streamsize num_bytes = bio->num; + try + { + /* make sure to read at least 1 byte and then read as much as we can */ + //num_bytes = stream->read(buf, 1).readsome(buf+1, len-1) + 1; + int i = 0; + while(stream->good() && i < len) + { + buf[i] = stream->get(); + if(buf[i] == '\n') + { + i++; + break; + } + i++; + } + buf[i] = '\0'; + num_bytes = i; + } + catch(ios_base::failure &) + { + } + return num_bytes; +} + + +static int bwrite(BIO *bio, const char *buf, int len) +{ + if(len == 0){ + return 0; + } + iostream *stream = reinterpret_cast(bio->ptr); + + /* write the data */ + try{ + stream->write(buf, len); + } catch(ios_base::failure &){ + /* ignore, the badbit is checked instead */ + } + // catch(ConnectionClosedException &ex){ + // throw; + // } + if(stream->bad()){ + //LOG(Error, Config) << "iostreambio: underlying Stream went bad while writing." ; + return 0; + } + + /* flush the underlying stream */ + try{ + stream->flush(); + } catch(ios_base::failure &){ + /* ignore, the badbit is checked instead */ + } + // catch(ConnectionClosedException &ex){ + // throw; + // } + if(stream->bad()){ + //LOG(Error, Config) << "iostreambio: underlying Stream went bad while flushing (bwrite)." ; + return 0; + } + + return len; +} + +} +} + diff --git a/src/lib/utils/crypto/iostreambio.h b/src/lib/utils/crypto/iostreambio.h new file mode 100644 index 000000000..cec9a3dc7 --- /dev/null +++ b/src/lib/utils/crypto/iostreambio.h @@ -0,0 +1,30 @@ +#pragma once + +namespace openssl +{ + struct bio_st; + typedef struct bio_st BIO; +} + +#include + +namespace bts +{ +namespace crypto +{ + +class iostreambio +{ +public: + explicit iostreambio(std::iostream* stream); + openssl::BIO* getBIO(); + + static const char * const name; + static const int type; +private: + openssl::BIO *_bio; +}; + +} +} +