1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 //#define LOG_NDEBUG 0
18 #define LOG_TAG "hidl_ClearkeyDecryptor"
19 #include <utils/Log.h>
20
21 #include <openssl/aes.h>
22
23 #include "AesCtrDecryptor.h"
24 #include "ClearKeyTypes.h"
25
26 namespace android {
27 namespace hardware {
28 namespace drm {
29 namespace V1_2 {
30 namespace clearkey {
31
32 using ::android::hardware::drm::V1_0::SubSample;
33 using ::android::hardware::drm::V1_0::Status;
34
35 static const size_t kBlockBitCount = kBlockSize * 8;
36
decrypt(const std::vector<uint8_t> & key,const Iv iv,const uint8_t * source,uint8_t * destination,const std::vector<SubSample> subSamples,size_t numSubSamples,size_t * bytesDecryptedOut)37 Status AesCtrDecryptor::decrypt(
38 const std::vector<uint8_t>& key,
39 const Iv iv, const uint8_t* source,
40 uint8_t* destination,
41 const std::vector<SubSample> subSamples,
42 size_t numSubSamples,
43 size_t* bytesDecryptedOut) {
44 uint32_t blockOffset = 0;
45 uint8_t previousEncryptedCounter[kBlockSize];
46 memset(previousEncryptedCounter, 0, kBlockSize);
47
48 if (key.size() != kBlockSize || (sizeof(Iv) / sizeof(uint8_t)) != kBlockSize) {
49 android_errorWriteLog(0x534e4554, "63982768");
50 return Status::ERROR_DRM_DECRYPT;
51 }
52
53 size_t offset = 0;
54 AES_KEY opensslKey;
55 AES_set_encrypt_key(key.data(), kBlockBitCount, &opensslKey);
56 Iv opensslIv;
57 memcpy(opensslIv, iv, sizeof(opensslIv));
58
59 for (size_t i = 0; i < numSubSamples; ++i) {
60 const SubSample& subSample = subSamples[i];
61
62 if (subSample.numBytesOfClearData > 0) {
63 memcpy(destination + offset, source + offset,
64 subSample.numBytesOfClearData);
65 offset += subSample.numBytesOfClearData;
66 }
67
68 if (subSample.numBytesOfEncryptedData > 0) {
69 AES_ctr128_encrypt(source + offset, destination + offset,
70 subSample.numBytesOfEncryptedData, &opensslKey,
71 opensslIv, previousEncryptedCounter,
72 &blockOffset);
73 offset += subSample.numBytesOfEncryptedData;
74 }
75 }
76
77 *bytesDecryptedOut = offset;
78 return Status::OK;
79 }
80
81 } // namespace clearkey
82 } // namespace V1_2
83 } // namespace drm
84 } // namespace hardware
85 } // namespace android
86
87