LibItsSecurity_externals.cc 68.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/*!
 * \file      LibItsSecurity_Functions.cc
 * \brief     Source file for Security externl functions.
 * \author    ETSI STF525
 * \copyright ETSI Copyright Notification
 *            No part may be reproduced except as authorized by written permission.
 *            The copyright and the foregoing restriction extend to reproduction in all media.
 *            All rights reserved.
 * \version   0.1
 */
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "LibItsSecurity_Functions.hh"

#include "sha256.hh"
#include "sha384.hh"
#include "hmac.hh"

#include "security_ecc.hh"

#include "security_services.hh"

#include <openssl/ec.h>
#include <openssl/ecdsa.h>

#include "loggers.hh"

namespace LibItsSecurity__Functions 
{

  // FIXME Unify code with security_services
  
  /**
   * \fn OCTETSTRING fx_hashWithSha256(const OCTETSTRING& p__toBeHashedData);
33
   * \brief Produces a 256-bit (32-bytes) hash value
34
35
36
37
38
39
40
   * \param[in] p__toBeHashedData The data to be used to calculate the hash value
   * \return  The hash value
   */
  OCTETSTRING fx__hashWithSha256(
                                 const OCTETSTRING& p__toBeHashedData
                                 ) {
    loggers::get_instance().log_msg(">>> fx__hashWithSha256: p__toBeHashedData= ", p__toBeHashedData); 
41

42
    sha256 hash;
43
44
45
46
    OCTETSTRING hashData;
    hash.generate(p__toBeHashedData, hashData);
    loggers::get_instance().log_msg("fx__hashWithSha256: hashData= ", hashData);
    return hashData;
47
48
49
50
  } // End of function fx__hashWithSha256

  /**
   * \fn OCTETSTRING fx_hashWithSha384(const OCTETSTRING& p__toBeHashedData);
51
   * \brief Produces a 384-bit (48-bytes) hash value
52
53
54
55
56
57
58
   * \param[in] p__toBeHashedData Data to be used to calculate the hash value
   * \return The hash value
   */
  OCTETSTRING fx__hashWithSha384(
                                 const OCTETSTRING& p__toBeHashedData
                                 ) {
    sha384 hash;
59
60
61
62
    OCTETSTRING hashData;
    hash.generate(p__toBeHashedData, hashData);
    loggers::get_instance().log_msg("fx__hashWithSha384: hashData= ", hashData);
    return hashData;
63
64
65
66
67
68
  } // End of function fx__hashWithSha384

  /**
   * \fn OCTETSTRING fx__signWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey);
   * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature
   * \param[in] p__toBeSignedSecuredMessage The data to be signed
69
   * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
70
71
72
73
74
75
76
77
   * \param[in] p__privateKey The private key
   * \return The signature value
   */
  OCTETSTRING fx__signWithEcdsaNistp256WithSha256(
                                                  const OCTETSTRING& p__toBeSignedSecuredMessage,
                                                  const OCTETSTRING& p__certificateIssuer,
                                                  const OCTETSTRING& p__privateKey
                                                  ) {
garciay's avatar
garciay committed
78
79
80
81
    loggers::get_instance().log_msg(">>> fx__signWithEcdsaNistp256WithSha256: data=", p__toBeSignedSecuredMessage); 
    loggers::get_instance().log_msg(">>> fx__signWithEcdsaNistp256WithSha256: issuer=", p__certificateIssuer); 
    loggers::get_instance().log_msg(">>> fx__signWithEcdsaNistp256WithSha256: private key=", p__privateKey); 
    
82
    // Sanity checks
83
    if ((p__certificateIssuer.lengthof() != 32) || (p__privateKey.lengthof() != 32)) {
84
      loggers::get_instance().log("fx__signWithEcdsaNistp256WithSha256: Wrong parameters");
85
      return OCTETSTRING(0, nullptr);
86
87
88
89
    }
    
    // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) )
    sha256 hash;
90
91
92
    OCTETSTRING hashData1; // Hash (Data input)
    hash.generate(p__toBeSignedSecuredMessage, hashData1);
    OCTETSTRING hashData2; // Hash (Signer identifier input)
93
    if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input)
94
      hashData2 = p__certificateIssuer;
95
96
    } else {
      hashData2 = hash.get_sha256_empty_string(); // Hash of empty string
97
    }
98
99
100
101
102
    loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1);
    loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash (Signer identifier input)=", hashData2);
    hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input)
    loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash (Data input) || Hash (Signer identifier input)=", hashData1);
    OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) )
103
    hash.generate(hashData1, hashData);
104
    loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData);
105
    // Calculate the signature
106
107
108
    security_ecc k(ec_elliptic_curves::nist_p_256, p__privateKey);
    OCTETSTRING r_sig;
    OCTETSTRING s_sig;
109
    if (k.sign(hashData, r_sig, s_sig) == 0) {
110
111
112
113
      OCTETSTRING os = r_sig + s_sig;
      loggers::get_instance().log_msg("r_sig= ", r_sig);
      loggers::get_instance().log_msg("s_sig= ", s_sig);
      loggers::get_instance().log_msg("sig= ", os);
114
115
116
      return os;
    }

117
    return OCTETSTRING(0, nullptr);
118
119
120
121
122
123
  }

  /**
   * \fn OCTETSTRING fx__signWithEcdsaBrainpoolp256WithSha256(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey);
   * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature
   * \param[in] p__toBeSignedSecuredMessage The data to be signed
124
   * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
125
126
127
128
129
130
131
132
133
   * \param[in] p__privateKey The private key
   * \return The signature value
   */
  OCTETSTRING fx__signWithEcdsaBrainpoolp256WithSha256(
                                                       const OCTETSTRING& p__toBeSignedSecuredMessage,
                                                       const OCTETSTRING& p__certificateIssuer,
                                                       const OCTETSTRING& p__privateKey
                                                       ) {
    // Sanity checks
134
    if ((p__certificateIssuer.lengthof() != 32) || (p__privateKey.lengthof() != 32)) {
135
      loggers::get_instance().log("fx__signWithEcdsaBrainpoolp256WithSha256: Wrong parameters");
136
      return OCTETSTRING(0, nullptr);
137
138
139
140
    }
    
    // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) )
    sha256 hash;
141
142
143
    OCTETSTRING hashData1; // Hash (Data input)
    hash.generate(p__toBeSignedSecuredMessage, hashData1);
    OCTETSTRING hashData2; // Hash (Signer identifier input)
144
    if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input)
145
      hashData2 = p__certificateIssuer;
146
147
    } else {
      hashData2 = hash.get_sha256_empty_string(); // Hash of empty string
148
    }
149
150
151
152
    loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp256WithSha256: Hash (Data input)=", hashData1);
    loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp256WithSha256: Hash (Signer identifier input)=", hashData2);
    hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input)
    OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) )
153
    hash.generate(hashData1, hashData);
154
    loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp256WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData);
155
    // Calculate the signature
