7 #include "packager/media/base/aes_cryptor.h"
12 #include <openssl/aes.h>
13 #include <openssl/err.h>
14 #include <openssl/rand.h>
16 #include "packager/base/logging.h"
17 #include "packager/base/stl_util.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),
35 num_crypt_bytes_(0) {}
37 AesCryptor::~AesCryptor() {}
39 bool AesCryptor::Crypt(
const std::vector<uint8_t>& text,
40 std::vector<uint8_t>* crypt_text) {
43 const size_t text_size = text.size();
44 crypt_text->resize(text_size + NumPaddingBytes(text_size));
45 size_t crypt_text_size = crypt_text->size();
46 if (!Crypt(text.data(), text_size, crypt_text->data(), &crypt_text_size)) {
49 DCHECK_LE(crypt_text_size, crypt_text->size());
50 crypt_text->resize(crypt_text_size);
54 bool AesCryptor::Crypt(
const std::string& text, std::string* crypt_text) {
57 const size_t text_size = text.size();
58 crypt_text->resize(text_size + NumPaddingBytes(text_size));
59 size_t crypt_text_size = crypt_text->size();
60 if (!Crypt(reinterpret_cast<const uint8_t*>(text.data()), text_size,
61 reinterpret_cast<uint8_t*>(string_as_array(crypt_text)),
64 DCHECK_LE(crypt_text_size, crypt_text->size());
65 crypt_text->resize(crypt_text_size);
70 if (!IsIvSizeValid(iv.size())) {
71 LOG(ERROR) <<
"Invalid IV size: " << iv.size();
81 if (constant_iv_flag_ == kUseConstantIv)
84 uint64_t increment = 0;
93 if (iv_.size() == 8) {
96 DCHECK_EQ(16u, iv_.size());
97 increment = (num_crypt_bytes_ + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE;
100 for (
int i = iv_.size() - 1; increment > 0 && i >= 0; --i) {
102 iv_[i] = increment & 0xFF;
105 num_crypt_bytes_ = 0;
110 std::vector<uint8_t>* iv) {
115 const size_t iv_size =
116 (protection_scheme == FOURCC_cenc || protection_scheme == FOURCC_cens)
120 if (RAND_bytes(iv->data(), iv_size) != 1) {
121 LOG(ERROR) <<
"RAND_bytes failed with error: "
122 << ERR_error_string(ERR_get_error(), NULL);
128 size_t AesCryptor::NumPaddingBytes(
size_t size)
const {