summaryrefslogtreecommitdiff
path: root/src/key.c
blob: 495cff4e1c21814c067acaa8a95aa4fc7b1f3a21 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

#include "p11-tests.h"

CK_OBJECT_HANDLE
find_related_object(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE key, CK_OBJECT_CLASS klass)
{
	CK_BYTE id[4096];
	CK_ATTRIBUTE attrs[2];

	attrs[0].type = CKA_ID;
	attrs[0].pValue = id;
	attrs[0].ulValueLen = sizeof(id);

	if(!p11t_object_get(session, key, attrs, 1))
		return CK_INVALID;

	attrs[1].type = CKA_CLASS;
	attrs[1].ulValueLen = sizeof(klass);
	attrs[1].pValue = &klass;

	return p11t_object_find_one(session, attrs, 2);
}

CK_OBJECT_HANDLE
p11t_key_get_public(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE key)
{
	return find_related_object(session, key, CKO_PUBLIC_KEY);
}

CK_OBJECT_HANDLE
p11t_key_get_private(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE key)
{
	return find_related_object(session, key, CKO_PRIVATE_KEY);
}

RSA*
p11t_key_export_public_rsa(CK_SESSION_HANDLE session, CK_OBJECT_HANDLE key)
{
	CK_ATTRIBUTE attrs[3];
	CK_BYTE modulus[4096];
	CK_BYTE public_exponent[4096];
	CK_ULONG modulus_bits;
	RSA *rsa;

	attrs[0].type = CKA_MODULUS;
	attrs[0].ulValueLen = sizeof(modulus);
	attrs[0].pValue = modulus;

	attrs[1].type = CKA_MODULUS_BITS;
	attrs[1].ulValueLen = sizeof(modulus_bits);
	attrs[1].pValue = &modulus_bits;

	attrs[2].type = CKA_PUBLIC_EXPONENT;
	attrs[2].ulValueLen = sizeof(public_exponent);
	attrs[2].pValue = public_exponent;

	if(!p11t_object_get(session, key, attrs, 3))
		return NULL;

	if(attrs[0].ulValueLen == CK_INVALID ||
	   attrs[2].ulValueLen == CK_INVALID)
		return NULL;

	rsa = RSA_new();
	rsa->n = BN_bin2bn(modulus, attrs[0].ulValueLen, NULL);
	rsa->e = BN_bin2bn(public_exponent, attrs[2].ulValueLen, NULL);
	assert(rsa && rsa->n && rsa->e);

	if(attrs[1].ulValueLen != CK_INVALID)
	{
		assert(RSA_size(rsa) == modulus_bits / 8);
	}

	return rsa;
}