1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include "sm4_core.h"
5
rk_crypto_cbc128_encrypt(void * ctx,const unsigned char * in,unsigned char * out,unsigned int len,unsigned char * ivec,block128_f block)6 static void rk_crypto_cbc128_encrypt(void *ctx, const unsigned char *in, unsigned char *out,
7 unsigned int len, unsigned char *ivec, block128_f block)
8 {
9 unsigned int n;
10 const unsigned char *iv = ivec;
11
12 while (len) {
13 for(n=0; n<SM4_BLOCK_SIZE && n<len; ++n)
14 out[n] = in[n] ^ iv[n];
15 for(; n<SM4_BLOCK_SIZE; ++n)
16 out[n] = iv[n];
17 (*block)(out, out, ctx);
18 iv = out;
19 if (len<=SM4_BLOCK_SIZE) break;
20 len -= SM4_BLOCK_SIZE;
21 in += SM4_BLOCK_SIZE;
22 out += SM4_BLOCK_SIZE;
23 }
24 memcpy(ivec,iv,SM4_BLOCK_SIZE);
25 }
26
rk_crypto_cbc128_decrypt(void * ctx,const unsigned char * in,unsigned char * out,unsigned int len,unsigned char * ivec,block128_f block)27 static void rk_crypto_cbc128_decrypt(void *ctx, const unsigned char *in, unsigned char *out,
28 unsigned int len, unsigned char *ivec, block128_f block)
29 {
30 unsigned int n;
31 unsigned char c;
32 unsigned char tmp_buf[SM4_BLOCK_SIZE];
33
34 memset(tmp_buf, 0x00, sizeof(tmp_buf));
35
36 while (len) {
37 (*block)(in, tmp_buf, ctx);
38 for(n=0; n<SM4_BLOCK_SIZE && n<len; ++n) {
39 c = in[n];
40 out[n] = tmp_buf[n] ^ ivec[n];
41 ivec[n] = c;
42 }
43 if (len<=SM4_BLOCK_SIZE) {
44 for (; n<SM4_BLOCK_SIZE; ++n)
45 ivec[n] = in[n];
46 break;
47 }
48 len -= SM4_BLOCK_SIZE;
49 in += SM4_BLOCK_SIZE;
50 out += SM4_BLOCK_SIZE;
51 }
52
53 }
54
rk_sm4_cbc_encrypt(const unsigned char * in,unsigned char * out,unsigned int length,const unsigned char * key,const int key_len,unsigned char * ivec,const int enc)55 int rk_sm4_cbc_encrypt(const unsigned char *in, unsigned char *out,
56 unsigned int length, const unsigned char *key, const int key_len,
57 unsigned char *ivec, const int enc)
58 {
59 sm4_context ctx;
60
61 if(key_len != 16)
62 return -1;
63
64 if(length%SM4_BLOCK_SIZE || length == 0)
65 return -1;
66
67 if (enc) {
68 rk_sm4_setkey_enc(&ctx, key);
69 rk_crypto_cbc128_encrypt((void*)&ctx, in, out, length, ivec, rk_rk_sm4_crypt_ecb);
70 } else {
71 rk_sm4_setkey_dec(&ctx, key);
72 rk_crypto_cbc128_decrypt((void*)&ctx, in, out, length, ivec, rk_rk_sm4_crypt_ecb);
73 }
74
75
76 return 0;
77 }
78
79
80