wolfssl-examples/pkcs11/pkcs11_rand.c

118 lines
3.1 KiB
C

/* pkcs11_rand.c
*
* Copyright (C) 2006-2020 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* wolfSSL is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
*/
#include <wolfssl/options.h>
#include <wolfssl/wolfcrypt/settings.h>
#include <wolfssl/wolfcrypt/wc_pkcs11.h>
#include <wolfssl/wolfcrypt/error-crypt.h>
#include <wolfssl/wolfcrypt/logging.h>
int pkcs11_rand(WC_RNG* rng)
{
int ret;
unsigned char buffer[32] = { 0, };
ret = wc_RNG_GenerateBlock(rng, buffer, sizeof(buffer));
if (ret != 0) {
fprintf(stderr, "Failed to generate random data\n");
}
else {
int i;
for (i = 0; i < (int)sizeof(buffer); i++) {
printf("%02x", buffer[i]);
}
printf("\n");
}
return ret;
}
int main(int argc, char* argv[])
{
int ret;
const char* library;
const char* slot;
const char* tokenName;
const char* userPin;
Pkcs11Dev dev;
Pkcs11Token token;
int slotId;
int devId = 1;
WC_RNG rng;
if (argc != 4 && argc != 5) {
fprintf(stderr,
"Usage: pkcs11_test <libname> <slot> <tokenname> [userpin]\n");
return 1;
}
library = argv[1];
slot = argv[2];
tokenName = argv[3];
userPin = (argc == 4) ? NULL : argv[4];
slotId = atoi(slot);
#if defined(DEBUG_WOLFSSL)
wolfSSL_Debugging_ON();
#endif
wolfCrypt_Init();
ret = wc_Pkcs11_Initialize(&dev, library, NULL);
if (ret != 0) {
fprintf(stderr, "Failed to initialize PKCS#11 library\n");
ret = 2;
}
if (ret == 0) {
ret = wc_Pkcs11Token_Init(&token, &dev, slotId, tokenName,
(byte*)userPin, userPin == NULL ? 0 : strlen(userPin));
if (ret != 0) {
fprintf(stderr, "Failed to initialize PKCS#11 token\n");
ret = 2;
}
if (ret == 0) {
ret = wc_CryptoDev_RegisterDevice(devId, wc_Pkcs11_CryptoDevCb,
&token);
if (ret != 0) {
fprintf(stderr, "Failed to register PKCS#11 token\n");
ret = 2;
}
if (ret == 0) {
wc_InitRng_ex(&rng, NULL, devId);
ret = pkcs11_rand(&rng);
if (ret != 0)
ret = 1;
wc_FreeRng(&rng);
}
wc_Pkcs11Token_Final(&token);
}
wc_Pkcs11_Finalize(&dev);
}
wolfCrypt_Cleanup();
return ret;
}