Skip to main content

aws_lc_rs/cipher/
des.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0 OR ISC
3
4use crate::aws_lc::{
5    DES_cblock, DES_ecb3_encrypt, DES_ecb_encrypt, DES_ede3_cbc_encrypt, DES_key_schedule,
6    DES_ncbc_encrypt, DES_DECRYPT, DES_ENCRYPT,
7};
8use crate::error::Unspecified;
9use crate::fips::indicator_check;
10use zeroize::Zeroize;
11
12use super::{DecryptionContext, EncryptionContext, SymmetricCipherKey};
13
14/// Length of a single DES key in bytes.
15pub const DES_KEY_LEN: usize = 8;
16
17/// Length of a 2TDEA (DES-EDE) key in bytes.
18pub const DES_EDE_KEY_LEN: usize = 16;
19
20/// Length of a 3TDEA (DES-EDE3) key in bytes.
21pub const DES_EDE3_KEY_LEN: usize = 24;
22
23/// The number of bytes for a DES/3DES-CBC initialization vector (IV).
24pub const DES_CBC_IV_LEN: usize = 8;
25
26pub(crate) const DES_BLOCK_LEN: usize = 8;
27
28// `#[repr(transparent)]` documents that `DesKey` has the same layout as the
29// wrapped array, which the `Drop` impl in `key.rs` relies on when it zeroizes
30// the key schedule bytes through a byte-slice view.
31//
32// The array is sized for 3TDEA and is used unchanged for single DES (slot 0
33// populated, slots 1 and 2 zeroed) and 2TDEA (slots 0 and 1 populated, slot 2 =
34// slot 0 per K3 == K1). Callers in this module match on `SymmetricCipherKey`
35// and read only the slots that are meaningful for the variant.
36#[repr(transparent)]
37pub(crate) struct DesKey(pub(super) [DES_key_schedule; 3]);
38
39pub(super) fn encrypt_cbc_mode(
40    key: &SymmetricCipherKey,
41    context: EncryptionContext,
42    in_out: &mut [u8],
43) -> Result<DecryptionContext, Unspecified> {
44    let iv_bytes: &[u8] = (&context).try_into()?;
45    let mut iv = [0u8; DES_CBC_IV_LEN];
46    iv.copy_from_slice(iv_bytes);
47
48    match key {
49        SymmetricCipherKey::Des { key } => {
50            des_cbc_encrypt(&key.0[0], &mut iv, in_out, DES_ENCRYPT);
51        }
52        SymmetricCipherKey::DesEde { key } | SymmetricCipherKey::DesEde3 { key } => {
53            des3_cbc_encrypt(
54                &key.0[0],
55                &key.0[1],
56                &key.0[2],
57                &mut iv,
58                in_out,
59                DES_ENCRYPT,
60            );
61        }
62        _ => unreachable!(),
63    }
64
65    iv.zeroize();
66    Ok(context.into())
67}
68
69#[allow(clippy::needless_pass_by_value)]
70pub(super) fn decrypt_cbc_mode<'in_out>(
71    key: &SymmetricCipherKey,
72    context: DecryptionContext,
73    in_out: &'in_out mut [u8],
74) -> Result<&'in_out mut [u8], Unspecified> {
75    let iv_bytes: &[u8] = (&context).try_into()?;
76    let mut iv = [0u8; DES_CBC_IV_LEN];
77    iv.copy_from_slice(iv_bytes);
78
79    match key {
80        SymmetricCipherKey::Des { key } => {
81            des_cbc_encrypt(&key.0[0], &mut iv, in_out, DES_DECRYPT);
82        }
83        SymmetricCipherKey::DesEde { key } | SymmetricCipherKey::DesEde3 { key } => {
84            des3_cbc_encrypt(
85                &key.0[0],
86                &key.0[1],
87                &key.0[2],
88                &mut iv,
89                in_out,
90                DES_DECRYPT,
91            );
92        }
93        _ => unreachable!(),
94    }
95
96    iv.zeroize();
97    Ok(in_out)
98}
99
100pub(super) fn encrypt_ecb_mode(
101    key: &SymmetricCipherKey,
102    context: EncryptionContext,
103    in_out: &mut [u8],
104) -> Result<DecryptionContext, Unspecified> {
105    if !matches!(context, EncryptionContext::None) {
106        return Err(Unspecified);
107    }
108
109    let mut in_out_iter = in_out.chunks_exact_mut(DES_BLOCK_LEN);
110    match key {
111        SymmetricCipherKey::Des { key } => {
112            for block in in_out_iter.by_ref() {
113                des_ecb_encrypt(&key.0[0], block, DES_ENCRYPT);
114            }
115        }
116        SymmetricCipherKey::DesEde { key } | SymmetricCipherKey::DesEde3 { key } => {
117            for block in in_out_iter.by_ref() {
118                des3_ecb_encrypt(&key.0[0], &key.0[1], &key.0[2], block, DES_ENCRYPT);
119            }
120        }
121        _ => unreachable!(),
122    }
123    // Sanity check: `encrypt` validates that `in_out.len() % block_len == 0`
124    // for ECB mode before dispatching here.
125    debug_assert_eq!(in_out_iter.into_remainder(), []);
126
127    Ok(context.into())
128}
129
130#[allow(clippy::needless_pass_by_value)]
131pub(super) fn decrypt_ecb_mode<'in_out>(
132    key: &SymmetricCipherKey,
133    context: DecryptionContext,
134    in_out: &'in_out mut [u8],
135) -> Result<&'in_out mut [u8], Unspecified> {
136    if !matches!(context, DecryptionContext::None) {
137        return Err(Unspecified);
138    }
139
140    // The inner scope ends the mutable borrow of `in_out` held by
141    // `in_out_iter` before we return `Ok(in_out)` below. `into_remainder()`
142    // would also consume the iterator and release the borrow, but it's inside
143    // a `debug_assert_eq!` and therefore not evaluated in release builds, so we
144    // can't rely on it for that purpose. `encrypt_ecb_mode` doesn't need this
145    // scope because it doesn't return `in_out`.
146    {
147        let mut in_out_iter = in_out.chunks_exact_mut(DES_BLOCK_LEN);
148        match key {
149            SymmetricCipherKey::Des { key } => {
150                for block in in_out_iter.by_ref() {
151                    des_ecb_encrypt(&key.0[0], block, DES_DECRYPT);
152                }
153            }
154            SymmetricCipherKey::DesEde { key } | SymmetricCipherKey::DesEde3 { key } => {
155                for block in in_out_iter.by_ref() {
156                    des3_ecb_encrypt(&key.0[0], &key.0[1], &key.0[2], block, DES_DECRYPT);
157                }
158            }
159            _ => unreachable!(),
160        }
161        // Sanity check: `decrypt` validates that `in_out.len() % block_len == 0`
162        // for ECB mode before dispatching here.
163        debug_assert_eq!(in_out_iter.into_remainder(), []);
164    }
165
166    Ok(in_out)
167}
168
169fn des3_cbc_encrypt(
170    ks1: &DES_key_schedule,
171    ks2: &DES_key_schedule,
172    ks3: &DES_key_schedule,
173    iv: &mut [u8; DES_CBC_IV_LEN],
174    in_out: &mut [u8],
175    enc: i32,
176) {
177    // The caller (`encrypt`/`decrypt` in cipher.rs) validates block alignment
178    // for CBC mode; assert here as a safety net.
179    debug_assert_eq!(in_out.len() % DES_BLOCK_LEN, 0);
180
181    // DES is not FIPS-approved; `indicator_check!` will observe that the
182    // underlying call does not increment the approved-operation counter and
183    // correctly mark the service indicator as unapproved in FIPS builds.
184    //
185    // SAFETY: `DES_ede3_cbc_encrypt` supports in-place operation (in == out).
186    indicator_check!(unsafe {
187        DES_ede3_cbc_encrypt(
188            in_out.as_ptr(),
189            in_out.as_mut_ptr(),
190            in_out.len(),
191            ks1,
192            ks2,
193            ks3,
194            iv.as_mut_ptr().cast::<DES_cblock>(),
195            enc,
196        );
197    });
198}
199
200fn des3_ecb_encrypt(
201    ks1: &DES_key_schedule,
202    ks2: &DES_key_schedule,
203    ks3: &DES_key_schedule,
204    block: &mut [u8],
205    enc: i32,
206) {
207    let input_block = block.as_ptr().cast::<DES_cblock>();
208    let output_block = block.as_mut_ptr().cast::<DES_cblock>();
209    // DES is not FIPS-approved; `indicator_check!` will observe that the
210    // underlying call does not increment the approved-operation counter and
211    // correctly mark the service indicator as unapproved in FIPS builds.
212    //
213    // SAFETY: `input_block` and `output_block` point to the same allocation;
214    // `DES_ecb3_encrypt` supports in-place operation.
215    indicator_check!(unsafe {
216        DES_ecb3_encrypt(input_block, output_block, ks1, ks2, ks3, enc);
217    });
218}
219
220fn des_cbc_encrypt(
221    ks: &DES_key_schedule,
222    iv: &mut [u8; DES_CBC_IV_LEN],
223    in_out: &mut [u8],
224    enc: i32,
225) {
226    // The caller (`encrypt`/`decrypt` in cipher.rs) validates block alignment
227    // for CBC mode; assert here as a safety net.
228    debug_assert_eq!(in_out.len() % DES_BLOCK_LEN, 0);
229
230    // DES is not FIPS-approved; `indicator_check!` will observe that the
231    // underlying call does not increment the approved-operation counter and
232    // correctly mark the service indicator as unapproved in FIPS builds.
233    //
234    // SAFETY: `DES_ncbc_encrypt` supports in-place operation (in == out).
235    indicator_check!(unsafe {
236        DES_ncbc_encrypt(
237            in_out.as_ptr(),
238            in_out.as_mut_ptr(),
239            in_out.len(),
240            ks,
241            iv.as_mut_ptr().cast::<DES_cblock>(),
242            enc,
243        );
244    });
245}
246
247fn des_ecb_encrypt(ks: &DES_key_schedule, block: &mut [u8], enc: i32) {
248    let input_block = block.as_ptr().cast::<DES_cblock>();
249    let output_block = block.as_mut_ptr().cast::<DES_cblock>();
250    // DES is not FIPS-approved; `indicator_check!` will observe that the
251    // underlying call does not increment the approved-operation counter and
252    // correctly mark the service indicator as unapproved in FIPS builds.
253    //
254    // SAFETY: `input_block` and `output_block` point to the same allocation;
255    // `DES_ecb_encrypt` supports in-place operation.
256    indicator_check!(unsafe {
257        DES_ecb_encrypt(input_block, output_block, ks, enc);
258    });
259}