1 // Copyright 2021 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ///////////////////////////////////////////////////////////////////////////////
16 #include "tink/aead/internal/aead_util.h"
17
18 #include <string>
19
20 #include "absl/status/status.h"
21 #include "openssl/evp.h"
22 #include "tink/util/errors.h"
23 #include "tink/util/statusor.h"
24
25 namespace crypto {
26 namespace tink {
27 namespace internal {
28
IsSupportedKmsEnvelopeAeadDekKeyType(absl::string_view key_type)29 bool IsSupportedKmsEnvelopeAeadDekKeyType(absl::string_view key_type) {
30 static const auto *kSupportedDekKeyTypes =
31 new absl::flat_hash_set<std::string>({
32 "type.googleapis.com/google.crypto.tink.AesGcmKey",
33 "type.googleapis.com/google.crypto.tink.XChaCha20Poly1305Key",
34 "type.googleapis.com/google.crypto.tink.AesCtrHmacAeadKey",
35 "type.googleapis.com/google.crypto.tink.AesEaxKey",
36 "type.googleapis.com/google.crypto.tink.AesGcmSivKey",
37 });
38 return kSupportedDekKeyTypes->contains(key_type);
39 }
40
GetAesGcmCipherForKeySize(uint32_t key_size_in_bytes)41 util::StatusOr<const EVP_CIPHER *> GetAesGcmCipherForKeySize(
42 uint32_t key_size_in_bytes) {
43 switch (key_size_in_bytes) {
44 case 16:
45 return EVP_aes_128_gcm();
46 case 32:
47 return EVP_aes_256_gcm();
48 default:
49 return ToStatusF(absl::StatusCode::kInvalidArgument,
50 "Invalid key size %d", key_size_in_bytes);
51 }
52 }
53
54 #ifdef OPENSSL_IS_BORINGSSL
GetAesGcmAeadForKeySize(uint32_t key_size_in_bytes)55 util::StatusOr<const EVP_AEAD *> GetAesGcmAeadForKeySize(
56 uint32_t key_size_in_bytes) {
57 switch (key_size_in_bytes) {
58 case 16:
59 return EVP_aead_aes_128_gcm();
60 case 32:
61 return EVP_aead_aes_256_gcm();
62 default:
63 return ToStatusF(absl::StatusCode::kInvalidArgument,
64 "Invalid key size %d", key_size_in_bytes);
65 }
66 }
67
GetAesGcmSivAeadCipherForKeySize(int key_size_in_bytes)68 util::StatusOr<const EVP_AEAD *> GetAesGcmSivAeadCipherForKeySize(
69 int key_size_in_bytes) {
70 switch (key_size_in_bytes) {
71 case 16:
72 return EVP_aead_aes_128_gcm_siv();
73 case 32:
74 return EVP_aead_aes_256_gcm_siv();
75 default:
76 return ToStatusF(
77 absl::StatusCode::kInvalidArgument,
78 "Invalid key size; valid values are {16, 32} bytes, got %d",
79 key_size_in_bytes);
80 }
81 }
82 #endif
83
84 } // namespace internal
85 } // namespace tink
86 } // namespace crypto
87