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
13 CBC implementation, encrypt block, Tom St Denis
22 @param ct [out] Ciphertext
23 @param len The number of bytes to process (must be multiple of block length)
25 @return CRYPT_OK if successful
27 int cbc_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, symmetric_CBC *cbc)
31 LTC_ARGCHK(pt != NULL);
32 LTC_ARGCHK(ct != NULL);
33 LTC_ARGCHK(cbc != NULL);
35 if ((err = cipher_is_valid(cbc->cipher)) != CRYPT_OK) {
39 /* is blocklen valid? */
40 if (cbc->blocklen < 1 || cbc->blocklen > (int)sizeof(cbc->IV)) {
41 return CRYPT_INVALID_ARG;
44 if (len % cbc->blocklen) {
45 return CRYPT_INVALID_ARG;
48 if (cbc->blocklen % sizeof(LTC_FAST_TYPE)) {
49 return CRYPT_INVALID_ARG;
53 if (cipher_descriptor[cbc->cipher].accel_cbc_encrypt != NULL) {
54 return cipher_descriptor[cbc->cipher].accel_cbc_encrypt(pt, ct, len / cbc->blocklen, cbc->IV, &cbc->key);
57 /* xor IV against plaintext */
59 for (x = 0; x < cbc->blocklen; x += sizeof(LTC_FAST_TYPE)) {
60 *(LTC_FAST_TYPE_PTR_CAST((unsigned char *)cbc->IV + x)) ^= *(LTC_FAST_TYPE_PTR_CAST((unsigned char *)pt + x));
63 for (x = 0; x < cbc->blocklen; x++) {
69 if ((err = cipher_descriptor[cbc->cipher].ecb_encrypt(cbc->IV, ct, &cbc->key)) != CRYPT_OK) {
73 /* store IV [ciphertext] for a future block */
75 for (x = 0; x < cbc->blocklen; x += sizeof(LTC_FAST_TYPE)) {
76 *(LTC_FAST_TYPE_PTR_CAST((unsigned char *)cbc->IV + x)) = *(LTC_FAST_TYPE_PTR_CAST((unsigned char *)ct + x));
79 for (x = 0; x < cbc->blocklen; x++) {
94 /* ref: $Format:%D$ */
95 /* git commit: $Format:%H$ */
96 /* commit time: $Format:%ai$ */