Created
November 13, 2024 13:22
-
-
Save randombit/90668962bf9c31a200b386c3009125e2 to your computer and use it in GitHub Desktop.
Generate EC mul test vectors using OpenSSL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define OPENSSL_SUPPRESS_DEPRECATED | |
#include <openssl/bn.h> | |
#include <openssl/ec.h> | |
#include <openssl/obj_mac.h> | |
#include <openssl/objects.h> | |
#include <stdio.h> | |
#include <vector> | |
void check_rc(const char* where, int rc, int expected_rc = 1) { | |
if(rc != expected_rc) { | |
printf("%s returned %d\n", where, rc); | |
exit(1); | |
} | |
} | |
BIGNUM* hex2bn(const char* s) { | |
auto bn = BN_new(); | |
int rc = BN_hex2bn(&bn, s); | |
if(rc == 0) { printf("hex2bn failed"); exit(1); } | |
return bn; | |
} | |
void dump(const char* what, BIGNUM* n, size_t order_bits) { | |
std::vector<uint8_t> x((order_bits + 7) / 8); | |
BN_bn2binpad(n, x.data(), x.size()); | |
printf("%s = 0x", what); | |
for(size_t i = 0; i != x.size(); ++i) { | |
printf("%02X", x[i]); | |
} | |
printf("\n"); | |
} | |
void dump(const char* what, EC_GROUP* group, EC_POINT* p, BN_CTX* ctx) { | |
uint8_t buf[256] = { 0 }; | |
size_t written = EC_POINT_point2oct(group, p, POINT_CONVERSION_COMPRESSED, | |
buf, sizeof(buf), ctx); | |
printf("%s = ", what); | |
for(size_t i = 0; i != written; ++i) { | |
printf("%02X", buf[i]); | |
} | |
printf("\n"); | |
} | |
int main() { | |
const auto nid = NID_secp256k1; | |
auto group = EC_GROUP_new_by_curve_name(nid); | |
auto bn_ctx = BN_CTX_new(); | |
const size_t bits = BN_num_bits(EC_GROUP_get0_order(group)); | |
printf("[%s]\n", OBJ_nid2sn(nid)); | |
for(size_t i = 1; i != 64; ++i) { | |
EC_POINT* basept = EC_POINT_new(group); | |
BIGNUM* basept_k = BN_new(); | |
BN_rand(basept_k, bits, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY); | |
EC_POINTs_mul(group, basept, basept_k, 0, nullptr, nullptr, bn_ctx); | |
EC_POINT* r = EC_POINT_new(group); | |
BIGNUM* n = BN_new(); | |
//BN_set_word(n, i); | |
BN_rand(n, bits, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY); | |
BN_mod(n, n, EC_GROUP_get0_order(group), bn_ctx); | |
const EC_POINT* basept_arr[1] = { basept }; | |
const BIGNUM* basept_k_arr[1] = { n }; | |
EC_POINTs_mul(group, r, nullptr, 1, basept_arr, basept_k_arr, bn_ctx); | |
dump("P", group, basept, bn_ctx); | |
dump("k", n, bits); | |
dump("Z", group, r, bn_ctx); | |
printf("\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment