Shaka Packager SDK
Loading...
Searching...
No Matches
aes_key_wrap.cc
1// Copyright 2026 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/base/aes_key_wrap.h>
8
9#include <cstddef>
10#include <cstdint>
11#include <vector>
12
13#include <absl/log/check.h>
14#include <absl/log/log.h>
15#include <mbedtls/nist_kw.h>
16
17namespace shaka {
18namespace media {
19namespace {
20
21bool IsValidWrappingKeySize(size_t size) {
22 return size == 16 || size == 24 || size == 32;
23}
24
25} // namespace
26
27bool AesKeyUnwrap(const std::vector<uint8_t>& wrapping_key,
28 const std::vector<uint8_t>& wrapped_data,
29 std::vector<uint8_t>* data) {
30 DCHECK(data);
31 if (!IsValidWrappingKeySize(wrapping_key.size())) {
32 LOG(ERROR) << "Invalid AES key wrap key size: " << wrapping_key.size();
33 return false;
34 }
35
36 mbedtls_nist_kw_context context;
37 mbedtls_nist_kw_init(&context);
38 int rv = mbedtls_nist_kw_setkey(
39 &context, MBEDTLS_CIPHER_ID_AES, wrapping_key.data(),
40 static_cast<unsigned>(wrapping_key.size()) * 8,
41 /* is_wrap= */ 0);
42 if (rv != 0) {
43 LOG(ERROR) << "AES key unwrap setkey failed: " << rv;
44 mbedtls_nist_kw_free(&context);
45 return false;
46 }
47
48 data->resize(wrapped_data.size());
49 size_t output_size = 0;
50 rv = mbedtls_nist_kw_unwrap(&context, MBEDTLS_KW_MODE_KW, wrapped_data.data(),
51 wrapped_data.size(), data->data(), &output_size,
52 data->size());
53 mbedtls_nist_kw_free(&context);
54 if (rv != 0) {
55 LOG(ERROR) << "AES key unwrap failed: " << rv;
56 return false;
57 }
58 data->resize(output_size);
59 return true;
60}
61
62} // namespace media
63} // namespace shaka
All the methods that are virtual are virtual for mocking.