opensc-explorer: extend 'random' to allow writing to a file

Accept a file name as a second argument to the 'random' command
to allow storing the generated random bytes to the file given.

Forbid writing binary data to stdout in interactive mode.
This commit is contained in:
Peter Marschall 2018-07-08 10:40:06 +02:00 committed by Frank Morgner
parent 7a4a9f1951
commit 9d501766b4
2 changed files with 48 additions and 4 deletions

View File

@ -522,10 +522,15 @@
<term>
<command>random</command>
<replaceable>count</replaceable>
<arg choice="opt"><replaceable>output-file</replaceable></arg>
</term>
<listitem>
<para>
Generate <replaceable>count</replaceable> bytes of random data.
Generate <replaceable>count</replaceable> bytes
of random data.
If <replaceable>output-file</replaceable> is given,
write the data to the host computer's file denoted
by it, otherwise show the data as hex dump.
</para>
</listitem>
</varlistentry>

View File

@ -181,7 +181,7 @@ static struct command cmds[] = {
"erase", "",
"erase card" },
{ do_random,
"random", "<count>",
"random", "<count> [<output-file>]",
"obtain <count> random bytes from card" },
{ do_update_record,
"update_record", "<file-id> <rec-no> <rec-offs> <data>",
@ -1663,8 +1663,10 @@ static int do_random(int argc, char **argv)
{
unsigned char buffer[SC_MAX_EXT_APDU_BUFFER_SIZE];
int r, count;
const char *filename = NULL;
FILE *outf = NULL;
if (argc != 1)
if (argc < 1 || argc > 2)
return usage(do_random);
count = atoi(argv[0]);
@ -1674,6 +1676,23 @@ static int do_random(int argc, char **argv)
return -1;
}
if (argc == 2) {
filename = argv[1];
if (interactive && strcmp(filename, "-") == 0) {
fprintf(stderr, "Binary writing to stdout not supported in interactive mode\n");
return -1;
}
outf = (strcmp(filename, "-") == 0)
? stdout
: fopen(filename, "wb");
if (outf == NULL) {
perror(filename);
return -1;
}
}
r = sc_lock(card);
if (r == SC_SUCCESS)
r = sc_get_challenge(card, buffer, count);
@ -1683,7 +1702,27 @@ static int do_random(int argc, char **argv)
return -1;
}
util_hex_dump_asc(stdout, buffer, count, 0);
if (argc == 2) {
/* outf is guaranteed to be non-NULL */
size_t written = fwrite(buffer, 1, count, outf);
if (written < (size_t) count)
perror(filename);
if (outf == stdout) {
printf("\nTotal of %"SC_FORMAT_LEN_SIZE_T"u random bytes written\n", written);
}
else
printf("Total of %"SC_FORMAT_LEN_SIZE_T"u random bytes written to %s\n",
written, filename);
fclose(outf);
if (written < (size_t) count)
return -1;
}
else {
util_hex_dump_asc(stdout, buffer, count, 0);
}
return 0;
}