156
157
158
    security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__privateKey);
    OCTETSTRING r_sig;
    OCTETSTRING s_sig;
159
    if (k.sign(hashData, r_sig, s_sig) == 0) {
160
161
162
163
      OCTETSTRING os = r_sig + s_sig;
      loggers::get_instance().log_msg("r_sig= ", r_sig);
      loggers::get_instance().log_msg("s_sig= ", s_sig);
      loggers::get_instance().log_msg("sig= ", os);
164
165
166
      return os;
    }

167
    return OCTETSTRING(0, nullptr);
168
169
170
171
172
173
  }

  /**
   * \fn OCTETSTRING fx__signWithEcdsaBrainpoolp384WithSha384(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey);
   * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature
   * \param[in] p__toBeSignedSecuredMessage The data to be signed
174
   * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
175
176
177
178
179
180
181
182
183
   * \param[in] p__privateKey The private key
   * \return The signature value
   */
  OCTETSTRING fx__signWithEcdsaBrainpoolp384WithSha384(
                                                       const OCTETSTRING& p__toBeSignedSecuredMessage,
                                                       const OCTETSTRING& p__certificateIssuer,
                                                       const OCTETSTRING& p__privateKey
                                                       ) {
    // Sanity checks
184
	    if ((p__certificateIssuer.lengthof() != 48) || (p__privateKey.lengthof() != 48)) {
185
      loggers::get_instance().log("fx__signWithEcdsaBrainpoolp384WithSha384: Wrong parameters");
186
      return OCTETSTRING(0, nullptr);
187
188
189
190
    }
    
    // Calculate the SHA384 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) )
    sha384 hash;
191
192
193
    OCTETSTRING hashData1; // Hash (Data input)
    hash.generate(p__toBeSignedSecuredMessage, hashData1);
    OCTETSTRING hashData2; // Hash (Signer identifier input)
194
    if (p__certificateIssuer != int2oct(0, 48)) { // || Hash (Signer identifier input)
195
      hashData2 = p__certificateIssuer;
196
197
    } else {
      hashData2 = hash.get_sha384_empty_string(); // Hash of empty string
198
    }
199
200
201
202
    loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384WithSha384: Hash (Data input)=", hashData1);
    loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384WithSha384: Hash (Signer identifier input)=", hashData2);
    hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input)
    OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) )
203
    hash.generate(hashData1, hashData);
204
    loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384WithSha384: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData);
205
    // Calculate the signature
206
207
208
    security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__privateKey);
    OCTETSTRING r_sig;
    OCTETSTRING s_sig;
209
    if (k.sign(hashData, r_sig, s_sig) == 0) {
210
211
212
213
      OCTETSTRING os = r_sig + s_sig;
      loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384WithSha384: r_sig= ", r_sig);
      loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384WithSha384: s_sig= ", s_sig);
      loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384WithSha384: sig= ", os);
214
215
216
      return os;
    }

217
    return OCTETSTRING(0, nullptr);
218
219
220
221
222
223
  }

  /**
   * \fn BOOLEAN fx__verifyWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& p__ecdsaNistp256PublicKeyCompressed);
   * \brief Verify the signature of the specified data
   * \param[in] p__toBeVerifiedData The data to be verified
224
   * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
225
226
227
228
229
230
231
232
   * \param[in] p__signature The signature
   * \param[in] p__ecdsaNistp256PublicKeyCompressed The compressed public key (x coordinate only)
   * \return true on success, false otherwise
   */
  BOOLEAN fx__verifyWithEcdsaNistp256WithSha256(
                                                const OCTETSTRING& p__toBeVerifiedData,
                                                const OCTETSTRING& p__certificateIssuer,
                                                const OCTETSTRING& p__signature,
233
                                                const OCTETSTRING& p__ecdsaNistp256PublicKeyCompressed,
234
                                                const INTEGER& p__compressedMode
235
                                                ) {
236
    // Sanity checks
237
    if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaNistp256PublicKeyCompressed.lengthof() != 32)) {
238
239
240
241
242
243
      loggers::get_instance().log("fx__verifyWithEcdsaNistp256WithSha256: Wrong parameters");
      return FALSE;
    }

    // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) )
    sha256 hash;
244
245
246
    OCTETSTRING hashData1; // Hash (Data input)
    hash.generate(p__toBeVerifiedData, hashData1);
    OCTETSTRING hashData2; // Hash (Signer identifier input)
247
    if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input)
248
      hashData2 = p__certificateIssuer;
249
250
    } else {
      hashData2 = hash.get_sha256_empty_string(); // Hash of empty string
251
    }
252
253
254
255
    loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1);
    loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256: Hash (Signer identifier input)=", hashData2);
    hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input)
    OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) )
256
    hash.generate(hashData1, hashData);
257
    loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData);
258
    // Check the signature
259
260
    security_ecc k(ec_elliptic_curves::nist_p_256, p__ecdsaNistp256PublicKeyCompressed, (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1);
    if (k.sign_verif(hashData, p__signature) == 0) {
261
262
263
264
265
266
267
268
269
270
      return TRUE;
    }

    return FALSE;
  }
  
  /**
   * \fn BOOLEAN fx__verifyWithEcdsaNistp256WithSha256_1(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& p__ecdsaNistp256PublicKeyX, const OCTETSTRING& p__ecdsaNistp256PublicKeyY);
   * \brief Verify the signature of the specified data
   * \param[in] p__toBeVerifiedData The data to be verified
271
   * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
272
273
274
275
276
277
278
279
280
281
282
283
284
   * \param[in] p__signature The signature
   * \param[in] p__ecdsaNistp256PublicKeyX The public key (x coordinate)
   * \param[in] p__ecdsaNistp256PublicKeyY The public key (y coordinate)
   * \return true on success, false otherwise
   */
  BOOLEAN fx__verifyWithEcdsaNistp256WithSha256__1(
                                                   const OCTETSTRING& p__toBeVerifiedData,
                                                   const OCTETSTRING& p__certificateIssuer,
                                                   const OCTETSTRING& p__signature,
                                                   const OCTETSTRING& p__ecdsaNistp256PublicKeyX,
                                                   const OCTETSTRING& p__ecdsaNistp256PublicKeyY
                                                   ) {
    // Sanity checks
285
    if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64)) {
286
287
288
289
290
291
      loggers::get_instance().log("fx__verifyWithEcdsaNistp256WithSha256__1: Wrong parameters");
      return FALSE;
    }

    // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) )
    sha256 hash;
292
293
294
    OCTETSTRING hashData1; // Hash (Data input)
    hash.generate(p__toBeVerifiedData, hashData1);
    OCTETSTRING hashData2; // Hash (Signer identifier input)
295
    if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input)
296
      hashData2 = p__certificateIssuer;
297
298
    } else {
      hashData2 = hash.get_sha256_empty_string(); // Hash of empty string
299
    }
