xref: /OK3568_Linux_fs/external/security/librkcrypto/test/c_mode/aes_ctr.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <assert.h>
5 #include "aes_core.h"
6 
rk_init_ctr(struct ctr_state * state,const unsigned char * iv)7 static void rk_init_ctr(struct ctr_state * state, const unsigned char *iv)
8 {
9 	state->num = 0;
10 	memset(state->ecount, 0, 16);
11 	memcpy(state->ivec, iv, 16);
12 }
13 
14 /* increment counter (128-bit int) by 1 */
rk_ctr128_inc(unsigned char * counter)15 static void rk_ctr128_inc(unsigned char *counter) {
16 	unsigned int n=16;
17 	unsigned char  c;
18 
19 	do {
20 		--n;
21 		c = counter[n];
22 		++c;
23 		counter[n] = c;
24 		if (c) return;
25 	} while (n);
26 }
27 
rk_crypto_ctr128_encrypt(const unsigned char * in,unsigned char * out,int len,const void * key,unsigned char * ivec,unsigned char * ecount_buf,unsigned int * num)28 static void rk_crypto_ctr128_encrypt(const unsigned char *in, unsigned char *out,
29 			int len, const void *key, unsigned char *ivec, unsigned char *ecount_buf,
30 			unsigned int *num)
31 {
32 	int n, l=0;
33 
34 	n = *num;
35 	while (l<len) {
36 		if (n==0) {
37 			rk_aes_encrypt(ivec, ecount_buf, key);
38  			rk_ctr128_inc(ivec);
39 		}
40 		out[l] = in[l] ^ ecount_buf[n];
41 		++l;
42 		n = (n+1) % 16;
43 	}
44 
45 	*num = n;
46 }
47 
48 /* XTS makes use of two different keys, usually generated by splitting
49  * the supplied block cipher's key in half.
50  * Because of the splitting, users wanting AES 256 and AES 128 encryption
51  * will need to choose key sizes of 512 bits and 256 bits respectively.
52  */
rk_aes_ctr_encrypt(const unsigned char * in,unsigned char * out,unsigned long length,const unsigned char * key,const int key_len,const unsigned char * ivec,const int enc)53 int rk_aes_ctr_encrypt(const unsigned char *in, unsigned char *out,
54         unsigned long length, const unsigned char *key, const int key_len,
55         const unsigned char *ivec, const int enc)
56 {
57 	RK_AES_KEY ks;
58 	struct ctr_state state;
59 
60 	if(key_len != 16 && key_len != 24 && key_len != 32)
61 		return -1;
62 
63 	rk_init_ctr(&state, ivec);
64 	rk_aes_set_encrypt_key(key, key_len * 8, &ks);
65 	rk_crypto_ctr128_encrypt(in, out, length, &ks, state.ivec, state.ecount, &state.num);
66 
67 	return 0;
68 }
69 
70 
71