Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / third_party / betocore / ukey2_connections / src / crypto_utils.rs

crypto_utils.rs70 lines · 2.4 KiBRaw
1// Copyright 2023 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
15use crate::d2d_connection_context_v1::{Aes256Key as RawAes256Key, AesCbcIv};
16use crypto_provider::aead::AeadError;
17use crypto_provider::aes::cbc::DecryptionError;
18
19/// Encrypt message of length N with AES-CBC-256
20pub(crate) fn encrypt_cbc<
21 R: rand::Rng + rand::CryptoRng,
22 A: crypto_provider::aes::cbc::AesCbcPkcs7Padded,
23>(
24 key: &RawAes256Key,
25 message: &[u8],
26 rng: &mut R,
27) -> (Vec<u8>, AesCbcIv) {
28 let mut iv: AesCbcIv = [0u8; 16];
29 rng.fill_bytes(&mut iv);
30 let ciphertext = A::encrypt(&key[..].try_into().unwrap(), &iv, message);
31 (ciphertext, iv)
32}
33
34/// Decrypt message of length N with AES-CBC-256
35pub(crate) fn decrypt_cbc<A: crypto_provider::aes::cbc::AesCbcPkcs7Padded>(
36 key: &RawAes256Key,
37 ciphertext: &[u8],
38 iv: &AesCbcIv,
39) -> Result<Vec<u8>, DecryptionError> {
40 A::decrypt(&key[..].try_into().unwrap(), iv, ciphertext)
41}
42
43// TODO: Implement caching of these ciphers per connection so we don't recreate on each computation.
44pub(crate) fn encrypt_gcm_siv<
45 A: crypto_provider::aead::AesGcmSiv
46 + crypto_provider::aead::AeadInit<crypto_provider::aes::Aes256Key>,
47>(
48 key: &RawAes256Key,
49 plaintext: &[u8],
50 aad: &[u8],
51 nonce: &A::Nonce,
52) -> Result<Vec<u8>, AeadError> {
53 let converted_key = key.as_slice().try_into().unwrap();
54 let encrypter = A::new(&converted_key);
55 encrypter.encrypt(plaintext, aad, nonce)
56}
57
58pub(crate) fn decrypt_gcm_siv<
59 A: crypto_provider::aead::AesGcmSiv
60 + crypto_provider::aead::AeadInit<crypto_provider::aes::Aes256Key>,
61>(
62 key: &RawAes256Key,
63 ciphertext: &[u8],
64 aad: &[u8],
65 nonce: &A::Nonce,
66) -> Result<Vec<u8>, AeadError> {
67 let converted_key = key.as_slice().try_into().unwrap();
68 let decrypter = A::new(&converted_key);
69 decrypter.decrypt(ciphertext, aad, nonce)
70}