300
301
302
303
    loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256__1: Hash (Data input)=", hashData1);
    loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256__1: Hash (Signer identifier input)=", hashData2);
    hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input)
    OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) )
304
    hash.generate(hashData1, hashData);
305
    loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256__1: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData);
306
    // Check the signature
307
    security_ecc k(ec_elliptic_curves::nist_p_256, p__ecdsaNistp256PublicKeyX, p__ecdsaNistp256PublicKeyY);
308
    //security_ecc k(ec_elliptic_curves::nist_p_256);
309
    if (k.sign_verif(hashData, p__signature) == 0) {
310
311
312
313
314
315
316
317
318
319
      return TRUE;
    }

    return FALSE;
  }

  /**
   * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp256WithSha256(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& p__ecdsaBrainpoolp256PublicKeyCompressed);
   * \brief Verify the signature of the specified data
   * \param[in] p__toBeVerifiedData The data to be verified
320
   * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
321
322
323
324
325
326
327
328
329
330
331
332
   * \param[in] p__signature The signature
   * \param[in] p__ecdsaBrainpoolp256PublicKeyCompressed The compressed public key (x coordinate only)
   * \return true on success, false otherwise
   */
  BOOLEAN fx__verifyWithEcdsaBrainpoolp256WithSha256(
                                                     const OCTETSTRING& p__toBeVerifiedData,
                                                     const OCTETSTRING& p__certificateIssuer,
                                                     const OCTETSTRING& p__signature,
                                                     const OCTETSTRING& p__ecdsaBrainpoolp256PublicKeyCompressed,
                                                     const INTEGER& p__compressedMode
                                                     ) {
    // Sanity checks
333
    if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaBrainpoolp256PublicKeyCompressed.lengthof() != 32)) {
334
335
336
337
338
339
      loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp256WithSha256: Wrong parameters");
      return FALSE;
    }

    // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) )
    sha256 hash;
340
341
342
    OCTETSTRING hashData1; // Hash (Data input)
    hash.generate(p__toBeVerifiedData, hashData1);
    OCTETSTRING hashData2; // Hash (Signer identifier input)
343
    if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input)
344
      hashData2 = p__certificateIssuer;
345
346
    } else {
      hashData2 = hash.get_sha256_empty_string(); // Hash of empty string
347
    }
348
349
350
351
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256WithSha256: Hash (Data input)=", hashData1);
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256WithSha256: Hash (Signer identifier input)=", hashData2);
    hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input)
    OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) )
352
    hash.generate(hashData1, hashData);
353
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData);
354
    // Check the signature
355
356
    security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__ecdsaBrainpoolp256PublicKeyCompressed, (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1);
    if (k.sign_verif(hashData, p__signature) == 0) {
357
358
359
360
361
362
363
364
365
366
      return TRUE;
    }

    return FALSE;
  }

  /**
   * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp256WithSha256_1(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& p__ecdsaBrainpoolp256PublicKeyX, const OCTETSTRING& p__ecdsaBrainpoolp256PublicKeyY);
   * \brief Verify the signature of the specified data
   * \param[in] p__toBeVerifiedData The data to be verified
367
   * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
368
369
370
371
372
373
374
   * \param[in] p__signature The signature
   * \param[in] p__ecdsaBrainpoolp256PublicKeyX The public key (x coordinate)
   * \param[in] p__ecdsaBrainpoolp256PublicKeyY The public key (y coordinate)
   * \return true on success, false otherwise
   */
  BOOLEAN fx__verifyWithEcdsaBrainpoolp256WithSha256__1(
                                                        const OCTETSTRING& p__toBeVerifiedData,
375
                                                        const OCTETSTRING& p__certificateIssuer,
376
377
378
379
380
                                                        const OCTETSTRING& p__signature,
                                                        const OCTETSTRING& p__ecdsaBrainpoolp256PublicKeyX,
                                                        const OCTETSTRING& p__ecdsaBrainpoolp256PublicKeyY
                                                        ) {
    // Sanity checks
381
    if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64)) {
382
383
384
385
386
387
      loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp256WithSha256__1: Wrong parameters");
      return FALSE;
    }

    // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) )
    sha256 hash;
388
389
390
    OCTETSTRING hashData1; // Hash (Data input)
    hash.generate(p__toBeVerifiedData, hashData1);
    OCTETSTRING hashData2; // Hash (Signer identifier input)
391
    if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input)
392
      hashData2 = p__certificateIssuer;
393
394
    } else {
      hashData2 = hash.get_sha256_empty_string(); // Hash of empty string
395
    }
396
397
398
399
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256WithSha256__1: Hash (Data input)=", hashData1);
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256WithSha256__1: Hash (Signer identifier input)=", hashData2);
    hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input)
    OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) )
400
    hash.generate(hashData1, hashData);
401
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256WithSha256__1: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData);
402
    // Check the signature
403
404
    security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__ecdsaBrainpoolp256PublicKeyX, p__ecdsaBrainpoolp256PublicKeyY);
    if (k.sign_verif(hashData, p__signature) == 0) {
405
406
407
408
409
410
411
412
413
414
      return TRUE;
    }

    return FALSE;
  }

  /**
   * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp384WithSha384(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& p__ecdsaBrainpoolp384PublicKeyCompressed);
   * \brief Verify the signature of the specified data
   * \param[in] p__toBeVerifiedData The data to be verified
415
   * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
416
417
418
419
420
421
422
423
424
425
426
427
   * \param[in] p__signature The signature
   * \param[in] p__ecdsaBrainpoolp384PublicKeyCompressed The compressed public key (x coordinate only)
   * \return true on success, false otherwise
   */
  BOOLEAN fx__verifyWithEcdsaBrainpoolp384WithSha384(
                                                     const OCTETSTRING& p__toBeVerifiedData,
                                                     const OCTETSTRING& p__certificateIssuer,
                                                     const OCTETSTRING& p__signature,
                                                     const OCTETSTRING& p__ecdsaBrainpoolp384PublicKeyCompressed,
                                                     const INTEGER& p__compressedMode
                                                     ) {
    // Sanity checks
428
    if ((p__certificateIssuer.lengthof() != 48) || (p__signature.lengthof() != 96) || (p__ecdsaBrainpoolp384PublicKeyCompressed.lengthof() != 48)) {
429
430
431
432
433
434
      loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp384WithSha384: Wrong parameters");
      return FALSE;
    }

    // Calculate the SHA384 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) )
    sha384 hash;
435
436
437
    OCTETSTRING hashData1; // Hash (Data input)
    hash.generate(p__toBeVerifiedData, hashData1);
    OCTETSTRING hashData2; // Hash (Signer identifier input)
438
    if (p__certificateIssuer != int2oct(0, 48)) { // || Hash (Signer identifier input)
439
      hashData2 = p__certificateIssuer;
440
441
    } else {
      hashData2 = hash.get_sha384_empty_string(); // Hash of empty string
442
    }
443
444
445
446
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384WithSha384: Hash (Data input)=", hashData1);
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384WithSha384: Hash (Signer identifier input)=", hashData2);
    hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input)
    OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) )
