7 #include "packager/media/base/aes_cryptor.h"
9 #include <openssl/aes.h>
10 #include <openssl/crypto.h>
11 #include <openssl/err.h>
12 #include <openssl/rand.h>
17 #include "packager/base/logging.h"
23 bool IsIvSizeValid(
size_t iv_size) {
24 return iv_size == 8 || iv_size == 16;
33 : aes_key_(new AES_KEY),
34 constant_iv_flag_(constant_iv_flag),
36 CRYPTO_library_init();
39 AesCryptor::~AesCryptor() {}
41 bool AesCryptor::Crypt(
const std::vector<uint8_t>& text,
42 std::vector<uint8_t>* crypt_text) {
45 const size_t text_size = text.size();
46 crypt_text->resize(text_size + NumPaddingBytes(text_size));
47 size_t crypt_text_size = crypt_text->size();
48 if (!Crypt(text.data(), text_size, crypt_text->data(), &crypt_text_size)) {
51 DCHECK_LE(crypt_text_size, crypt_text->size());
52 crypt_text->resize(crypt_text_size);
56 bool AesCryptor::Crypt(
const std::string& text, std::string* crypt_text) {
59 const size_t text_size = text.size();
60 crypt_text->resize(text_size + NumPaddingBytes(text_size));
61 size_t crypt_text_size = crypt_text->size();
62 if (!Crypt(
reinterpret_cast<const uint8_t*
>(text.data()), text_size,
63 reinterpret_cast<uint8_t*
>(&(*crypt_text)[0]), &crypt_text_size))
65 DCHECK_LE(crypt_text_size, crypt_text->size());
66 crypt_text->resize(crypt_text_size);
71 if (!IsIvSizeValid(
iv.size())) {
72 LOG(ERROR) <<
"Invalid IV size: " <<
iv.size();
82 if (constant_iv_flag_ == kUseConstantIv)
85 uint64_t increment = 0;
94 if (iv_.size() == 8) {
97 DCHECK_EQ(16u, iv_.size());
98 increment = (num_crypt_bytes_ + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE;
101 for (
int i = iv_.size() - 1; increment > 0 && i >= 0; --i) {
103 iv_[i] = increment & 0xFF;
106 num_crypt_bytes_ = 0;
111 std::vector<uint8_t>* iv) {
116 const size_t iv_size =
117 (protection_scheme == FOURCC_cenc || protection_scheme == FOURCC_cens)
121 if (RAND_bytes(
iv->data(), iv_size) != 1) {
122 LOG(ERROR) <<
"RAND_bytes failed with error: "
123 << ERR_error_string(ERR_get_error(), NULL);
129 size_t AesCryptor::NumPaddingBytes(
size_t size)
const {