• 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 static uint32_t FK[4] = {
16 	0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc,
17 };
18 
19 static uint32_t CK[32] = {
20 	0x00070e15, 0x1c232a31, 0x383f464d, 0x545b6269,
21 	0x70777e85, 0x8c939aa1, 0xa8afb6bd, 0xc4cbd2d9,
22 	0xe0e7eef5, 0xfc030a11, 0x181f262d, 0x343b4249,
23 	0x50575e65, 0x6c737a81, 0x888f969d, 0xa4abb2b9,
24 	0xc0c7ced5, 0xdce3eaf1, 0xf8ff060d, 0x141b2229,
25 	0x30373e45, 0x4c535a61, 0x686f767d, 0x848b9299,
26 	0xa0a7aeb5, 0xbcc3cad1, 0xd8dfe6ed, 0xf4fb0209,
27 	0x10171e25, 0x2c333a41, 0x484f565d, 0x646b7279,
28 };
29 
30 #define L32_(x)					\
31 	((x) ^ 					\
32 	ROL32((x), 13) ^			\
33 	ROL32((x), 23))
34 
35 #define ENC_ROUND(x0, x1, x2, x3, x4, i)	\
36 	x4 = x1 ^ x2 ^ x3 ^ *(CK + i);		\
37 	x4 = S32(x4);				\
38 	x4 = x0 ^ L32_(x4);			\
39 	*(rk + i) = x4
40 
41 #define DEC_ROUND(x0, x1, x2, x3, x4, i)	\
42 	x4 = x1 ^ x2 ^ x3 ^ *(CK + i);		\
43 	x4 = S32(x4);				\
44 	x4 = x0 ^ L32_(x4);			\
45 	*(rk + 31 - i) = x4
46 
sm4_set_encrypt_key(SM4_KEY * key,const uint8_t user_key[16])47 void sm4_set_encrypt_key(SM4_KEY *key, const uint8_t user_key[16])
48 {
49 	uint32_t *rk = key->rk;
50 	uint32_t x0, x1, x2, x3, x4;
51 
52 	x0 = GETU32(user_key     ) ^ FK[0];
53 	x1 = GETU32(user_key  + 4) ^ FK[1];
54 	x2 = GETU32(user_key  + 8) ^ FK[2];
55 	x3 = GETU32(user_key + 12) ^ FK[3];
56 
57 #define ROUND ENC_ROUND
58 	ROUNDS(x0, x1, x2, x3, x4);
59 #undef ROUND
60 
61 	x0 = x1 = x2 = x3 = x4 = 0;
62 }
63 
sm4_set_decrypt_key(SM4_KEY * key,const uint8_t user_key[16])64 void sm4_set_decrypt_key(SM4_KEY *key, const uint8_t user_key[16])
65 {
66 	uint32_t *rk = key->rk;
67 	uint32_t x0, x1, x2, x3, x4;
68 
69 	x0 = GETU32(user_key     ) ^ FK[0];
70 	x1 = GETU32(user_key  + 4) ^ FK[1];
71 	x2 = GETU32(user_key  + 8) ^ FK[2];
72 	x3 = GETU32(user_key + 12) ^ FK[3];
73 
74 #define ROUND DEC_ROUND
75 	ROUNDS(x0, x1, x2, x3, x4);
76 #undef ROUND
77 
78 	x0 = x1 = x2 = x3 = x4 = 0;
79 }
80