From ca7025237f020718ce90b3aec3e4e00712f6f7d3 Mon Sep 17 00:00:00 2001 From: Magnus Ahltorp Date: Fri, 10 Apr 2015 09:58:16 +0200 Subject: Add hsmhelper --- c_src/hsmhelper.c | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 c_src/hsmhelper.c (limited to 'c_src/hsmhelper.c') diff --git a/c_src/hsmhelper.c b/c_src/hsmhelper.c new file mode 100644 index 0000000..5ab9045 --- /dev/null +++ b/c_src/hsmhelper.c @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2014, NORDUnet A/S. + * See LICENSE for licensing information. + */ + +#include +#include +#include +#include + +#include "hsmhelper.h" +#include "erlport.h" + +static long +parseslot(char *slotstring) +{ + char *endptr = NULL; + + if (slotstring[0] == '\0') { + errx(1, "no slot given"); + } + + long slot = strtol(slotstring, &endptr, 10); + + if (endptr[0] != '\0') { + errx(1, "not a valid slot number: %s", slotstring); + } + + return slot; +} + +static void +loop(CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hKey, + CK_MECHANISM_TYPE mechanism) +{ + unsigned char buf[10000]; + unsigned char signature[2048]; + ssize_t len; + + while ((len = read_command(buf, sizeof(buf), 4)) > 0) { + unsigned long signatureLen = sizeof(signature); + sign(hSession, hKey, buf, len, signature, &signatureLen, mechanism); + write_reply(signature, signatureLen, 4); + } +} + +int +main(int argc, char *argv[]) +{ + if (argc < 6) { + errx(1, "usage: %s rsa|ecdsa ", argv[0]); + } + + char *library_path = argv[1]; + char *slotstring = argv[2]; + char *keytype = argv[3]; + char *keyname = argv[4]; + char *pin = argv[5]; + + init(library_path); + + long slot = parseslot(slotstring); + + CK_MECHANISM_TYPE mechanism; + + if (strcmp(keytype, "ecdsa") == 0) { + mechanism = CKM_ECDSA; + } else if (strcmp(keytype, "rsa") == 0) { + mechanism = CKM_SHA256_RSA_PKCS; + } else { + errx(1, "invalid key type: %s", keytype); + } + + CK_SESSION_HANDLE hSession = open_session(slot); + + login(hSession, pin); + + CK_OBJECT_HANDLE hKey = find_key(hSession, CKO_PRIVATE_KEY, keyname); + + loop(hSession, hKey, mechanism); + + return 0; +} -- cgit v1.1