1 /**
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <unistd.h>
17 #include <stdlib.h>
18 #include <stdio.h>
19 #include <string.h>
20 #include <crypt.h>
21 #include "functionalext.h"
22
23 #define BITS_COUNT_OF_ONE_BYTE 8
24 #define LENGTH 8
25
26 // 验证加解密之后是否还与原文相同
test_encrypt_and_decrypt(void)27 static void test_encrypt_and_decrypt(void)
28 {
29 char keytext[] = "ABCDEFGH";
30 char key[65];
31 char plaintext[] = "HELLO123";
32 char buf[65];
33 char block_cipher[9];
34 char block_decrypt[9];
35
36 // 处理密钥
37 for (int i = 0; i < LENGTH; i++) {
38 for (int j = 0; j < BITS_COUNT_OF_ONE_BYTE; j++) {
39 key[i * BITS_COUNT_OF_ONE_BYTE + j] = (keytext[i] >> j) & 1;
40 }
41 }
42
43 // 将明文处理为二进制
44 for (int i = 0; i < LENGTH; i++) {
45 for (int j = 0; j < BITS_COUNT_OF_ONE_BYTE; j++) {
46 buf[i * BITS_COUNT_OF_ONE_BYTE + j] = (plaintext[i] >> j) & 1;
47 }
48 setkey(key);
49 }
50 printf("Before encrypting: %s\n", plaintext);
51
52 // 加密并将二进制数据处理为字符串
53 encrypt(buf, 0);
54 for (int i = 0; i < LENGTH; i++) {
55 block_cipher[i] = '\0';
56 for (int j = 0; j < BITS_COUNT_OF_ONE_BYTE; j++) {
57 block_cipher[i] |= buf[i * BITS_COUNT_OF_ONE_BYTE + j] << j;
58 }
59 block_cipher[LENGTH] = '\0';
60 }
61 printf("After encrypting: %s\n", block_cipher);
62
63 // 解密并将二进制数据处理为字符串
64 encrypt(buf, 1);
65 for (int i = 0; i < LENGTH; i++) {
66 block_decrypt[i] = '\0';
67 for (int j = 0; j < BITS_COUNT_OF_ONE_BYTE; j++) {
68 block_decrypt[i] |= buf[i * BITS_COUNT_OF_ONE_BYTE + j] << j;
69 }
70 block_decrypt[LENGTH] = '\0';
71 }
72 printf("After decrypting: %s\n", block_decrypt);
73 EXPECT_STREQ("test_encrypt_and_decrypt", plaintext, block_decrypt);
74 }
75
main(void)76 int main(void)
77 {
78 test_encrypt_and_decrypt();
79 return t_status;
80 }