1 /*
2 * Copyright (C) 2021 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 #define LOG_TAG "clearkey-AesDecryptor"
17
18 #include <utils/Log.h>
19
20 #include <openssl/aes.h>
21
22 #include "AesCtrDecryptor.h"
23 #include "ClearKeyTypes.h"
24
25 namespace clearkeydrm {
26
27 static const size_t kBlockBitCount = kBlockSize * 8;
28
decrypt(const std::vector<uint8_t> & key,const Iv iv,const uint8_t * source,uint8_t * destination,const std::vector<int32_t> & clearDataLengths,const std::vector<int32_t> & encryptedDataLengths,size_t * bytesDecryptedOut)29 CdmResponseType AesCtrDecryptor::decrypt(const std::vector<uint8_t>& key, const Iv iv,
30 const uint8_t* source, uint8_t* destination,
31 const std::vector<int32_t>& clearDataLengths,
32 const std::vector<int32_t>& encryptedDataLengths,
33 size_t* bytesDecryptedOut) {
34
35 if (key.size() != kBlockSize || clearDataLengths.size() != encryptedDataLengths.size()) {
36 android_errorWriteLog(0x534e4554, "63982768");
37 return clearkeydrm::ERROR_DECRYPT;
38 }
39
40 uint32_t blockOffset = 0;
41 uint8_t previousEncryptedCounter[kBlockSize];
42 memset(previousEncryptedCounter, 0, kBlockSize);
43
44 size_t offset = 0;
45 AES_KEY opensslKey;
46 AES_set_encrypt_key(key.data(), kBlockBitCount, &opensslKey);
47 Iv opensslIv;
48 memcpy(opensslIv, iv, sizeof(opensslIv));
49
50 for (size_t i = 0; i < clearDataLengths.size(); ++i) {
51 int32_t numBytesOfClearData = clearDataLengths[i];
52 if (numBytesOfClearData > 0) {
53 memcpy(destination + offset, source + offset, numBytesOfClearData);
54 offset += numBytesOfClearData;
55 }
56
57 int32_t numBytesOfEncryptedData = encryptedDataLengths[i];
58 if (numBytesOfEncryptedData > 0) {
59 AES_ctr128_encrypt(source + offset, destination + offset,
60 numBytesOfEncryptedData, &opensslKey, opensslIv,
61 previousEncryptedCounter, &blockOffset);
62 offset += numBytesOfEncryptedData;
63 }
64 }
65
66 *bytesDecryptedOut = offset;
67 return clearkeydrm::OK;
68 }
69
70 } // namespace clearkeydrm
71