Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/fipsmodule/modes/cbc.c

raw
1 // Copyright (c) 2008 The OpenSSL Project. All rights reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 #include <assert.h>
5 #include <string.h>
6
7 #include <openssl/type_check.h>
8
9 #include "internal.h"
10 #include "../../internal.h"
11
12
13 void CRYPTO_cbc128_encrypt(const uint8_t *in, uint8_t *out, size_t len,
14 const AES_KEY *key, uint8_t ivec[16],
15 block128_f block) {
16 assert(key != NULL && ivec != NULL);
17 if (len == 0) {
18 // Avoid |ivec| == |iv| in the |memcpy| below, which is not legal in C.
19 return;
20 }
21
22 assert(in != NULL && out != NULL);
23 size_t n;
24 const uint8_t *iv = ivec;
25 while (len >= 16) {
26 CRYPTO_xor16(out, in, iv);
27 (*block)(out, out, key);
28 iv = out;
29 len -= 16;
30 in += 16;
31 out += 16;
32 }
33
34 if (len > 0) {
35 for (n = 0; n < 16 && n < len; ++n) {
36 out[n] = in[n] ^ iv[n];
37 }
38 for (; n < 16; ++n) {
39 out[n] = iv[n];
40 }
41 (*block)(out, out, key);
42 iv = out;
43 }
44
45 OPENSSL_memcpy(ivec, iv, 16);
46 }
47
48 void CRYPTO_cbc128_decrypt(const uint8_t *in, uint8_t *out, size_t len,
49 const AES_KEY *key, uint8_t ivec[16],
50 block128_f block) {
51 assert(key != NULL && ivec != NULL);
52 if (len == 0) {
53 // Avoid |ivec| == |iv| in the |memcpy| below, which is not legal in C.
54 return;
55 }
56
57 assert(in != NULL && out != NULL);
58
59 const uintptr_t inptr = (uintptr_t) in;
60 const uintptr_t outptr = (uintptr_t) out;
61 // If |in| and |out| alias, |in| must be ahead.
62 assert(inptr >= outptr || inptr + len <= outptr);
63
64 size_t n;
65 alignas(16) uint8_t tmp[16];
66 if ((inptr >= 32 && outptr <= inptr - 32) || inptr < outptr) {
67 // If |out| is at least two blocks behind |in| or completely disjoint, there
68 // is no need to decrypt to a temporary block.
69 const uint8_t *iv = ivec;
70 while (len >= 16) {
71 (*block)(in, out, key);
72 CRYPTO_xor16(out, out, iv);
73 iv = in;
74 len -= 16;
75 in += 16;
76 out += 16;
77 }
78 OPENSSL_memcpy(ivec, iv, 16);
79 } else {
80 OPENSSL_STATIC_ASSERT(16 % sizeof(crypto_word_t) == 0,
81 block_cannot_be_evenly_divided_into_crypto_word_t)
82
83 while (len >= 16) {
84 (*block)(in, tmp, key);
85 for (n = 0; n < 16; n += sizeof(crypto_word_t)) {
86 crypto_word_t c = CRYPTO_load_word_le(in + n);
87 CRYPTO_store_word_le(out + n, CRYPTO_load_word_le(tmp + n) ^
88 CRYPTO_load_word_le(ivec + n));
89 CRYPTO_store_word_le(ivec + n, c);
90 }
91 len -= 16;
92 in += 16;
93 out += 16;
94 }
95 }
96
97 while (len) {
98 uint8_t c;
99 (*block)(in, tmp, key);
100 for (n = 0; n < 16 && n < len; ++n) {
101 c = in[n];
102 out[n] = tmp[n] ^ ivec[n];
103 ivec[n] = c;
104 }
105 if (len <= 16) {
106 for (; n < 16; ++n) {
107 ivec[n] = in[n];
108 }
109 break;
110 }
111 len -= 16;
112 in += 16;
113 out += 16;
114 }
115 }