add tools

This commit is contained in:
Zhi Guan
2022-05-01 09:48:31 +08:00
parent d1b3816319
commit 52af204f0d
10 changed files with 704 additions and 75 deletions

View File

@@ -49,19 +49,26 @@
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmssl/sm3.h>
#include <gmssl/sm2.h>
#include <gmssl/sm3.h>
#include <gmssl/error.h>
static const char *options = "[-hex|-bin] [-pubkey pem [-id str]] [-in file]";
int sm3_main(int argc, char **argv)
{
int ret = 1;
char *prog = argv[0];
int bin = 0;
char *pubkeyfile = NULL;
char *infile = NULL;
char *id = NULL;
FILE *pubkeyfp = NULL;
FILE *infp = stdin;
SM3_CTX sm3_ctx;
uint8_t dgst[32];
uint8_t buf[4096];
@@ -73,26 +80,32 @@ int sm3_main(int argc, char **argv)
while (argc > 0) {
if (!strcmp(*argv, "-help")) {
help:
fprintf(stderr, "usage: %s [-pubkey pem [-id str]] [-in file]\n", prog);
fprintf(stderr, "usage: %s %s\n", prog, options);
fprintf(stderr, "usage: echo -n \"abc\" | %s\n", prog);
return -1;
return 0;
} else if (!strcmp(*argv, "-hex")) {
if (bin) {
error_print();
goto end;
}
bin = 0;
} else if (!strcmp(*argv, "-bin")) {
bin = 1;
} else if (!strcmp(*argv, "-pubkey")) {
if (--argc < 1) goto bad;
pubkeyfile = *(++argv);
} else if (!strcmp(*argv, "-id")) {
if (--argc < 1) goto bad;
id = *(++argv);
} else if (!strcmp(*argv, "-in")) {
if (--argc < 1) goto bad;
infile = *(++argv);
} else {
fprintf(stderr, "%s: illegal option '%s'\n", prog, *argv);
goto help;
goto end;
bad:
fprintf(stderr, "%s: '%s' option value required\n", prog, *argv);
goto end;
}
argc--;
@@ -107,11 +120,11 @@ help:
if (!(pubkeyfp = fopen(pubkeyfile, "r"))) {
error_print();
return -1;
goto end;
}
if (sm2_public_key_info_from_pem(&sm2_key, pubkeyfp) != 1) {
error_print();
return -1;
goto end;
}
if (!id) {
id = SM2_DEFAULT_ID;
@@ -123,14 +136,14 @@ help:
} else {
if (id) {
fprintf(stderr, "%s: option '-id' must be with '-pubkey'\n", prog);
goto help;
goto end;
}
}
if (infile) {
if (!(infp = fopen(infile, "r"))) {
error_print();
return -1;
goto end;
}
}
while ((len = fread(buf, 1, sizeof(buf), infp)) > 0) {
@@ -138,17 +151,19 @@ help:
}
sm3_finish(&sm3_ctx, dgst);
for (i = 0; i < sizeof(dgst); i++) {
printf("%02x", dgst[i]);
}
printf("\n");
if (infile) {
fclose(infp);
if (bin) {
fwrite(dgst, 1, 32, stdout);
} else {
for (i = 0; i < sizeof(dgst); i++) {
printf("%02x", dgst[i]);
}
printf("\n");
}
return 0;
bad:
fprintf(stderr, "%s: '%s' option value required\n", prog, *argv);
return -1;
ret = 0;
end:
if (infile) fclose(infp);
return ret;
}