Implemented ntru_private_key class
[strongswan.git] / src / libstrongswan / plugins / ntru / ntru_public_key.c
1 /*
2 * Copyright (C) 2014 Andreas Steffen
3 * HSR Hochschule fuer Technik Rapperswil
4 *
5 * Copyright (C) 2009-2013 Security Innovation
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2 of the License, or (at your
10 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * for more details.
16 */
17
18 #include "ntru_public_key.h"
19
20 #include "ntru_crypto/ntru_crypto_ntru_convert.h"
21
22 #include <utils/debug.h>
23
24 typedef struct private_ntru_public_key_t private_ntru_public_key_t;
25
26 /**
27 * Private data of an ntru_public_key_t object.
28 */
29 struct private_ntru_public_key_t {
30 /**
31 * Public ntru_public_key_t interface.
32 */
33 ntru_public_key_t public;
34
35 /**
36 * NTRU Parameter Set
37 */
38 ntru_param_set_t *params;
39
40 /**
41 * Polynomial h which is the public key
42 */
43 uint16_t *pubkey;
44
45 /**
46 * Encoding of the public key
47 */
48 chunk_t encoding;
49
50 };
51
52 METHOD(ntru_public_key_t, get_encoding, chunk_t,
53 private_ntru_public_key_t *this)
54 {
55 if (!this->encoding.len)
56 {
57 size_t pubkey_len;
58 u_char *enc;
59
60 /* compute public key length encoded as packed coefficients */
61 pubkey_len = (this->params->N * this->params->q_bits + 7) / 8;
62
63 /* allocate memory for public key encoding */
64 this->encoding = chunk_alloc(2 + NTRU_OID_LEN + pubkey_len);
65 enc = this->encoding.ptr;
66
67 /* format header and packed public key */
68 *enc++ = NTRU_PUBKEY_TAG;
69 *enc++ = NTRU_OID_LEN;
70 memcpy(enc, this->params->oid, NTRU_OID_LEN);
71 enc += NTRU_OID_LEN;
72 ntru_elements_2_octets(this->params->N, this->pubkey,
73 this->params->q_bits, enc);
74 }
75 return this->encoding;
76 }
77
78 METHOD(ntru_public_key_t, destroy, void,
79 private_ntru_public_key_t *this)
80 {
81 chunk_clear(&this->encoding);
82 free(this->pubkey);
83 free(this);
84 }
85
86 /*
87 * Described in header.
88 */
89 ntru_public_key_t *ntru_public_key_create(ntru_param_set_t *params,
90 uint16_t *pubkey)
91 {
92 private_ntru_public_key_t *this;
93 int i;
94
95 INIT(this,
96 .public = {
97 .get_encoding = _get_encoding,
98 .destroy = _destroy,
99 },
100 .params = params,
101 .pubkey = malloc(params->N * sizeof(uint16_t)),
102 );
103
104 for (i = 0; i < params->N; i++)
105 {
106 this->pubkey[i] = pubkey[i];
107 }
108
109 return &this->public;
110 }