针对以上测试用例,如何通过命令行中的参数,在mian函数中进行调用
时间: 2024-02-20 16:00:05 浏览: 73
可以使用命令行参数来传递测试用例中的一些参数,如密钥、算法标识、初始向量、输入数据等。在main函数中可以通过解析命令行参数来获取这些参数,并将它们传递给SKF_Mac()函数。以下是一个简单的示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "skf.h"
int main(int argc, char* argv[])
{
ULONG rv;
HAPPLICATION hApp;
HCONTAINER hContainer;
ULONG ulAlgId = SGD_SM4_ECB;
ULONG ulBitLen = 128;
UCHAR pbKey[16] = {0};
UCHAR pbIV[16] = {0};
UCHAR pbData[1024] = {0};
ULONG ulDataLen = 0;
UCHAR pbMac[16] = {0};
ULONG ulMacLen = 16;
ULONG ulTimeStart, ulTimeEnd, ulTimeUsed;
// 解析命令行参数
if (argc != 6) {
printf("Usage: %s key alg iv data_file mac_file\n", argv[0]);
return -1;
}
memcpy(pbKey, argv[1], 16);
ulAlgId = atoi(argv[2]);
memcpy(pbIV, argv[3], 16);
FILE* fp = fopen(argv[4], "rb");
if (fp == NULL) {
printf("Failed to open data file: %s\n", argv[4]);
return -1;
}
ulDataLen = fread(pbData, 1, 1024, fp);
fclose(fp);
fp = fopen(argv[5], "wb");
if (fp == NULL) {
printf("Failed to open MAC file: %s\n", argv[5]);
return -1;
}
// 连接到加密设备
rv = SKF_ConnectDev("ACR122U", NULL);
if (rv != SAR_OK) {
printf("Failed to connect to device: %lx\n", rv);
return -1;
}
// 打开应用
rv = SKF_OpenApplication("TestApp", &hApp);
if (rv != SAR_OK) {
printf("Failed to open application: %lx\n", rv);
SKF_DisconnectDev();
return -1;
}
// 打开容器
rv = SKF_OpenContainer(hApp, "TestContainer", &hContainer);
if (rv != SAR_OK) {
printf("Failed to open container: %lx\n", rv);
SKF_CloseApplication(hApp);
SKF_DisconnectDev();
return -1;
}
// 设置密钥
rv = SKF_SetSymmKey(hContainer, pbKey, ulAlgId, &ulBitLen);
if (rv != SAR_OK) {
printf("Failed to set symmetric key: %lx\n", rv);
SKF_CloseContainer(hContainer);
SKF_CloseApplication(hApp);
SKF_DisconnectDev();
return -1;
}
// 计算MAC
ulTimeStart = clock();
rv = SKF_Mac(hContainer, ulAlgId, pbIV, pbData, ulDataLen, pbMac, &ulMacLen);
ulTimeEnd = clock();
ulTimeUsed = ulTimeEnd - ulTimeStart;
if (rv != SAR_OK) {
printf("Failed to calculate MAC: %lx\n", rv);
SKF_DeleteSymmKey(hContainer);
SKF_CloseContainer(hContainer);
SKF_CloseApplication(hApp);
SKF_DisconnectDev();
return -1;
}
// 输出结果
printf("MAC: ");
for (int i = 0; i < ulMacLen; i++) {
printf("%02x", pbMac[i]);
}
printf("\n");
printf("Time used: %lu ms\n", ulTimeUsed);
// 将MAC写入文件
fwrite(pbMac, 1, ulMacLen, fp);
// 删除密钥
rv = SKF_DeleteSymmKey(hContainer);
if (rv != SAR_OK) {
printf("Failed to delete symmetric key: %lx\n", rv);
}
// 关闭容器
rv = SKF_CloseContainer(hContainer);
if (rv != SAR_OK) {
printf("Failed to close container: %lx\n", rv);
}
// 关闭应用
rv = SKF_CloseApplication(hApp);
if (rv != SAR_OK) {
printf("Failed to close application: %lx\n", rv);
}
// 断开连接
SKF_DisconnectDev();
return 0;
}
```
在这个示例中,命令行参数依次是:密钥、算法标识、初始向量、输入数据文件、MAC输出文件。程序通过解析命令行参数来获取这些值,并将它们传递给SKF_Mac()函数。程序还会将计算得到的MAC写入到输出文件中。
阅读全文