github.com/ethereumproject/go-ethereum@v5.5.2+incompatible/crypto/secp256k1/libsecp256k1/src/modules/ecdh/tests_impl.h (about) 1 /********************************************************************** 2 * Copyright (c) 2015 Andrew Poelstra * 3 * Distributed under the MIT software license, see the accompanying * 4 * file COPYING or http://www.opensource.org/licenses/mit-license.php.* 5 **********************************************************************/ 6 7 #ifndef _SECP256K1_MODULE_ECDH_TESTS_ 8 #define _SECP256K1_MODULE_ECDH_TESTS_ 9 10 void test_ecdh_generator_basepoint(void) { 11 unsigned char s_one[32] = { 0 }; 12 secp256k1_pubkey point[2]; 13 int i; 14 15 s_one[31] = 1; 16 /* Check against pubkey creation when the basepoint is the generator */ 17 for (i = 0; i < 100; ++i) { 18 secp256k1_sha256_t sha; 19 unsigned char s_b32[32]; 20 unsigned char output_ecdh[32]; 21 unsigned char output_ser[32]; 22 unsigned char point_ser[33]; 23 size_t point_ser_len = sizeof(point_ser); 24 secp256k1_scalar s; 25 26 random_scalar_order(&s); 27 secp256k1_scalar_get_b32(s_b32, &s); 28 29 /* compute using ECDH function */ 30 CHECK(secp256k1_ec_pubkey_create(ctx, &point[0], s_one) == 1); 31 CHECK(secp256k1_ecdh(ctx, output_ecdh, &point[0], s_b32) == 1); 32 /* compute "explicitly" */ 33 CHECK(secp256k1_ec_pubkey_create(ctx, &point[1], s_b32) == 1); 34 CHECK(secp256k1_ec_pubkey_serialize(ctx, point_ser, &point_ser_len, &point[1], SECP256K1_EC_COMPRESSED) == 1); 35 CHECK(point_ser_len == sizeof(point_ser)); 36 secp256k1_sha256_initialize(&sha); 37 secp256k1_sha256_write(&sha, point_ser, point_ser_len); 38 secp256k1_sha256_finalize(&sha, output_ser); 39 /* compare */ 40 CHECK(memcmp(output_ecdh, output_ser, sizeof(output_ser)) == 0); 41 } 42 } 43 44 void test_bad_scalar(void) { 45 unsigned char s_zero[32] = { 0 }; 46 unsigned char s_overflow[32] = { 47 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 48 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 49 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b, 50 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41 51 }; 52 unsigned char s_rand[32] = { 0 }; 53 unsigned char output[32]; 54 secp256k1_scalar rand; 55 secp256k1_pubkey point; 56 57 /* Create random point */ 58 random_scalar_order(&rand); 59 secp256k1_scalar_get_b32(s_rand, &rand); 60 CHECK(secp256k1_ec_pubkey_create(ctx, &point, s_rand) == 1); 61 62 /* Try to multiply it by bad values */ 63 CHECK(secp256k1_ecdh(ctx, output, &point, s_zero) == 0); 64 CHECK(secp256k1_ecdh(ctx, output, &point, s_overflow) == 0); 65 /* ...and a good one */ 66 s_overflow[31] -= 1; 67 CHECK(secp256k1_ecdh(ctx, output, &point, s_overflow) == 1); 68 } 69 70 void run_ecdh_tests(void) { 71 test_ecdh_generator_basepoint(); 72 test_bad_scalar(); 73 } 74 75 #endif