• 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 mbuf[32] = {
23 		0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
24 		0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
25 		0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
26 		0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,
27 	};
28 	unsigned char cbuf[32] = {0};
29 	unsigned char pbuf[32] = {0};
30 	size_t mlen1 = 20, mlen2 = 16;
31 	size_t clen1, clen2;
32 	size_t plen1, plen2;
33 	int i;
34 
35 	rand_bytes(key, sizeof(key));
36 	rand_bytes(iv, sizeof(iv));
37 
38 	printf("key: ");
39 	for (i = 0; i < sizeof(key); i++) {
40 		printf("%02X", key[i]);
41 	}
42 	printf("\n");
43 
44 	printf("iv: ");
45 	for (i = 0; i < sizeof(iv); i++) {
46 		printf("%02X", iv[i]);
47 	}
48 	printf("\n");
49 
50 
51 	printf("sm4_cbc_pading encrypt %zu bytes\n", mlen1);
52 
53 	printf("plaintext: ");
54 	for (i = 0; i < mlen1; i++) {
55 		printf("%02X", mbuf[i]);
56 	}
57 	printf("\n");
58 
59 	sm4_set_encrypt_key(&sm4_key, key);
60 	sm4_cbc_padding_encrypt(&sm4_key, iv, mbuf, mlen1, cbuf, &clen1);
61 
62 	printf("ciphertext: ");
63 	for (i = 0; i < clen1; i++) {
64 		printf("%02X", cbuf[i]);
65 	}
66 	printf("\n");
67 
68 	sm4_set_decrypt_key(&sm4_key, key);
69 	sm4_cbc_padding_decrypt(&sm4_key, iv, cbuf, clen1, pbuf, &plen1);
70 
71 	printf("decrypted: ");
72 	for (i = 0; i < plen1; i++) {
73 		printf("%02X", pbuf[i]);
74 	}
75 	printf("\n");
76 
77 	printf("sm4_cbc_pading encrypt %zu bytes\n", mlen2);
78 
79 	printf("plaintext: ");
80 	for (i = 0; i < mlen2; i++) {
81 		printf("%02X", mbuf[i]);
82 	}
83 	printf("\n");
84 
85 	sm4_set_encrypt_key(&sm4_key, key);
86 	sm4_cbc_padding_encrypt(&sm4_key, iv, mbuf, mlen2, cbuf, &clen2);
87 
88 	printf("ciphertext: ");
89 	for (i = 0; i < clen2; i++) {
90 		printf("%02X", cbuf[i]);
91 	}
92 	printf("\n");
93 
94 	sm4_set_decrypt_key(&sm4_key, key);
95 	sm4_cbc_padding_decrypt(&sm4_key, iv, cbuf, clen2, pbuf, &plen2);
96 
97 	printf("decrypted: ");
98 	for (i = 0; i < plen2; i++) {
99 		printf("%02X", pbuf[i]);
100 	}
101 	printf("\n");
102 
103 
104 	return 0;
105 }
106