447
    hash.generate(hashData1, hashData);
448
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384WithSha384: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData);
449
    // Check the signature
450
451
    security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__ecdsaBrainpoolp384PublicKeyCompressed, (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1);
    if (k.sign_verif(hashData, p__signature) == 0) {
452
453
454
455
456
457
458
459
460
461
      return TRUE;
    }

    return FALSE;
  }

  /**
   * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp384WithSha384_1(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& p__ecdsaBrainpoolp384PublicKeyX, const OCTETSTRING& p__ecdsaBrainpoolp384PublicKeyY);
   * \brief Verify the signature of the specified data
   * \param[in] p__toBeVerifiedData The data to be verified
462
   * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate
463
464
465
466
467
468
469
   * \param[in] p__signature The signature
   * \param[in] p__ecdsaBrainpoolp384PublicKeyX The public key (x coordinate)
   * \param[in] p__ecdsaBrainpoolp384PublicKeyY The public key (y coordinate)
   * \return true on success, false otherwise
   */
  BOOLEAN fx__verifyWithEcdsaBrainpoolp384WithSha384__1(
                                                        const OCTETSTRING& p__toBeVerifiedData,
470
                                                        const OCTETSTRING& p__certificateIssuer,
471
472
473
474
475
                                                        const OCTETSTRING& p__signature,
                                                        const OCTETSTRING& p__ecdsaBrainpoolp384PublicKeyX,
                                                        const OCTETSTRING& p__ecdsaBrainpoolp384PublicKeyY
                                                        ) {
    // Sanity checks
476
    if ((p__certificateIssuer.lengthof() != 48) || (p__signature.lengthof() != 96)) {
477
478
479
480
481
482
      loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp384WithSha384__1: Wrong parameters");
      return FALSE;
    }

    // Calculate the SHA384 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) )
    sha384 hash;
483
484
485
    OCTETSTRING hashData1; // Hash (Data input)
    hash.generate(p__toBeVerifiedData, hashData1);
    OCTETSTRING hashData2; // Hash (Signer identifier input)
486
    if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input)
487
      hashData2 = p__certificateIssuer;
488
489
    } else {
      hashData2 = hash.get_sha384_empty_string(); // Hash of empty string
490
    }
491
492
493
494
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384WithSha384: Hash (Data input)=", hashData1);
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384WithSha384: Hash (Signer identifier input)=", hashData2);
    hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input)
    OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) )
495
    hash.generate(hashData1, hashData);
496
    loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384WithSha384: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData);
497
    // Check the signature
498
499
    security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__ecdsaBrainpoolp384PublicKeyX, p__ecdsaBrainpoolp384PublicKeyY);
    if (k.sign_verif(hashData, p__signature) == 0) {
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
      return TRUE;
    }

    return FALSE;
  }

  /**
   * \fn OCTETSTRING fx__test__hmac__sha256(const OCTETSTRING& p__k, const OCTETSTRING& p__m);
   * \brief Generate a HMAC-SHA256 value based on the provided secret key
   * \param[in] p__k The secret key used for the HMAC calculation
   * \param[in] p__m The message
   * \return The HMAC value resized to 16-byte
   */
  OCTETSTRING fx__test__hmac__sha256(const OCTETSTRING& p__k, const OCTETSTRING& p__m) {
    loggers::get_instance().log(">>> fx__test__hmac__sha256");

    hmac h(hash_algorithms::sha_256); // TODO Use ec_encryption_algorithm
517
518
    OCTETSTRING t;
    if (h.generate(p__m, p__k, t) == -1) {
519
      loggers::get_instance().warning("fx__test__hmac__sha256: Failed to generate HMAC");
520
      return OCTETSTRING(0, nullptr);
521
    }
522
    loggers::get_instance().log_msg("fx__test__hmac__sha256: HMAC: ", t);
523

524
    return t;
525
526
527
528
529
530
531
532
533
534
535
536
537
538
  }

  /**
   * \fn OCTETSTRING fx__test__encrypt__aes__128__ccm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__pt);
   * \brief Encrypt the message using AES 128 CCM algorithm
   * \param[in] p__k The symmetric encryption key
   * \param[in] p__n The initial vector, nonce vector
   * \param[in] p__pt The message to encrypt
   * \return The encrypted message concatenated to the AES 128 CCM tag
   */
  OCTETSTRING fx__test__encrypt__aes__128__ccm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__pt) {
    loggers::get_instance().log(">>> fx__test__encrypt__aes__128__ccm__test");
    
    security_ecc ec(ec_elliptic_curves::nist_p_256);
539
540
    OCTETSTRING enc_message;
    if (ec.encrypt(encryption_algotithm::aes_128_ccm, p__k, p__n, p__pt, enc_message) == -1) {
541
      loggers::get_instance().warning("fx__test__encrypt__aes__128__ccm__test: Failed to encrypt message");
542
      return OCTETSTRING(0, nullptr);
543
    }
544
545
    OCTETSTRING os(enc_message + ec.tag());
    loggers::get_instance().log_msg("fx__test__encrypt__aes__128__ccm__test: encrypted message: ", os);
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562

    return os;
  }
  
  /**
   * \fn OCTETSTRING fx__test__decrypt__aes__128__ccm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__ct);
   * \brief Encrypt the message using AES 128 CCM algorithm
   * \param[in] p__k The symmetric encryption key
   * \param[in] p__n The initial vector, nonce vector
   * \param[in] p__ct The encrypted message concatenated to the AES 128 CCM tag
   * \return The original message
   */
  OCTETSTRING fx__test__decrypt__aes__128__ccm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__ct) {
    loggers::get_instance().log(">>> fx__test__decrypt__aes__128__ccm__test");
    
    security_ecc ec(ec_elliptic_curves::nist_p_256);
    // Extract the tag
563
    OCTETSTRING tag(16, p__ct.lengthof() - 16 + static_cast<const unsigned char*>(p__ct));
564
    loggers::get_instance().log_msg("fx__test__decrypt__aes__128__ccm__test: tag: ", tag);
565
    // Remove the tag from the end of the encrypted message
566
    OCTETSTRING ct(p__ct.lengthof() - 16, static_cast<const unsigned char*>(p__ct));
567
    loggers::get_instance().log_msg("fx__test__decrypt__aes__128__ccm__test: ct: ", ct);
568
    
569
    OCTETSTRING message;
570
    if (ec.decrypt(encryption_algotithm::aes_128_ccm, p__k, p__n, tag, ct, message) == -1) {
571
      loggers::get_instance().warning("fx__test__decrypt__aes__128__ccm__test: Failed to decrypt message");
572
      return OCTETSTRING(0, nullptr);
573
    }
574
    loggers::get_instance().log_to_hexa("fx__test__decrypt__aes__128__ccm__test: decrypted message: ", message);
575
    
576
    return message;
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
  }
  
  /**
   * \fn OCTETSTRING fx__encryptWithEciesNistp256WithSha256(const OCTETSTRING& p__toBeEncryptedSecuredMessage, const OCTETSTRING& p__recipientsPublicKeyX, const OCTETSTRING& p__recipientsPublicKeyY, OCTETSTRING& p__publicEphemeralKeyX, OCTETSTRING& p__publicEphemeralKeyY, OCTETSTRING& p__encrypted__sym__key, OCTETSTRING& p__authentication__vector, OCTETSTRING& p__nonce);
   * \brief Encrypt the message using ECIES algorithm to encrypt AES 128 CCM symmetric key, as defined in IEEE Std 1609.2-2017
   * \param[in] p__toBeEncryptedSecuredMessage The message to be encrypted
   * \param[in] p__recipientsPublicKeyCompressed The Recipient's compressed public key
   * \param[in] p__compressedMode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
   * \param[out] p__publicEphemeralKeyCompressed The public ephemeral compressed key
   * \param[out] p__ephemeralCompressedMode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
   * \param[out] p__encrypted__sym__key The encrypted AES 128 symmetric key
   * \param[out] p__authentication__vector The tag of the encrypted AES 128 symmetric key
   * \param[out] p__nonce The nonce vector
   * \return The original message
   * \see IEEE Std 1609.2-2017 Clause 5.3.5 Public key encryption algorithms: ECIES
   * \see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/
   * \see http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf
   */
  // TODO Use common function for both fx__encryptWithEciesxxx and fx__decryptWithEciesxxx function
  OCTETSTRING fx__encryptWithEciesNistp256WithSha256(const OCTETSTRING& p__toBeEncryptedSecuredMessage, const OCTETSTRING& p__recipientsPublicKeyCompressed, const INTEGER& p__compressedMode, OCTETSTRING& p__publicEphemeralKeyCompressed, INTEGER& p__ephemeralCompressedMode, OCTETSTRING& p__encrypted__sym__key, OCTETSTRING& p__authentication__vector, OCTETSTRING& p__nonce) {
    loggers::get_instance().log_msg(">>> fx__encryptWithEciesNistp256WithSha256: p__toBeEncryptedSecuredMessage: ", p__toBeEncryptedSecuredMessage);
garciay's avatar
garciay committed
598
    loggers::get_instance().log_msg(">>> fx__encryptWithEciesNistp256WithSha256: p__recipientsPublicKeyCompressed", p__recipientsPublicKeyCompressed);
599
600
601
602
603
604
    loggers::get_instance().log(">>> fx__encryptWithEciesNistp256WithSha256: p__compressedMode: %d", static_cast<int>(p__compressedMode));
    
    // 1. Generate new Private/Public key
    security_ecc ec(ec_elliptic_curves::nist_p_256);
    if (ec.generate() == -1) {
      loggers::get_instance().warning("fx__encryptWithEciesNistp256WithSha256: Failed to generate ephemeral keys");
605
      return OCTETSTRING(0, nullptr);
606
607
    }
    // 2. Generate and derive shared secret
608
    security_ecc ec_comp(ec_elliptic_curves::nist_p_256, p__recipientsPublicKeyCompressed, (static_cast<int>(p__compressedMode) == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1);
609
610
    if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y()) == -1) {
      loggers::get_instance().warning("fx__encryptWithEciesNistp256WithSha256: Failed to generate and derive secret key");
611
      return OCTETSTRING(0, nullptr);
612
613
    }
    // Set the encrypted symmetric key
