1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4 
5 /**
6    @file copy_or_zeromem.c
7    Either copy or zero a block of memory in constant time, Steffen Jaeckel
8 */
9 
10 /**
11    Either copy or zero a block of memory in constant time
12    @param src    The source where to read from
13    @param dest   The destination where to write to
14    @param len    The length of the area to process (octets)
15    @param coz    Copy (on 0) Or Zero (> 0)
16 */
copy_or_zeromem(const unsigned char * src,unsigned char * dest,unsigned long len,int coz)17 void copy_or_zeromem(const unsigned char* src, unsigned char* dest, unsigned long len, int coz)
18 {
19    unsigned long y;
20 #ifdef LTC_FAST
21    unsigned long z;
22    LTC_FAST_TYPE fastMask = ~(LTC_FAST_TYPE)0; /* initialize fastMask at all ones */
23 #endif
24    unsigned char mask = 0xff; /* initialize mask at all ones */
25 
26    LTC_ARGCHKVD(src  != NULL);
27    LTC_ARGCHKVD(dest != NULL);
28 
29    if (coz != 0) coz = 1;
30    y = 0;
31    mask *= 1 - coz; /* mask = ( coz ? 0 : 0xff ) */
32 #ifdef LTC_FAST
33    fastMask *= 1 - coz;
34    if (len & ~15) {
35       for (; y < (len & ~15); y += 16) {
36         for (z = 0; z < 16; z += sizeof(LTC_FAST_TYPE)) {
37           *(LTC_FAST_TYPE_PTR_CAST(&dest[y+z])) = *(LTC_FAST_TYPE_PTR_CAST(&src[y+z])) & fastMask;
38         }
39       }
40    }
41 #endif
42    for (; y < len; y++) {
43       dest[y] = src[y] & mask;
44    }
45 #ifdef LTC_CLEAN_STACK
46 #ifdef LTC_FAST
47    fastMask = 0;
48 #endif
49    mask = 0;
50 #endif
51 }
52