Sign the input with ECDSA method and returns the signature
(self, inputb, digest_alg=OpenSSL.digest_ecdsa_sha1)
| 321 | OpenSSL.BN_free(priv_key) |
| 322 | |
| 323 | def sign(self, inputb, digest_alg=OpenSSL.digest_ecdsa_sha1): |
| 324 | """ |
| 325 | Sign the input with ECDSA method and returns the signature |
| 326 | """ |
| 327 | # pylint: disable=too-many-branches,too-many-locals |
| 328 | try: |
| 329 | size = len(inputb) |
| 330 | buff = OpenSSL.malloc(inputb, size) |
| 331 | digest = OpenSSL.malloc(0, 64) |
| 332 | if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL: |
| 333 | md_ctx = OpenSSL.EVP_MD_CTX_new() |
| 334 | else: |
| 335 | md_ctx = OpenSSL.EVP_MD_CTX_create() |
| 336 | dgst_len = OpenSSL.pointer(OpenSSL.c_int(0)) |
| 337 | siglen = OpenSSL.pointer(OpenSSL.c_int(0)) |
| 338 | sig = OpenSSL.malloc(0, 151) |
| 339 | |
| 340 | key = OpenSSL.EC_KEY_new_by_curve_name(self.curve) |
| 341 | if key == 0: |
| 342 | raise Exception("[OpenSSL] EC_KEY_new_by_curve_name FAIL ...") |
| 343 | |
| 344 | priv_key = OpenSSL.BN_bin2bn(self.privkey, len(self.privkey), 0) |
| 345 | pub_key_x = OpenSSL.BN_bin2bn(self.pubkey_x, len(self.pubkey_x), 0) |
| 346 | pub_key_y = OpenSSL.BN_bin2bn(self.pubkey_y, len(self.pubkey_y), 0) |
| 347 | |
| 348 | if (OpenSSL.EC_KEY_set_private_key(key, priv_key)) == 0: |
| 349 | raise Exception("[OpenSSL] EC_KEY_set_private_key FAIL ...") |
| 350 | |
| 351 | group = OpenSSL.EC_KEY_get0_group(key) |
| 352 | pub_key = OpenSSL.EC_POINT_new(group) |
| 353 | |
| 354 | if (OpenSSL.EC_POINT_set_affine_coordinates_GFp(group, pub_key, |
| 355 | pub_key_x, |
| 356 | pub_key_y, |
| 357 | 0)) == 0: |
| 358 | raise Exception( |
| 359 | "[OpenSSL] EC_POINT_set_affine_coordinates_GFp FAIL ...") |
| 360 | if (OpenSSL.EC_KEY_set_public_key(key, pub_key)) == 0: |
| 361 | raise Exception("[OpenSSL] EC_KEY_set_public_key FAIL ...") |
| 362 | if (OpenSSL.EC_KEY_check_key(key)) == 0: |
| 363 | raise Exception("[OpenSSL] EC_KEY_check_key FAIL ...") |
| 364 | |
| 365 | if OpenSSL._hexversion > 0x10100000 and not OpenSSL._libreSSL: |
| 366 | OpenSSL.EVP_MD_CTX_new(md_ctx) |
| 367 | else: |
| 368 | OpenSSL.EVP_MD_CTX_init(md_ctx) |
| 369 | OpenSSL.EVP_DigestInit_ex(md_ctx, digest_alg(), None) |
| 370 | |
| 371 | if (OpenSSL.EVP_DigestUpdate(md_ctx, buff, size)) == 0: |
| 372 | raise Exception("[OpenSSL] EVP_DigestUpdate FAIL ...") |
| 373 | OpenSSL.EVP_DigestFinal_ex(md_ctx, digest, dgst_len) |
| 374 | OpenSSL.ECDSA_sign(0, digest, dgst_len.contents, sig, siglen, key) |
| 375 | if (OpenSSL.ECDSA_verify(0, digest, dgst_len.contents, sig, |
| 376 | siglen.contents, key)) != 1: |
| 377 | raise Exception("[OpenSSL] ECDSA_verify FAIL ...") |
| 378 | |
| 379 | return sig.raw[:siglen.contents.value] |
| 380 |