3 This file is part of the ARM-Crypto-Lib.
4 Copyright (C) 2006-2010 Daniel Otte (daniel.otte@rub.de)
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "bcal-basic.h"
27 static void increment_be(void* block, uint8_t size_B){
31 c += ((uint8_t*)block)[size_B];
32 ((uint8_t*)block)[size_B] = (uint8_t)c;
37 uint8_t bcal_ctr_init(const bcdesc_t* desc, const void* key, uint16_t keysize_b, inc_fp_t inc_func, bcal_ctr_ctx_t* ctx){
38 ctx->desc = (bcdesc_t*)desc;
40 ctx->inc_func = inc_func;
42 ctx->inc_func = increment_be;
44 ctx->blocksize_B = (bcal_cipher_getBlocksize_b(desc)+7)/8;
45 ctx->in_block=malloc(ctx->blocksize_B);
46 if(ctx->in_block==NULL){
49 return bcal_cipher_init(desc, key, keysize_b, &(ctx->cctx));
52 void bcal_ctr_free(bcal_ctr_ctx_t* ctx){
54 bcal_cipher_free(&(ctx->cctx));
57 void bcal_ctr_loadIV(const void* iv, bcal_ctr_ctx_t* ctx){
59 memcpy(ctx->in_block, iv, ctx->blocksize_B);
63 void bcal_ctr_encNext(void* block, bcal_ctr_ctx_t* ctx){
64 uint8_t tmp[ctx->blocksize_B];
65 memcpy(tmp, ctx->in_block, ctx->blocksize_B);
66 bcal_cipher_enc(tmp, &(ctx->cctx));
67 memxor(block, tmp, ctx->blocksize_B);
68 ctx->inc_func(ctx->in_block, ctx->blocksize_B);
71 void bcal_ctr_decNext(void* block, bcal_ctr_ctx_t* ctx){
72 bcal_ctr_encNext(block, ctx);
75 void bcal_ctr_encMsg(const void* iv, void* msg, uint32_t msg_len_b, bcal_ctr_ctx_t* ctx){
76 bcal_ctr_loadIV(iv, ctx);
78 blocksize_b = ctx->blocksize_B*8;
79 while(msg_len_b>blocksize_b){
80 bcal_ctr_encNext(msg, ctx);
81 msg_len_b -= blocksize_b;
82 msg = (uint8_t*)msg + ctx->blocksize_B;
84 uint8_t tmp[ctx->blocksize_B];
85 memcpy(tmp, ctx->in_block, ctx->blocksize_B);
86 bcal_cipher_enc(tmp, &(ctx->cctx));
87 ctx->inc_func(ctx->in_block, ctx->blocksize_B);
88 tmp[msg_len_b/8] = 0xff00>>(msg_len_b&7);
89 memxor(msg, tmp, (msg_len_b+7)/8);
92 void bcal_ctr_decMsg(const void* iv, void* msg, uint32_t msg_len_b, bcal_ctr_ctx_t* ctx){
93 bcal_ctr_encMsg(iv, msg, msg_len_b, ctx);