614
615
    p__encrypted__sym__key = ec.encrypted_symmetric_key();
    loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: Encrypted symmetric key: ", p__encrypted__sym__key);
616
    // Set the tag of the symmetric key encryption
617
618
    p__authentication__vector = ec.tag();
    loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: p__authentication__vector: ", p__authentication__vector);
619
    // Set ephemeral public keys
620
621
    p__publicEphemeralKeyCompressed = ec.public_key_compressed();
    loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: Ephemeral public compressed key: ", p__publicEphemeralKeyCompressed);
622
    p__ephemeralCompressedMode = (ec.public_key_compressed_mode() == ecc_compressed_mode::compressed_y_0) ? 0 : 1;
garciay's avatar
garciay committed
623
    loggers::get_instance().log("fx__encryptWithEciesNistp256WithSha256: Ephemeral public compressed mode: %d", p__ephemeralCompressedMode);
624
    // 3. Retrieve AES 128 parameters
625
626
627
628
    p__nonce = ec.nonce();
    loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: p__nonce: ", p__nonce);
    OCTETSTRING enc_symm_key = ec.symmetric_encryption_key();
    loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: enc_symm_key: ", enc_symm_key);
629
    // 4. Encrypt the data using AES-128 CCM
630
631
    OCTETSTRING enc_message;
    if (ec.encrypt(encryption_algotithm::aes_128_ccm, ec.symmetric_encryption_key(), ec.nonce(), p__toBeEncryptedSecuredMessage, enc_message) == -1) {
632
      loggers::get_instance().warning("fx__encryptWithEciesNistp256WithSha256: Failed to encrypt message");
633
      return OCTETSTRING(0, nullptr);
634
    }
635
636
    enc_message += ec.tag();
    loggers::get_instance().log_to_hexa("fx__encryptWithEciesNistp256WithSha256: enc message||Tag: ", enc_message);
637
    
