24 #include <openssl/bio.h>
25 #include <openssl/evp.h>
27 #include <boost/lexical_cast.hpp>
31 class BlockCipher::Impl : boost::noncopyable
35 : m_cipher(BIO_new(BIO_f_cipher()))
36 , m_sink(BIO_new(BIO_s_mem()))
38 BIO_push(m_cipher, m_sink);
43 BIO_free_all(m_cipher);
53 span<const uint8_t> key, span<const uint8_t> iv)
54 : m_impl(make_unique<Impl>())
58 initializeAesCbc(key, iv, op);
62 boost::lexical_cast<std::string>(algo)));
69 BlockCipher::preTransform()
75 BlockCipher::convert(span<const uint8_t> data)
80 int wLen = BIO_write(m_impl->m_cipher, data.data(), data.size());
83 if (!BIO_should_retry(m_impl->m_cipher)) {
91 return static_cast<size_t>(wLen);
96 BlockCipher::finalize()
98 if (BIO_flush(m_impl->m_cipher) != 1)
101 while (!isConverterEmpty()) {
110 BlockCipher::fillOutputBuffer()
112 int nPending = BIO_pending(m_impl->m_sink);
117 auto buffer = make_unique<OBuffer>(nPending);
118 int nRead = BIO_read(m_impl->m_sink, buffer->data(), nPending);
122 buffer->erase(buffer->begin() + nRead, buffer->end());
127 BlockCipher::isConverterEmpty()
const
129 return BIO_pending(m_impl->m_sink) <= 0;
133 BlockCipher::initializeAesCbc(span<const uint8_t> key, span<const uint8_t> iv,
CipherOperator op)
135 const EVP_CIPHER* cipherType =
nullptr;
136 switch (key.size()) {
138 cipherType = EVP_aes_128_cbc();
141 cipherType = EVP_aes_192_cbc();
144 cipherType = EVP_aes_256_cbc();
150 auto requiredIvLen =
static_cast<size_t>(EVP_CIPHER_iv_length(cipherType));
151 if (iv.size() != requiredIvLen)
154 BIO_set_cipher(m_impl->m_cipher, cipherType, key.data(), iv.data(),
158 unique_ptr<Transform>
160 span<const uint8_t> key, span<const uint8_t> iv)
162 return make_unique<BlockCipher>(algo, op, key, iv);
std::string to_string(const errinfo_stacktrace &x)