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
69pub(super) fn decrypt_cbc_mode<'in_out>(
70    key: &SymmetricCipherKey,
71    context: DecryptionContext,
72    in_out: &'in_out mut [u8],
73) -> Result<&'in_out mut [u8], Unspecified> {
74    let iv_bytes: &[u8] = (&context).try_into()?;
75    let mut iv = [0u8; DES_CBC_IV_LEN];
76    iv.copy_from_slice(iv_bytes);
77
78    match key {
79        SymmetricCipherKey::Des { key } => {
80            des_cbc_encrypt(&key.0[0], &mut iv, in_out, DES_DECRYPT);
81        }
82        SymmetricCipherKey::DesEde { key } | SymmetricCipherKey::DesEde3 { key } => {
83            des3_cbc_encrypt(
84                &key.0[0],
85                &key.0[1],
86                &key.0[2],
87                &mut iv,
88                in_out,
89                DES_DECRYPT,
90            );
91        }
92        _ => unreachable!(),
93    }
94
95    iv.zeroize();
96    Ok(in_out)
97}
98
99pub(super) fn encrypt_ecb_mode(
100    key: &SymmetricCipherKey,
101    context: EncryptionContext,
102    in_out: &mut [u8],
103) -> Result<DecryptionContext, Unspecified> {
104    if !matches!(context, EncryptionContext::None) {
105        unreachable!();
106    }
107
108    let mut in_out_iter = in_out.chunks_exact_mut(DES_BLOCK_LEN);
109    match key {
110        SymmetricCipherKey::Des { key } => {
111            for block in in_out_iter.by_ref() {
112                des_ecb_encrypt(&key.0[0], block, DES_ENCRYPT);
113            }
114        }
115        SymmetricCipherKey::DesEde { key } | SymmetricCipherKey::DesEde3 { key } => {
116            for block in in_out_iter.by_ref() {
117                des3_ecb_encrypt(&key.0[0], &key.0[1], &key.0[2], block, DES_ENCRYPT);
118            }
119        }
120        _ => unreachable!(),
121    }
122    // Sanity check: `encrypt` validates that `in_out.len() % block_len == 0`
123    // for ECB mode before dispatching here.
124    debug_assert!(in_out_iter.into_remainder().is_empty());
125
126    Ok(context.into())
127}
128
129pub(super) fn decrypt_ecb_mode<'in_out>(
130    key: &SymmetricCipherKey,
131    context: DecryptionContext,
132    in_out: &'in_out mut [u8],
133) -> Result<&'in_out mut [u8], Unspecified> {
134    if !matches!(context, DecryptionContext::None) {
135        unreachable!();
136    }
137
138    // The inner scope ends the mutable borrow of `in_out` held by
139    // `in_out_iter` before we return `Ok(in_out)` below. `into_remainder()`
140    // would also consume the iterator and release the borrow, but it's inside
141    // a `debug_assert!` and therefore not evaluated in release builds, so we
142    // can't rely on it for that purpose. `encrypt_ecb_mode` doesn't need this
143    // scope because it doesn't return `in_out`.
144    {
145        let mut in_out_iter = in_out.chunks_exact_mut(DES_BLOCK_LEN);
146        match key {
147            SymmetricCipherKey::Des { key } => {
148                for block in in_out_iter.by_ref() {
149                    des_ecb_encrypt(&key.0[0], block, DES_DECRYPT);
150                }
151            }
152            SymmetricCipherKey::DesEde { key } | SymmetricCipherKey::DesEde3 { key } => {
153                for block in in_out_iter.by_ref() {
154                    des3_ecb_encrypt(&key.0[0], &key.0[1], &key.0[2], block, DES_DECRYPT);
155                }
156            }
157            _ => unreachable!(),
158        }
159        // Sanity check: `decrypt` validates that `in_out.len() % block_len == 0`
160        // for ECB mode before dispatching here.
161        debug_assert!(in_out_iter.into_remainder().is_empty());
162    }
163
164    Ok(in_out)
165}
166
167fn des3_cbc_encrypt(
168    ks1: &DES_key_schedule,
169    ks2: &DES_key_schedule,
170    ks3: &DES_key_schedule,
171    iv: &mut [u8; DES_CBC_IV_LEN],
172    in_out: &mut [u8],
173    enc: i32,
174) {
175    // The caller (`encrypt`/`decrypt` in cipher.rs) validates block alignment
176    // for CBC mode; assert here as a safety net.
177    debug_assert_eq!(in_out.len() % DES_BLOCK_LEN, 0);
178
179    // DES is not FIPS-approved; `indicator_check!` will observe that the
180    // underlying call does not increment the approved-operation counter and
181    // correctly mark the service indicator as unapproved in FIPS builds.
182    //
183    // SAFETY: `DES_ede3_cbc_encrypt` supports in-place operation (in == out).
184    indicator_check!(unsafe {
185        DES_ede3_cbc_encrypt(
186            in_out.as_ptr(),
187            in_out.as_mut_ptr(),
188            in_out.len(),
189            ks1,
190            ks2,
191            ks3,
192            iv.as_mut_ptr() as *mut DES_cblock,
193            enc,
194        );
195    });
196}
197
198fn des3_ecb_encrypt(
199    ks1: &DES_key_schedule,
200    ks2: &DES_key_schedule,
201    ks3: &DES_key_schedule,
202    block: &mut [u8],
203    enc: i32,
204) {
205    let input_block = block.as_ptr() as *const DES_cblock;
206    let output_block = block.as_mut_ptr() as *mut DES_cblock;
207    // DES is not FIPS-approved; `indicator_check!` will observe that the
208    // underlying call does not increment the approved-operation counter and
209    // correctly mark the service indicator as unapproved in FIPS builds.
210    //
211    // SAFETY: `input_block` and `output_block` point to the same allocation;
212    // `DES_ecb3_encrypt` supports in-place operation.
213    indicator_check!(unsafe {
214        DES_ecb3_encrypt(input_block, output_block, ks1, ks2, ks3, enc);
215    });
216}
217
218fn des_cbc_encrypt(
219    ks: &DES_key_schedule,
220    iv: &mut [u8; DES_CBC_IV_LEN],
221    in_out: &mut [u8],
222    enc: i32,
223) {
224    // The caller (`encrypt`/`decrypt` in cipher.rs) validates block alignment
225    // for CBC mode; assert here as a safety net.
226    debug_assert_eq!(in_out.len() % DES_BLOCK_LEN, 0);
227
228    // DES is not FIPS-approved; `indicator_check!` will observe that the
229    // underlying call does not increment the approved-operation counter and
230    // correctly mark the service indicator as unapproved in FIPS builds.
231    //
232    // SAFETY: `DES_ncbc_encrypt` supports in-place operation (in == out).
233    indicator_check!(unsafe {
234        DES_ncbc_encrypt(
235            in_out.as_ptr(),
236            in_out.as_mut_ptr(),
237            in_out.len(),
238            ks,
239            iv.as_mut_ptr() as *mut DES_cblock,
240            enc,
241        );
242    });
243}
244
245fn des_ecb_encrypt(ks: &DES_key_schedule, block: &mut [u8], enc: i32) {
246    let input_block = block.as_ptr() as *const DES_cblock;
247    let output_block = block.as_mut_ptr() as *mut DES_cblock;
248    // DES is not FIPS-approved; `indicator_check!` will observe that the
249    // underlying call does not increment the approved-operation counter and
250    // correctly mark the service indicator as unapproved in FIPS builds.
251    //
252    // SAFETY: `input_block` and `output_block` point to the same allocation;
253    // `DES_ecb_encrypt` supports in-place operation.
254    indicator_check!(unsafe {
255        DES_ecb_encrypt(input_block, output_block, ks, enc);
256    });
257}