DASH Media Packaging SDK
 All Classes Namespaces Functions Variables Typedefs Enumerator
aes_cryptor.cc
1 // Copyright 2016 Google Inc. All rights reserved.
2 //
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file or at
5 // https://developers.google.com/open-source/licenses/bsd
6 
7 #include "packager/media/base/aes_cryptor.h"
8 
9 #include <openssl/aes.h>
10 #include <openssl/err.h>
11 #include <openssl/rand.h>
12 
13 #include "packager/base/logging.h"
14 #include "packager/base/stl_util.h"
15 
16 namespace edash_packager {
17 namespace media {
18 
19 AesCryptor::AesCryptor() : aes_key_(new AES_KEY) {}
20 AesCryptor::~AesCryptor() {}
21 
22 bool AesCryptor::Crypt(const std::vector<uint8_t>& text,
23  std::vector<uint8_t>* crypt_text) {
24  // Save text size to make it work for in-place conversion, since the
25  // next statement will update the text size.
26  const size_t text_size = text.size();
27  crypt_text->resize(text_size + NumPaddingBytes(text_size));
28  size_t crypt_text_size = crypt_text->size();
29  if (!CryptInternal(text.data(), text_size, crypt_text->data(),
30  &crypt_text_size)) {
31  return false;
32  }
33  DCHECK_LE(crypt_text_size, crypt_text->size());
34  crypt_text->resize(crypt_text_size);
35  return true;
36 }
37 
38 bool AesCryptor::Crypt(const std::string& text, std::string* crypt_text) {
39  // Save text size to make it work for in-place conversion, since the
40  // next statement will update the text size.
41  const size_t text_size = text.size();
42  crypt_text->resize(text_size + NumPaddingBytes(text_size));
43  size_t crypt_text_size = crypt_text->size();
44  if (!CryptInternal(reinterpret_cast<const uint8_t*>(text.data()), text_size,
45  reinterpret_cast<uint8_t*>(string_as_array(crypt_text)),
46  &crypt_text_size))
47  return false;
48  DCHECK_LE(crypt_text_size, crypt_text->size());
49  crypt_text->resize(crypt_text_size);
50  return true;
51 }
52 
53 size_t AesCryptor::NumPaddingBytes(size_t size) const {
54  // No padding by default.
55  return 0;
56 }
57 
58 bool AesCryptor::GenerateRandomIv(FourCC protection_scheme,
59  std::vector<uint8_t>* iv) {
60  // ISO/IEC 23001-7:2016 10.1 and 10.3 For 'cenc' and 'cens'
61  // default_Per_Sample_IV_Size and Per_Sample_IV_Size SHOULD be 8-bytes.
62  // There is no official guideline on the iv size for 'cbc1' and 'cbcs',
63  // but 16-byte provides better security.
64  const size_t iv_size =
65  (protection_scheme == FOURCC_cenc || protection_scheme == FOURCC_cens)
66  ? 8
67  : 16;
68  iv->resize(iv_size);
69  if (RAND_bytes(iv->data(), iv_size) != 1) {
70  LOG(ERROR) << "RAND_bytes failed with error: "
71  << ERR_error_string(ERR_get_error(), NULL);
72  return false;
73  }
74  return true;
75 }
76 
77 } // namespace media
78 } // namespace edash_packager
79 
80