• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright 2014-2022 The GmSSL Project. All Rights Reserved.
3  *
4  *  Licensed under the Apache License, Version 2.0 (the License); you may
5  *  not use this file except in compliance with the License.
6  *
7  *  http://www.apache.org/licenses/LICENSE-2.0
8  */
9 
10 
11 #include <gmssl/sm4.h>
12 #include <gmssl/endian.h>
13 #include "sm4_lcl.h"
14 
15 
16 #define L32(x)							\
17 	((x) ^							\
18 	ROL32((x),  2) ^					\
19 	ROL32((x), 10) ^					\
20 	ROL32((x), 18) ^					\
21 	ROL32((x), 24))
22 
23 #define ROUND_SBOX(x0, x1, x2, x3, x4, i)			\
24 	x4 = x1 ^ x2 ^ x3 ^ *(rk + i);				\
25 	x4 = S32(x4);						\
26 	x4 = x0 ^ L32(x4)
27 
28 #define ROUND_TBOX(x0, x1, x2, x3, x4, i)			\
29 	x4 = x1 ^ x2 ^ x3 ^ *(rk + i);				\
30 	t0 = ROL32(SM4_T[(uint8_t)x4], 8);			\
31 	x4 >>= 8;						\
32 	x0 ^= t0;						\
33 	t0 = ROL32(SM4_T[(uint8_t)x4], 16);			\
34 	x4 >>= 8;						\
35 	x0 ^= t0;						\
36 	t0 = ROL32(SM4_T[(uint8_t)x4], 24);			\
37 	x4 >>= 8;						\
38 	x0 ^= t0;						\
39 	t1 = SM4_T[x4];					\
40 	x4 = x0 ^ t1
41 
42 #define ROUND ROUND_TBOX
43 
44 
sm4_encrypt(const SM4_KEY * key,const unsigned char in[16],unsigned char out[16])45 void sm4_encrypt(const SM4_KEY *key, const unsigned char in[16], unsigned char out[16])
46 {
47 	const uint32_t *rk = key->rk;
48 	uint32_t x0, x1, x2, x3, x4;
49 	uint32_t t0, t1;
50 
51 	x0 = GETU32(in     );
52 	x1 = GETU32(in +  4);
53 	x2 = GETU32(in +  8);
54 	x3 = GETU32(in + 12);
55 	ROUNDS(x0, x1, x2, x3, x4);
56 	PUTU32(out     , x0);
57 	PUTU32(out +  4, x4);
58 	PUTU32(out +  8, x3);
59 	PUTU32(out + 12, x2);
60 }
61 
62 /* caller make sure counter not overflow */
sm4_ctr32_encrypt_blocks(const unsigned char * in,unsigned char * out,size_t blocks,const SM4_KEY * key,const unsigned char iv[16])63 void sm4_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out,
64 	size_t blocks, const SM4_KEY *key, const unsigned char iv[16])
65 {
66 	const uint32_t *rk = key->rk;
67 	unsigned int c0 = GETU32(iv     );
68 	unsigned int c1 = GETU32(iv +  4);
69 	unsigned int c2 = GETU32(iv +  8);
70 	unsigned int c3 = GETU32(iv + 12);
71 	uint32_t x0, x1, x2, x3, x4;
72 	uint32_t t0, t1;
73 
74 	while (blocks--) {
75 		x0 = c0;
76 		x1 = c1;
77 		x2 = c2;
78 		x3 = c3;
79 		ROUNDS(x0, x1, x2, x3, x4);
80 		PUTU32(out     , GETU32(in     ) ^ x0);
81 		PUTU32(out +  4, GETU32(in +  4) ^ x4);
82 		PUTU32(out +  8, GETU32(in +  8) ^ x3);
83 		PUTU32(out + 12, GETU32(in + 12) ^ x2);
84 		in += 16;
85 		out += 16;
86 		c3++;
87 	}
88 }
89