1 // SPDX-License-Identifier: BSD-2-Clause
2 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3  *
4  * LibTomCrypt is a library that provides various cryptographic
5  * algorithms in a highly modular and flexible manner.
6  *
7  * The library is free for all purposes without any express
8  * guarantee it works.
9  */
10 #include "tomcrypt_private.h"
11 
12 /**
13    @file copy_or_zeromem.c
14    Either copy or zero a block of memory in constant time, Steffen Jaeckel
15 */
16 
17 /**
18    Either copy or zero a block of memory in constant time
19    @param src    The source where to read from
20    @param dest   The destination where to write to
21    @param len    The length of the area to process (octets)
22    @param coz    Copy (on 0) Or Zero (> 0)
23 */
copy_or_zeromem(const unsigned char * src,unsigned char * dest,unsigned long len,int coz)24 void copy_or_zeromem(const unsigned char* src, unsigned char* dest, unsigned long len, int coz)
25 {
26    unsigned long y;
27 #ifdef LTC_FAST
28    unsigned long z;
29    LTC_FAST_TYPE fastMask = ~(LTC_FAST_TYPE)0; /* initialize fastMask at all ones */
30 #endif
31    unsigned char mask = 0xff; /* initialize mask at all ones */
32 
33    LTC_ARGCHKVD(src  != NULL);
34    LTC_ARGCHKVD(dest != NULL);
35 
36    if (coz != 0) coz = 1;
37    y = 0;
38    mask *= 1 - coz; /* mask = ( coz ? 0 : 0xff ) */
39 #ifdef LTC_FAST
40    fastMask *= 1 - coz;
41    if (len & ~15) {
42       for (; y < (len & ~15); y += 16) {
43         for (z = 0; z < 16; z += sizeof(LTC_FAST_TYPE)) {
44           *(LTC_FAST_TYPE_PTR_CAST(&dest[y+z])) = *(LTC_FAST_TYPE_PTR_CAST(&src[y+z])) & fastMask;
45         }
46       }
47    }
48 #endif
49    for (; y < len; y++) {
50       dest[y] = src[y] & mask;
51    }
52 #ifdef LTC_CLEAN_STACK
53 #ifdef LTC_FAST
54    fastMask = 0;
55 #endif
56    mask = 0;
57 #endif
58 }
59 
60 /* ref:         $Format:%D$ */
61 /* git commit:  $Format:%H$ */
62 /* commit time: $Format:%ai$ */
63