1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "media/cast/transport/utility/transport_encryption_handler.h"
7 #include "base/logging.h"
8 #include "crypto/encryptor.h"
9 #include "crypto/symmetric_key.h"
10 #include "media/cast/transport/cast_transport_defines.h"
16 TransportEncryptionHandler::TransportEncryptionHandler()
17 : key_(), encryptor_(), iv_mask_(), initialized_(false) {}
19 TransportEncryptionHandler::~TransportEncryptionHandler() {}
21 bool TransportEncryptionHandler::Initialize(std::string aes_key
,
22 std::string aes_iv_mask
) {
24 if (aes_iv_mask
.size() == kAesKeySize
&& aes_key
.size() == kAesKeySize
) {
25 iv_mask_
= aes_iv_mask
;
27 crypto::SymmetricKey::Import(crypto::SymmetricKey::AES
, aes_key
));
28 encryptor_
.reset(new crypto::Encryptor());
29 encryptor_
->Init(key_
.get(), crypto::Encryptor::CTR
, std::string());
31 } else if (aes_iv_mask
.size() != 0 || aes_key
.size() != 0) {
32 DCHECK_EQ(aes_iv_mask
.size(), 0u)
33 << "Invalid Crypto configuration: aes_iv_mask.size";
34 DCHECK_EQ(aes_key
.size(), 0u)
35 << "Invalid Crypto configuration: aes_key.size";
41 bool TransportEncryptionHandler::Encrypt(uint32 frame_id
,
42 const base::StringPiece
& data
,
43 std::string
* encrypted_data
) {
46 if (!encryptor_
->SetCounter(GetAesNonce(frame_id
, iv_mask_
))) {
47 NOTREACHED() << "Failed to set counter";
50 if (!encryptor_
->Encrypt(data
, encrypted_data
)) {
51 NOTREACHED() << "Encrypt error";
57 bool TransportEncryptionHandler::Decrypt(uint32 frame_id
,
58 const base::StringPiece
& ciphertext
,
59 std::string
* plaintext
) {
63 if (!encryptor_
->SetCounter(transport::GetAesNonce(frame_id
, iv_mask_
))) {
64 NOTREACHED() << "Failed to set counter";
67 if (!encryptor_
->Decrypt(ciphertext
, plaintext
)) {
68 VLOG(1) << "Decryption error";
74 } // namespace transport