24 #include <openssl/bio.h>
25 #include <openssl/evp.h>
27 #include <boost/lexical_cast.hpp>
33 class BlockCipher::Impl : boost::noncopyable
37 : m_cipher(BIO_new(BIO_f_cipher()))
38 , m_sink(BIO_new(BIO_s_mem()))
40 BIO_push(m_cipher, m_sink);
45 BIO_free_all(m_cipher);
55 span<const uint8_t> key, span<const uint8_t> iv)
56 : m_impl(make_unique<Impl>())
60 initializeAesCbc(key, iv, op);
64 boost::lexical_cast<std::string>(algo)));
71 BlockCipher::preTransform()
77 BlockCipher::convert(span<const uint8_t> data)
82 int wLen = BIO_write(m_impl->m_cipher, data.data(), data.size());
85 if (!BIO_should_retry(m_impl->m_cipher)) {
93 return static_cast<size_t>(wLen);
98 BlockCipher::finalize()
100 if (BIO_flush(m_impl->m_cipher) != 1)
103 while (!isConverterEmpty()) {
112 BlockCipher::fillOutputBuffer()
114 int nPending = BIO_pending(m_impl->m_sink);
119 auto buffer = make_unique<OBuffer>(nPending);
120 int nRead = BIO_read(m_impl->m_sink, buffer->data(), nPending);
124 buffer->erase(buffer->begin() + nRead, buffer->end());
129 BlockCipher::isConverterEmpty()
const
131 return BIO_pending(m_impl->m_sink) <= 0;
135 BlockCipher::initializeAesCbc(span<const uint8_t> key, span<const uint8_t> iv,
CipherOperator op)
137 const EVP_CIPHER* cipherType =
nullptr;
138 switch (key.size()) {
140 cipherType = EVP_aes_128_cbc();
143 cipherType = EVP_aes_192_cbc();
146 cipherType = EVP_aes_256_cbc();
152 auto requiredIvLen =
static_cast<size_t>(EVP_CIPHER_iv_length(cipherType));
153 if (iv.size() != requiredIvLen)
156 BIO_set_cipher(m_impl->m_cipher, cipherType, key.data(), iv.data(),
160 unique_ptr<Transform>
162 span<const uint8_t> key, span<const uint8_t> iv)
164 return make_unique<BlockCipher>(algo, op, key, iv);
std::string to_string(const errinfo_stacktrace &x)