Creating a key

Updated: May 17, 2017

SmartKey provides multiple interfaces to application developers. For C/C++ programmers, SmartKey provides a PKCS#11 interface through a library. For Java programmers, SmartKey can be accessed through the JCE interface. SmartKey can also be accessed through its RESTful interface, documented at http://support.smartkey.io/api/index.html

We provide examples for using SmartKey in 3 languages – a C++ program using the PKCS#11 interface, a Java program using the JCE interface, and a Python program using the REST interface.

Download the code to initialize and login. The example programs can be downloaded in full at http://support.smartkey.io/smartkey/resources.html


CK_OBJECT_HANDLE generate_key(CK_FUNCTION_LIST_PTR p11, CK_SESSION_HANDLE hSession, CK_ULONG len) {
    CK_RV rv;
    CK_MECHANISM mechKeyGen = {
      CKM_AES_KEY_GEN, NULL_PTR, 0
    };
    CK_BBOOL _true = CK_TRUE;
    CK_OBJECT_HANDLE hKey;

    CK_ATTRIBUTE keyTemplate[] = {
      {CKA_VALUE_LEN, &len, sizeof(len)},
      {CKA_ENCRYPT, &_true, sizeof(_true)},
      {CKA_DECRYPT, &_true, sizeof(_true)}
    };

    rv = p11->C_GenerateKey(hSession, &mechKeyGen, keyTemplate, sizeof(keyTemplate)/sizeof(*keyTemplate), &hKey);
    if (rv == CKR_OK) return hKey; else return CK_INVALID_HANDLE;
}


private static SecretKey generateKey(Provider provider, String type, int length) {
    try {
        KeyGenerator keyGen = KeyGenerator.getInstance(type, provider);
        keyGen.init(length);
        SecretKey key = keyGen.generateKey();
        System.out.println("Successfully generated secret key of type " + type + " and length " + length);
        return key;
    } catch (Exception e) {
        System.out.println("Can't generate secret key: " + e);
        return null;
    }
}


def generate_key(bearer_token, name, description, type, length):
    key_request = {'name': name, 'description': description, 'obj_type': type, 'key_size': length}
    res = requests.request(method='POST',
                           url="https://www.smartkey.io/crypto/v1/keys",
                           headers={'Authorization' : 'Bearer ' + bearer_token},
                           data=json.dumps(key_request))
    if res.status_code != requests.codes.created:
        print "Can't generate secret key: " + str(res.status_code)
        return None
    else:
        print "Successfully generated secret key"
        return res.json()['kid']