1 /* 2 * Copyright 2015, Mozilla Foundation and contributors 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 #ifndef __ClearKeyDecryptionManager_h__ 18 #define __ClearKeyDecryptionManager_h__ 19 20 #include <map> 21 22 #include "ClearKeyUtils.h" 23 #include "RefCounted.h" 24 25 class ClearKeyDecryptor; 26 27 class CryptoMetaData { 28 public: CryptoMetaData()29 CryptoMetaData() {} 30 CryptoMetaData(const GMPEncryptedBufferMetadata * aCrypto)31 explicit CryptoMetaData(const GMPEncryptedBufferMetadata* aCrypto) 32 { 33 Init(aCrypto); 34 } 35 Init(const GMPEncryptedBufferMetadata * aCrypto)36 void Init(const GMPEncryptedBufferMetadata* aCrypto) 37 { 38 if (!aCrypto) { 39 assert(!IsValid()); 40 return; 41 } 42 Assign(mKeyId, aCrypto->KeyId(), aCrypto->KeyIdSize()); 43 Assign(mIV, aCrypto->IV(), aCrypto->IVSize()); 44 Assign(mClearBytes, aCrypto->ClearBytes(), aCrypto->NumSubsamples()); 45 Assign(mCipherBytes, aCrypto->CipherBytes(), aCrypto->NumSubsamples()); 46 } 47 IsValid()48 bool IsValid() const { 49 return !mKeyId.empty() && 50 !mIV.empty() && 51 !mCipherBytes.empty() && 52 !mClearBytes.empty(); 53 } 54 NumSubsamples()55 size_t NumSubsamples() const { 56 assert(mClearBytes.size() == mCipherBytes.size()); 57 return mClearBytes.size(); 58 } 59 60 std::vector<uint8_t> mKeyId; 61 std::vector<uint8_t> mIV; 62 std::vector<uint16_t> mClearBytes; 63 std::vector<uint32_t> mCipherBytes; 64 }; 65 66 class ClearKeyDecryptionManager : public RefCounted 67 { 68 private: 69 ClearKeyDecryptionManager(); 70 ~ClearKeyDecryptionManager(); 71 72 static ClearKeyDecryptionManager* sInstance; 73 74 public: 75 static ClearKeyDecryptionManager* Get(); 76 77 bool HasSeenKeyId(const KeyId& aKeyId) const; 78 bool HasKeyForKeyId(const KeyId& aKeyId) const; 79 80 const Key& GetDecryptionKey(const KeyId& aKeyId); 81 82 // Create a decryptor for the given KeyId if one does not already exist. 83 void InitKey(KeyId aKeyId, Key aKey); 84 void ExpectKeyId(KeyId aKeyId); 85 void ReleaseKeyId(KeyId aKeyId); 86 87 // Decrypts buffer *in place*. 88 GMPErr Decrypt(uint8_t* aBuffer, uint32_t aBufferSize, 89 const CryptoMetaData& aMetadata); 90 GMPErr Decrypt(std::vector<uint8_t>& aBuffer, 91 const CryptoMetaData& aMetadata); 92 93 void Shutdown(); 94 95 private: 96 bool IsExpectingKeyForKeyId(const KeyId& aKeyId) const; 97 98 std::map<KeyId, ClearKeyDecryptor*> mDecryptors; 99 }; 100 101 #endif // __ClearKeyDecryptionManager_h__ 102