638
    return enc_message;
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
  }

  /**
   * \fn OCTETSTRING fx__decryptWithEciesNistp256WithSha256(const OCTETSTRING& p__encryptedSecuredMessage, const OCTETSTRING& p__privateEncKey, const OCTETSTRING& p__publicEphemeralKeyX, const OCTETSTRING& p__publicEphemeralKeyY, const OCTETSTRING& p__encrypted__sym__key, const OCTETSTRING& p__authentication__vector, const OCTETSTRING& p__nonce);
   * \brief Decrypt the message using ECIES algorithm to decrypt AES 128 CCM symmetric key, as defined in IEEE Std 1609.2-2017
   * \param[in] p__encryptedSecuredMessage The encrypted message
   * \param[in] p__privateEncKey The private encryption key
   * \param[in] p__publicEphemeralKeyCompressed The public ephemeral compressed key
   * \param[in] p__ephemeralCompressedMode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise
   * \param[in] p__encrypted__sym__key The encrypted AES 128 symmetric key
   * \param[in] p__authentication__vector The tag of the encrypted AES 128 symmetric key
   * \param[in] p__nonce The nonce vector
   * \return The original message
   * \see IEEE Std 1609.2-2017 Clause 5.3.5 Public key encryption algorithms: ECIES
   * \see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/
   * \see http://digital.csic.es/bitstream/10261/32671/1/V2-I2-P7-13.pdf
   */
  // TODO Use common function for both fx__encryptWithEciesxxx and fx__decryptWithEciesxxx function
  OCTETSTRING fx__decryptWithEciesNistp256WithSha256(const OCTETSTRING& p__encryptedSecuredMessage, const OCTETSTRING& p__privateEncKey, const OCTETSTRING& p__publicEphemeralKeyCompressed, const INTEGER& p__ephemeralCompressedMode, const OCTETSTRING& p__encrypted__sym__key, const OCTETSTRING& p__authentication__vector, const OCTETSTRING& p__nonce) {
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__toBeEncryptedSecuredMessage: ", p__encryptedSecuredMessage);
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__privateEncKey: ", p__privateEncKey);
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__publicEphemeralKeyCompressed: ", p__publicEphemeralKeyCompressed);
    loggers::get_instance().log(">>> fx__decryptWithEciesNistp256WithSha256: p__ephemeralCompressedMode: %d", static_cast<int>(p__ephemeralCompressedMode));
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__nonce: ", p__nonce);
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__authentication__vector: ", p__authentication__vector);
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesNistp256WithSha256: p__encrypted__sym__key: ", p__encrypted__sym__key);

    // 1. Create security_ecc instance
667
668
    security_ecc ec(ec_elliptic_curves::nist_p_256, p__privateEncKey);
    security_ecc ec_comp(ec_elliptic_curves::nist_p_256, p__publicEphemeralKeyCompressed, (static_cast<int>(p__ephemeralCompressedMode) == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1);
669
670
    
    // 2. Generate the shared secret value based on recipient's public ephemeral keys will be required
671
    if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, p__privateEncKey, ec_comp.public_key_x(), ec_comp.public_key_y(), p__encrypted__sym__key, p__nonce, p__authentication__vector) == -1) {
672
      loggers::get_instance().warning("fx__decryptWithEciesNistp256WithSha256: Failed to generate shared secret");
673
      return OCTETSTRING(0, nullptr);
674
675
676
    }
    
    // Decrypt the message
677
678
    OCTETSTRING enc_message(p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof(), static_cast<const unsigned char*>(p__encryptedSecuredMessage)); // Extract the encrypted message
    loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: enc_message: ", enc_message); // Extract the ctag value
679
    OCTETSTRING tag(ec.tag().lengthof(), static_cast<const unsigned char*>(p__encryptedSecuredMessage) + p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof());
680
681
    loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: tag: ", tag);
    OCTETSTRING message;
682
683
    if (ec.decrypt(tag, enc_message, message) == -1) {
      loggers::get_instance().warning("fx__decryptWithEciesNistp256WithSha256: Failed to generate shared secret");
684
      return OCTETSTRING(0, nullptr);
685
    }
686
    loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: dec message: ", message);
687
    
688
    return message;
689
690
691
692
693
694
695
696
697
698
  }
  
  OCTETSTRING fx__encryptWithEciesBrainpoolp256WithSha256(const OCTETSTRING& p__toBeEncryptedSecuredMessage, const OCTETSTRING& p__recipientsPublicKeyCompressed, const INTEGER& p__compressedMode, OCTETSTRING& p__publicEphemeralKeyCompressed, INTEGER& p__ephemeralCompressedMode, OCTETSTRING& p__encrypted__sym__key, OCTETSTRING& p__authentication__vector, OCTETSTRING& p__nonce) {
    loggers::get_instance().log_msg(">>> fx__encryptWithEciesBrainpoolp256WithSha256: p__toBeEncryptedSecuredMessage: ", p__toBeEncryptedSecuredMessage);
    loggers::get_instance().log_msg(">>> fx__encryptWithEciesBrainpoolp256WithSha256: p__recipientsPublicKeyCompressed: ", p__recipientsPublicKeyCompressed);
    loggers::get_instance().log(">>> fx__encryptWithEciesBrainpoolp256WithSha256: p__compressedMode: %d", static_cast<int>(p__compressedMode));

    // 1. Generate new Private/Public key
    security_ecc ec(ec_elliptic_curves::brainpool_p_256_r1);
    if (ec.generate() == -1) {
699
700
      loggers::get_instance().warning(": Failed to generate ephemeral keys");
      return OCTETSTRING(0, nullptr);
701
702
    }
    // 2. Generate and derive shared secret
703
    security_ecc ec_comp(ec_elliptic_curves::brainpool_p_256_r1, p__recipientsPublicKeyCompressed, (static_cast<int>(p__compressedMode) == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1);
704
    if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, ec_comp.public_key_x(), ec_comp.public_key_y()) == -1) {
705
706
      loggers::get_instance().warning(": Failed to generate and derive secret key");
      return OCTETSTRING(0, nullptr);
707
708
    }
    // Set the encrypted symmetric key
709
710
    p__encrypted__sym__key = ec.encrypted_symmetric_key();
    loggers::get_instance().log_msg(": Encrypted symmetric key: ", p__encrypted__sym__key);
711
    // Set the tag of the symmetric key encryption
712
713
    p__authentication__vector = ec.tag();
    loggers::get_instance().log_msg(": p__authentication__vector: ", p__authentication__vector);
714
    // Set ephemeral public keys
715
716
    p__publicEphemeralKeyCompressed = ec.public_key_compressed();
    loggers::get_instance().log_msg(": Ephemeral public compressed key: ", p__publicEphemeralKeyCompressed);
717
    p__ephemeralCompressedMode = (ec.public_key_compressed_mode() == ecc_compressed_mode::compressed_y_0) ? 0 : 1;
718
    loggers::get_instance().log(": Ephemeral public compressed mode: %d: ", p__ephemeralCompressedMode);
719
    // 3. Retrieve AES 128 parameters
720
721
722
723
    p__nonce = ec.nonce();
    loggers::get_instance().log_msg(": p__nonce: ", p__nonce);
    OCTETSTRING enc_symm_key = ec.symmetric_encryption_key();
    loggers::get_instance().log_msg(": enc_symm_key: ", enc_symm_key);
724
    // 4. Encrypt the data using AES-128 CCM
725
726
727
728
    OCTETSTRING enc_message;
    if (ec.encrypt(encryption_algotithm::aes_128_ccm, ec.symmetric_encryption_key(), ec.nonce(), p__toBeEncryptedSecuredMessage, enc_message) == -1) {
      loggers::get_instance().warning(": Failed to encrypt message");
      return OCTETSTRING(0, nullptr);
729
    }
730
731
    enc_message += ec.tag();
    loggers::get_instance().log_to_hexa(": enc message||Tag: ", enc_message);
732

733
    return enc_message;
