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 aad[20];
23 unsigned char mbuf[64] = {
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[64] = {0};
29 unsigned char pbuf[64] = {0};
30 unsigned char tag[16];
31 int i;
32
33 rand_bytes(key, sizeof(key));
34 rand_bytes(iv, sizeof(iv));
35
36 printf("key: ");
37 for (i = 0; i < sizeof(key); i++) {
38 printf("%02X", key[i]);
39 }
40 printf("\n");
41
42 printf("iv: ");
43 for (i = 0; i < sizeof(iv); i++) {
44 printf("%02X", iv[i]);
45 }
46 printf("\n");
47
48 sm4_set_encrypt_key(&sm4_key, key);
49
50 printf("sm4 gcm encrypt\n");
51
52 printf("auth-only data: ");
53 for (i = 0; i < sizeof(aad); i++) {
54 printf("%02X", aad[i]);
55 }
56 printf("\n");
57
58 printf("plaintext: ");
59 for (i = 0; i < sizeof(mbuf); i++) {
60 printf("%02X", mbuf[i]);
61 }
62 printf("\n");
63
64 sm4_gcm_encrypt(&sm4_key, iv, sizeof(iv), aad, sizeof(aad), mbuf, sizeof(mbuf), cbuf, sizeof(tag), tag);
65
66 printf("ciphertext: ");
67 for (i = 0; i < sizeof(cbuf); i++) {
68 printf("%02X", cbuf[i]);
69 }
70 printf("\n");
71
72 printf("mac-tag: ");
73 for (i = 0; i < sizeof(tag); i++) {
74 printf("%02X", tag[i]);
75 }
76 printf("\n");
77
78 if (sm4_gcm_decrypt(&sm4_key, iv, sizeof(iv), aad, sizeof(aad), cbuf, sizeof(mbuf), tag, sizeof(tag), pbuf) != 1) {
79 fprintf(stderr, "sm4 gcm decrypt failed\n");
80 return 1;
81 }
82
83 printf("decrypted: ");
84 for (i = 0; i < sizeof(pbuf); i++) {
85 printf("%02X", pbuf[i]);
86 }
87 printf("\n");
88
89 return 0;
90 }
91