• 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 #include <stdio.h>
11 #include <string.h>
12 #include <stdlib.h>
13 #include <gmssl/sm4.h>
14 #include <gmssl/rand.h>
15 
16 
main(void)17 int main(void)
18 {
19 	SM4_KEY sm4_key;
20 	unsigned char key[16];
21 	unsigned char iv[16];
22 	unsigned char ctr[16];
23 	unsigned char mbuf[20] = {
24 		0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
25 		0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
26 		0x31,0x32,0x33,0x34,
27 	};
28 	unsigned char cbuf[20] = {0};
29 	unsigned char pbuf[20] = {0};
30 	int i;
31 
32 	rand_bytes(key, sizeof(key));
33 	rand_bytes(iv, sizeof(iv));
34 
35 	printf("key: ");
36 	for (i = 0; i < sizeof(key); i++) {
37 		printf("%02X", key[i]);
38 	}
39 	printf("\n");
40 
41 	printf("ctr: ");
42 	for (i = 0; i < sizeof(iv); i++) {
43 		printf("%02X", iv[i]);
44 	}
45 	printf("\n");
46 
47 	sm4_set_encrypt_key(&sm4_key, key);
48 
49 	printf("sm4 ctr encrypt %zu bytes\n", sizeof(mbuf));
50 
51 	printf("plaintext: ");
52 	for (i = 0; i < sizeof(mbuf); i++) {
53 		printf("%02X", mbuf[i]);
54 	}
55 	printf("\n");
56 
57 	memcpy(ctr, iv, 16);
58 	sm4_ctr_encrypt(&sm4_key, ctr, mbuf, sizeof(mbuf), cbuf);
59 
60 	printf("ciphertext: ");
61 	for (i = 0; i < sizeof(cbuf); i++) {
62 		printf("%02X", cbuf[i]);
63 	}
64 	printf("\n");
65 
66 	memcpy(ctr, iv, 16);
67 	sm4_ctr_decrypt(&sm4_key, ctr, cbuf, sizeof(cbuf), pbuf);
68 
69 	printf("decrypted: ");
70 	for (i = 0; i < sizeof(pbuf); i++) {
71 		printf("%02X", pbuf[i]);
72 	}
73 	printf("\n");
74 
75 	return 0;
76 }
77