1
/* LibTomCrypt, modular cryptographic library -- Tom St Denis
3
* LibTomCrypt is a library that provides various cryptographic
4
* algorithms in a highly modular and flexible manner.
6
* The library is free for all purposes without any express
9
* Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.org
15
CTR implementation, encrypt data, Tom St Denis
24
@param ct [out] Ciphertext
25
@param len Length of plaintext (octets)
27
@return CRYPT_OK if successful
29
int ctr_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CTR *ctr)
33
LTC_ARGCHK(pt != NULL);
34
LTC_ARGCHK(ct != NULL);
35
LTC_ARGCHK(ctr != NULL);
37
if ((err = cipher_is_valid(ctr->cipher)) != CRYPT_OK) {
41
/* is blocklen/padlen valid? */
42
if (ctr->blocklen < 0 || ctr->blocklen > (int)sizeof(ctr->ctr) ||
43
ctr->padlen < 0 || ctr->padlen > (int)sizeof(ctr->pad)) {
44
return CRYPT_INVALID_ARG;
48
if (ctr->blocklen % sizeof(LTC_FAST_TYPE)) {
49
return CRYPT_INVALID_ARG;
53
/* handle acceleration only if pad is empty, accelerator is present and length is >= a block size */
54
if ((ctr->padlen == ctr->blocklen) && cipher_descriptor[ctr->cipher].accel_ctr_encrypt != NULL && (len >= (unsigned long)ctr->blocklen)) {
55
cipher_descriptor[ctr->cipher].accel_ctr_encrypt(pt, ct, len/ctr->blocklen, ctr->ctr, ctr->mode, &ctr->key);
60
/* is the pad empty? */
61
if (ctr->padlen == ctr->blocklen) {
62
/* increment counter */
63
if (ctr->mode == CTR_COUNTER_LITTLE_ENDIAN) {
65
for (x = 0; x < ctr->blocklen; x++) {
66
ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255;
67
if (ctr->ctr[x] != (unsigned char)0) {
73
for (x = ctr->blocklen-1; x >= 0; x--) {
74
ctr->ctr[x] = (ctr->ctr[x] + (unsigned char)1) & (unsigned char)255;
75
if (ctr->ctr[x] != (unsigned char)0) {
82
cipher_descriptor[ctr->cipher].ecb_encrypt(ctr->ctr, ctr->pad, &ctr->key);
86
if (ctr->padlen == 0 && len >= (unsigned long)ctr->blocklen) {
87
for (x = 0; x < ctr->blocklen; x += sizeof(LTC_FAST_TYPE)) {
88
*((LTC_FAST_TYPE*)((unsigned char *)ct + x)) = *((LTC_FAST_TYPE*)((unsigned char *)pt + x)) ^
89
*((LTC_FAST_TYPE*)((unsigned char *)ctr->pad + x));
94
ctr->padlen = ctr->blocklen;
98
*ct++ = *pt++ ^ ctr->pad[ctr->padlen++];
106
/* $Source: /cvs/libtom/libtomcrypt/src/modes/ctr/ctr_encrypt.c,v $ */
107
/* $Revision: 1.13 $ */
108
/* $Date: 2005/05/05 14:35:59 $ */