Shaka Packager SDK
aes_encryptor_factory.cc
1 // Copyright 2018 Google LLC. 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/crypto/aes_encryptor_factory.h>
8 
9 #include <packager/media/base/aes_encryptor.h>
10 #include <packager/media/base/aes_pattern_cryptor.h>
11 #include <packager/media/crypto/sample_aes_ec3_cryptor.h>
12 
13 namespace shaka {
14 namespace media {
15 
16 std::unique_ptr<AesCryptor> AesEncryptorFactory::CreateEncryptor(
17  FourCC protection_scheme,
18  uint8_t crypt_byte_block,
19  uint8_t skip_byte_block,
20  Codec codec,
21  const std::vector<uint8_t>& key,
22  const std::vector<uint8_t>& iv) {
23  std::unique_ptr<AesCryptor> encryptor;
24  switch (protection_scheme) {
25  case FOURCC_cenc:
26  encryptor.reset(new AesCtrEncryptor);
27  break;
28  case FOURCC_cbc1:
29  encryptor.reset(new AesCbcEncryptor(kNoPadding));
30  break;
31  case FOURCC_cens:
32  encryptor.reset(new AesPatternCryptor(
33  crypt_byte_block, skip_byte_block,
35  AesCryptor::kDontUseConstantIv,
36  std::unique_ptr<AesCryptor>(new AesCtrEncryptor)));
37  break;
38  case FOURCC_cbcs:
39  encryptor.reset(new AesPatternCryptor(
40  crypt_byte_block, skip_byte_block,
42  AesCryptor::kUseConstantIv,
43  std::unique_ptr<AesCryptor>(new AesCbcEncryptor(kNoPadding))));
44  break;
45  case kAppleSampleAesProtectionScheme:
46  if (crypt_byte_block == 0 && skip_byte_block == 0) {
47  if (codec == kCodecEAC3) {
48  encryptor.reset(new SampleAesEc3Cryptor(
49  std::unique_ptr<AesCryptor>(new AesCbcEncryptor(kNoPadding))));
50  } else {
51  encryptor.reset(
52  new AesCbcEncryptor(kNoPadding, AesCryptor::kUseConstantIv));
53  }
54  } else {
55  encryptor.reset(new AesPatternCryptor(
56  crypt_byte_block, skip_byte_block,
58  AesCryptor::kUseConstantIv,
59  std::unique_ptr<AesCryptor>(new AesCbcEncryptor(kNoPadding))));
60  }
61  break;
62  default:
63  LOG(ERROR) << "Unsupported protection scheme.";
64  return nullptr;
65  }
66 
67  if (iv.empty()) {
68  std::vector<uint8_t> random_iv;
69  if (!AesCryptor::GenerateRandomIv(protection_scheme, &random_iv)) {
70  LOG(ERROR) << "Failed to generate random iv.";
71  return nullptr;
72  }
73  if (!encryptor->InitializeWithIv(key, random_iv))
74  return nullptr;
75  } else {
76  if (!encryptor->InitializeWithIv(key, iv))
77  return nullptr;
78  }
79 
80  return encryptor;
81 }
82 
83 } // namespace media
84 } // namespace shaka
static bool GenerateRandomIv(FourCC protection_scheme, std::vector< uint8_t > *iv)
Definition: aes_cryptor.cc:110
All the methods that are virtual are virtual for mocking.
Definition: crypto_flags.cc:66