xref: /OK3568_Linux_fs/external/security/librkcrypto/test/c_mode/sm4_cfb.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "sm4_core.h"
5 
rk_crypto_cfb128_encrypt(void * ctx,const unsigned char * in,unsigned char * out,size_t len,unsigned char ivec[SM4_BLOCK_SIZE],int * num,int enc,block128_f block)6 void rk_crypto_cfb128_encrypt(void *ctx, const unsigned char *in, unsigned char *out,
7 			size_t len, unsigned char ivec[SM4_BLOCK_SIZE], int *num,
8 			int enc, block128_f block)
9 {
10     unsigned int n;
11     size_t l = 0;
12 
13     n = *num;
14     if (enc) {
15 
16 	while (l<len) {
17 		if (n == 0) {
18 			(*block)(ivec, ivec, ctx);
19 		}
20 		out[l] = ivec[n] ^= in[l];
21 		++l;
22 		n = (n+1) % SM4_BLOCK_SIZE;
23 	}
24 	*num = n;
25     } else {
26 	while (l<len) {
27 		unsigned char c;
28 		if (n == 0) {
29 			(*block)(ivec, ivec, ctx);
30 		}
31 		out[l] = ivec[n] ^ (c = in[l]); ivec[n] = c;
32 		++l;
33 		n = (n+1) % SM4_BLOCK_SIZE;
34 	}
35 	*num=n;
36     }
37 }
38 
rk_sm4_cfb_encrypt(const unsigned char * in,unsigned char * out,unsigned long length,const unsigned char * key,const int key_len,unsigned char * ivec,const int enc)39 int rk_sm4_cfb_encrypt(const unsigned char *in, unsigned char *out,
40         unsigned long length, const unsigned char *key, const int key_len,
41         unsigned char *ivec, const int enc)
42 {
43 	sm4_context  ctx;
44 	int num = 0;
45 
46 	if (in == NULL || out ==NULL || key == NULL)
47 		return -1;
48 
49 	if (key_len != 16)
50 		return -2;
51 
52 	if(length == 0)
53 		return -3;
54 
55 	rk_sm4_setkey_enc(&ctx, key);
56 
57 	rk_crypto_cfb128_encrypt((void *)&ctx, in, out,length, ivec,
58 				&num,enc, rk_rk_sm4_crypt_ecb);
59 	return 0;
60 }
61 
62 
63