xref: /OK3568_Linux_fs/external/security/librkcrypto/test/c_mode/des_cfb.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <assert.h>
5 #include "des_core.h"
6 
rk_crypto_cfb128_encrypt(void * ctx,const unsigned char * in,unsigned char * out,size_t len,unsigned char ivec[DES_BLOCK_SIZE],int * num,int enc,block128_f block)7 static void rk_crypto_cfb128_encrypt(void *ctx, const unsigned char *in, unsigned char *out,
8 			size_t len, unsigned char ivec[DES_BLOCK_SIZE], int *num,
9 			int enc, block128_f block)
10 {
11     unsigned int n;
12     size_t l = 0;
13 
14     n = *num;
15     if (enc) {
16 
17 	while (l<len) {
18 		if (n == 0) {
19 			(*block)(ivec, ivec, ctx);
20 		}
21 		out[l] = ivec[n] ^= in[l];
22 		++l;
23 		n = (n+1) % DES_BLOCK_SIZE;
24 	}
25 	*num = n;
26     } else {
27 	while (l<len) {
28 		unsigned char c;
29 		if (n == 0) {
30 			(*block)(ivec, ivec, ctx);
31 		}
32 		out[l] = ivec[n] ^ (c = in[l]); ivec[n] = c;
33 		++l;
34 		n = (n+1) % DES_BLOCK_SIZE;
35 	}
36 	*num=n;
37     }
38 }
39 
rk_des_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)40 int rk_des_cfb_encrypt(const unsigned char *in, unsigned char *out,
41         unsigned long length, const unsigned char *key, const int key_len,
42         unsigned char *ivec, const int enc)
43 {
44 	rk_des_context  ctx;
45 	rk_des3_context ctx3;
46 	int num = 0;
47 
48 	if (in == NULL || out ==NULL || key == NULL)
49 		return -1;
50 
51 	if (key_len != 8 && key_len != 16 && key_len != 24)
52 		return -2;
53 
54 	if(length == 0)
55 		return -3;
56 
57 	switch(key_len){
58 	case 8:
59 		rk_des_setkey_enc(&ctx, key);
60 		rk_crypto_cfb128_encrypt((void *)&ctx, in, out,length, ivec,
61 					 &num,enc, rk_des_crypt_ecb);
62 		break;
63 	case 16:
64 		rk_des3_set2key_enc(&ctx3, key);
65 		rk_crypto_cfb128_encrypt((void *)&ctx3, in, out,length, ivec,
66 					 &num,enc, rk_des3_crypt_ecb);
67 		break;
68 	case 24:
69 		rk_des3_set3key_enc(&ctx3, key);
70 		rk_crypto_cfb128_encrypt((void *)&ctx3, in, out,length, ivec,
71 					 &num,enc, rk_des3_crypt_ecb);
72 		break;
73 	default:
74 		return -1;
75 	}
76 
77 	 return 0;
78 }
79 
80