734
735
736
737
738
739
740
741
742
743
744
745
  }

  OCTETSTRING fx__decryptWithEciesBrainpoolp256WithSha256(const OCTETSTRING& p__encryptedSecuredMessage, const OCTETSTRING& p__privateEncKey, const OCTETSTRING& p__publicEphemeralKeyCompressed, const INTEGER& p__ephemeralCompressedMode, const OCTETSTRING& p__encrypted__sym__key, const OCTETSTRING& p__authentication__vector, const OCTETSTRING& p__nonce) {
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256WithSha256: p__toBeEncryptedSecuredMessage: ", p__encryptedSecuredMessage);
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256WithSha256: p__privateEncKey: ", p__privateEncKey);
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256WithSha256: p__publicEphemeralKeyCompressed: ", p__publicEphemeralKeyCompressed);
    loggers::get_instance().log(">>> fx__decryptWithEciesBrainpoolp256WithSha256: p__ephemeralCompressedMode: %d", static_cast<int>(p__ephemeralCompressedMode));
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256WithSha256: p__nonce: ", p__nonce);
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256WithSha256: p__authentication__vector: ", p__authentication__vector);
    loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256WithSha256: p__encrypted__sym__key: ", p__encrypted__sym__key);

    // 1. Create security_ecc instance
746
747
    security_ecc ec(ec_elliptic_curves::brainpool_p_256_r1, p__privateEncKey);
    security_ecc ec_comp(ec_elliptic_curves::brainpool_p_256_r1, p__publicEphemeralKeyCompressed, (static_cast<int>(p__ephemeralCompressedMode) == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1);
748
749

    // 2. Generate the shared secret value based on recipient's public ephemeral keys will be required
750
    if (ec.generate_and_derive_ephemeral_key(encryption_algotithm::aes_128_ccm, p__privateEncKey, ec_comp.public_key_x(), ec_comp.public_key_y(), p__encrypted__sym__key, p__nonce, p__authentication__vector) == -1) {
751
      loggers::get_instance().warning("fx__decryptWithEciesBrainpoolp256WithSha256: Failed to generate shared secret");
752
      return OCTETSTRING(0, nullptr);
753
754
    }

755
756
757
    // Decrypt the message
    OCTETSTRING enc_message(p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof(), static_cast<const unsigned char*>(p__encryptedSecuredMessage)); // Extract the encrypted message
    loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256WithSha256: enc_message: ", enc_message); // Extract the ctag value
758
    OCTETSTRING tag(ec.tag().lengthof(), static_cast<const unsigned char*>(p__encryptedSecuredMessage) + p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof());
759
760
    loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256WithSha256: tag: ", tag);
    OCTETSTRING message;
761
762
    if (ec.decrypt(tag, enc_message, message) == -1) {
      loggers::get_instance().warning("fx__decryptWithEciesBrainpoolp256WithSha256: Failed to generate shared secret");
763
      return OCTETSTRING(0, nullptr);
764
    }
765
    loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256WithSha256: dec message: ", message);
766

767
    return message;
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
  }

  /**
   * \brief    Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm.
   *          This function should not be used by the ATS
   * \param   p_privateKey    The new private key value
   * \param   p_publicKeyX    The new public key value (x coordinate)
   * \param   p_publicKeyX    The new public key value (y coordinate)
   * \return  true on success, false otherwise
   fx_generateKeyPair_nistp256(out octetstring<UInt64> p_privateKey, out octetstring p_publicKeyX, out octetstring p_publicKeyY) return boolean;
  */
  BOOLEAN fx__generateKeyPair__nistp256(
                                        OCTETSTRING& p__privateKey,
                                        OCTETSTRING& p__publicKeyX,
                                        OCTETSTRING& p__publicKeyY,
                                        OCTETSTRING& p__publicKeyCompressed,
                                        INTEGER& p__compressedMode
                                        ) {
    security_ecc k(ec_elliptic_curves::nist_p_256);
    if (k.generate() != 0) {
788
789
790
791
      p__privateKey = OCTETSTRING(0, nullptr);
      p__publicKeyX = OCTETSTRING(0, nullptr);
      p__publicKeyY = OCTETSTRING(0, nullptr);
      p__publicKeyCompressed = OCTETSTRING(0, nullptr);
792
793
794
      return FALSE;
    }
    // Sanity checks
795
    if (k.private_key().lengthof() != 32) {
796
797
798
      loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid private key size");
      return FALSE;
    }
799
    if (k.public_key_x().lengthof() != 32) {
800
801
802
      loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid public key X-coordonate size");
      return FALSE;
    }
803
    if (k.public_key_y().lengthof() != 32) {
804
805
806
      loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid public key Y-coordonate size");
      return FALSE;
    }
807
    if (k.public_key_compressed().lengthof() != 32) {
808
809
810
      loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid public compressed key size");
      return FALSE;
    }
811
812
813
814
    p__privateKey = k.private_key();
    p__publicKeyX = k.public_key_x();
    p__publicKeyY = k.public_key_y();
    p__publicKeyCompressed = k.public_key_compressed();
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
    p__compressedMode = INTEGER((int)k.public_key_compressed_mode());
    
    return TRUE;
  }

  /**
   * \brief    Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm.
   *          This function should not be used by the ATS
   * \param   p_privateKey    The new private key value
   * \param   p_publicKeyX    The new public key value (x coordinate)
   * \param   p_publicKeyX    The new public key value (y coordinate)
   * \return  true on success, false otherwise
   fx_generateKeyPair_nistp256(out octetstring<UInt64> p_privateKey, out octetstring p_publicKeyX, out octetstring p_publicKeyY) return boolean;
  */
  BOOLEAN fx__generateKeyPair__brainpoolp256(
                                             OCTETSTRING& p__privateKey,
                                             OCTETSTRING& p__publicKeyX,
                                             OCTETSTRING& p__publicKeyY,
                                             OCTETSTRING& p__publicKeyCompressed,
                                             INTEGER& p__compressedMode
                                             ) {
    security_ecc k(ec_elliptic_curves::brainpool_p_256_r1);
    if (k.generate() != 0) {
838
839
840
841
      p__privateKey = OCTETSTRING(0, nullptr);
      p__publicKeyX = OCTETSTRING(0, nullptr);
      p__publicKeyY = OCTETSTRING(0, nullptr);
      p__publicKeyCompressed = OCTETSTRING(0, nullptr);
842
843
844
845
      return FALSE;
    }

    // Sanity checks
846
    if (k.private_key().lengthof() != 32) {
847
848
849
      loggers::get_instance().error("fx__generateKeyPair__brainpoolp256: Invalid private key size");
      return FALSE;
    }
850
    if (k.public_key_x().lengthof() != 32) {
851
852
853
      loggers::get_instance().error("fx__generateKeyPair__brainpoolp256: Invalid public key X-coordonate size");
      return FALSE;
    }
854
    if (k.public_key_y().lengthof() != 32) {
855
856
857
      loggers::get_instance().error("fx__generateKeyPair__brainpoolp256: Invalid public key Y-coordonate size");
      return FALSE;
    }
858
    if (k.public_key_compressed().lengthof() != 32) {
859
860
861
      loggers::get_instance().error("fx__generateKeyPair__brainpoolp256: Invalid public compressed key size");
      return FALSE;
    }
862
863
864
865
    p__privateKey = k.private_key();
    p__publicKeyX = k.public_key_x();
    p__publicKeyY = k.public_key_y();
    p__publicKeyCompressed = k.public_key_compressed();
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
    p__compressedMode = INTEGER((int)k.public_key_compressed_mode());
    
    return TRUE;
  }

  /**
   * \brief    Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm.
   *          This function should not be used by the ATS
   * \param   p_privateKey    The new private key value
   * \param   p_publicKeyX    The new public key value (x coordinate)
   * \param   p_publicKeyX    The new public key value (y coordinate)
   * \return  true on success, false otherwise
   fx_generateKeyPair_nistp256(out octetstring<UInt64> p_privateKey, out octetstring p_publicKeyX, out octetstring p_publicKeyY) return boolean;
  */
  BOOLEAN fx__generateKeyPair__brainpoolp384(
                                             OCTETSTRING& p__privateKey,
                                             OCTETSTRING& p__publicKeyX,
                                             OCTETSTRING& p__publicKeyY,
                                             OCTETSTRING& p__publicKeyCompressed,
                                             INTEGER& p__compressedMode
                                             ) {
    security_ecc k(ec_elliptic_curves::brainpool_p_384_r1);
    if (k.generate() != 0) {
889
890
891
892
      p__privateKey = OCTETSTRING(0, nullptr);
      p__publicKeyX = OCTETSTRING(0, nullptr);
      p__publicKeyY = OCTETSTRING(0, nullptr);
      p__publicKeyCompressed = OCTETSTRING(0, nullptr);
893
894
895
896
      return FALSE;
    }

    // Sanity checks
897
    if (k.private_key().lengthof() != 48) {
898
899
900
      loggers::get_instance().error("fx__generateKeyPair__brainpoolp384: Invalid private key size");
      return FALSE;
    }
901
    if (k.public_key_x().lengthof() != 48) {
902
903
904
      loggers::get_instance().error("fx__generateKeyPair__brainpoolp384: Invalid public key X-coordonate size");
      return FALSE;
    }
905
    if (k.public_key_y().lengthof() != 48) {
906
907
908
      loggers::get_instance().error("fx__generateKeyPair__brainpoolp384: Invalid public key Y-coordonate size");
      return FALSE;
    }
909
    if (k.public_key_compressed().lengthof() != 48) {
910
911
912
      loggers::get_instance().error("fx__generateKeyPair__brainpoolp384: Invalid public compressed key size");
      return FALSE;
    }
913
914
915
916
    p__privateKey = k.private_key();
    p__publicKeyX = k.public_key_x();
    p__publicKeyY = k.public_key_y();
    p__publicKeyCompressed = k.public_key_compressed();
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
    p__compressedMode = INTEGER((int)k.public_key_compressed_mode());

    return TRUE;
  }

  //        group encryption

  //        group certificatesLoader

  /** 
   * \brief    Load in memory cache the certificates available in the specified directory
   * \param   p_rootDirectory Root directory to access to the certificates identified by the certificate ID
   * \param   p_configId      A configuration identifier
   * @remark  This method SHALL be call before any usage of certificates
   * \return  true on success, false otherwise
   fx_loadCertificates(in charstring p_rootDirectory, in charstring p_configId) return boolean;
  */
  BOOLEAN fx__loadCertificates(
                               const CHARSTRING& p__rootDirectory,
                               const CHARSTRING& p__configId
                               ) {
    loggers::get_instance().log(">>> fx__loadCertificates: '%s', '%s'", static_cast<const char*>(p__rootDirectory), static_cast<const char*>(p__configId));

    std::string str(static_cast<const char*>(p__rootDirectory));
    if (p__configId.lengthof() != 0) {
      str += "/";
      str += std::string(static_cast<const char*>(p__configId));
    }
    params params;
    params.insert(std::pair<std::string, std::string>(std::string("sec_db_path"), str));
    if (security_services::get_instance().setup(params) == -1) {
      return FALSE;
    }
    
    return TRUE;
  }

garciay's avatar
garciay committed
954
  BOOLEAN fx__store__certificate(const CHARSTRING& p__cert__id, const OCTETSTRING& p__cert, const OCTETSTRING& p__private__key, const OCTETSTRING& p__public__key__x, const OCTETSTRING& p__public__key__y, const OCTETSTRING& p__public__key__compressed, const INTEGER& p__public__key__compressed__mode, const OCTETSTRING& p__hash, const OCTETSTRING& p__hashid8, const OCTETSTRING& p__issuer, const OCTETSTRING_template& p__private__enc__key, const OCTETSTRING_template& p__public__enc__key__x, const OCTETSTRING_template& p__public__enc__key__y, const OCTETSTRING_template& p__public__enc__compressed__key, const INTEGER_template& p__public__enc__key__compressed__mode) {
955
956
957
958
959
960
961
    loggers::get_instance().log(">>> fx__store__certificate: '%s'", static_cast<const char*>(p__cert__id));

    int result;
    if (!p__private__enc__key.is_omit()) {
      const OCTETSTRING private_enc_key = p__private__enc__key.valueof();
      const OCTETSTRING public_enc_key_x = p__public__enc__key__x.valueof();
      const OCTETSTRING public_enc_key_y = p__public__enc__key__y.valueof();
garciay's avatar
garciay committed
962
      result = security_services::get_instance().store_certificate(p__cert__id, p__cert, p__private__key, p__public__key__x, p__public__key__y, p__public__key__compressed, p__public__key__compressed__mode, p__hash, p__hashid8, p__issuer, p__private__enc__key.valueof(), p__public__enc__key__x.valueof(), p__public__enc__key__y.valueof(), p__public__enc__compressed__key.valueof(), p__public__enc__key__compressed__mode.valueof());
963
    } else {
garciay's avatar
garciay committed
964
      result = security_services::get_instance().store_certificate(p__cert__id, p__cert, p__private__key, p__public__key__x, p__public__key__y, p__public__key__compressed, p__public__key__compressed__mode, p__hash, p__hashid8, p__issuer, OCTETSTRING(0, nullptr), OCTETSTRING(0, nullptr), OCTETSTRING(0, nullptr), OCTETSTRING(0, nullptr), INTEGER(-1));
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
    }
    
    return (result == 0);
  }
  
  /**
   * \brief    Unload from memory cache the certificates
   * \return  true on success, false otherwise
   */
  BOOLEAN fx__unloadCertificates(
) {
    return TRUE;
  }

  /**
   * \brief    Read the specified certificate
   * \param   p_certificateId the certificate identifier
   * \param   p_certificate   the expected certificate
   * \return  true on success, false otherwise
   */
  BOOLEAN fx__readCertificate(
                              const CHARSTRING& p__certificateId,
                              OCTETSTRING& p__certificate
                              ) {
    loggers::get_instance().log(">>> fx__readCertificate: '%s'", static_cast<const char*>(p__certificateId));

    if (security_services::get_instance().read_certificate(p__certificateId, p__certificate) == -1) {
      return FALSE;
    }
    
    return TRUE;
  }

  BOOLEAN fx__readCertificateFromDigest(
                                        const OCTETSTRING& p__digest,
                                        CHARSTRING& p__certificateId) {
For faster browsing, not all history is shown. View entire blame