5 int cbc_start(int cipher, const unsigned char *IV, const unsigned char *key,
6 int keylen, int num_rounds, symmetric_CBC *cbc)
15 if ((err = cipher_is_valid(cipher)) != CRYPT_OK) {
20 if ((err = cipher_descriptor[cipher].setup(key, keylen, num_rounds, &cbc->key)) != CRYPT_OK) {
25 cbc->blocklen = cipher_descriptor[cipher].block_length;
27 for (x = 0; x < cbc->blocklen; x++) {
33 int cbc_encrypt(const unsigned char *pt, unsigned char *ct, symmetric_CBC *cbc)
36 unsigned char tmp[MAXBLOCKSIZE];
42 if ((err = cipher_is_valid(cbc->cipher)) != CRYPT_OK) {
46 /* is blocklen valid? */
47 if (cbc->blocklen < 0 || cbc->blocklen > (int)sizeof(cbc->IV)) {
48 return CRYPT_INVALID_ARG;
51 /* xor IV against plaintext */
52 for (x = 0; x < cbc->blocklen; x++) {
53 tmp[x] = pt[x] ^ cbc->IV[x];
57 cipher_descriptor[cbc->cipher].ecb_encrypt(tmp, ct, &cbc->key);
59 /* store IV [ciphertext] for a future block */
60 for (x = 0; x < cbc->blocklen; x++) {
65 zeromem(tmp, sizeof(tmp));
70 int cbc_decrypt(const unsigned char *ct, unsigned char *pt, symmetric_CBC *cbc)
73 unsigned char tmp[MAXBLOCKSIZE], tmp2[MAXBLOCKSIZE];
79 /* decrypt the block from ct into tmp */
80 if ((err = cipher_is_valid(cbc->cipher)) != CRYPT_OK) {
83 cipher_descriptor[cbc->cipher].ecb_decrypt(ct, tmp, &cbc->key);
85 /* is blocklen valid? */
86 if (cbc->blocklen < 0 || cbc->blocklen > (int)sizeof(cbc->IV)) {
87 return CRYPT_INVALID_ARG;
90 /* xor IV against the plaintext of the previous step */
91 for (x = 0; x < cbc->blocklen; x++) {
92 /* copy CT in case ct == pt */
95 /* actually decrypt the byte */
96 pt[x] = tmp[x] ^ cbc->IV[x];
99 /* replace IV with this current ciphertext */
100 for (x = 0; x < cbc->blocklen; x++) {
101 cbc->IV[x] = tmp2[x];
104 zeromem(tmp, sizeof(tmp));
105 zeromem(tmp2, sizeof(tmp2));