23 #include "../detail/openssl.hpp" 25 #include <boost/lexical_cast.hpp> 31 class BlockCipher::Impl
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 const uint8_t* key,
size_t keyLen,
54 const uint8_t* iv,
size_t ivLen)
59 initializeAesCbc(key, keyLen, iv, ivLen, op);
62 BOOST_THROW_EXCEPTION(
Error(
getIndex(),
"Unsupported block cipher algorithm " +
63 boost::lexical_cast<std::string>(algo)));
70 BlockCipher::preTransform()
76 BlockCipher::convert(
const uint8_t* data,
size_t dataLen)
81 int wLen = BIO_write(m_impl->m_cipher, data, dataLen);
84 if (!BIO_should_retry(m_impl->m_cipher)) {
86 BOOST_THROW_EXCEPTION(
Error(
getIndex(),
"Failed to accept more input"));
92 return static_cast<size_t>(wLen);
97 BlockCipher::finalize()
99 if (BIO_flush(m_impl->m_cipher) != 1)
102 while (!isConverterEmpty()) {
111 BlockCipher::fillOutputBuffer()
113 int nPending = BIO_pending(m_impl->m_sink);
118 auto buffer = make_unique<OBuffer>(nPending);
119 int nRead = BIO_read(m_impl->m_sink, buffer->data(), nPending);
123 buffer->erase(buffer->begin() + nRead, buffer->end());
128 BlockCipher::isConverterEmpty()
const 130 return BIO_pending(m_impl->m_sink) <= 0;
134 BlockCipher::initializeAesCbc(
const uint8_t* key,
size_t keyLen,
137 const EVP_CIPHER* cipherType =
nullptr;
140 cipherType = EVP_aes_128_cbc();
143 cipherType = EVP_aes_192_cbc();
146 cipherType = EVP_aes_256_cbc();
152 size_t requiredIvLen =
static_cast<size_t>(EVP_CIPHER_iv_length(cipherType));
153 if (ivLen != requiredIvLen)
156 BIO_set_cipher(m_impl->m_cipher, cipherType, key, iv, static_cast<int>(op));
159 unique_ptr<Transform>
161 const uint8_t* key,
size_t keyLen,
162 const uint8_t* iv,
size_t ivLen)
164 return make_unique<BlockCipher>(algo, op, key, keyLen, iv, ivLen);
Copyright (c) 2013-2017 Regents of the University of California.
unique_ptr< T > make_unique(Args &&...args)
std::string to_string(const V &v)