#include "echoion/protocol/Identity.hpp" #include "echoion/protocol/Crypto.hpp" #include "echoion/protocol/Util.hpp" #include #include #include #include #include #include #include #include namespace Echoion::Protocol { namespace { using Bytes = std::vector; [[noreturn]] void fail(const char* what) { throw std::runtime_error(std::string("Identity: ") + what); } EVP_PKEY* asPkey(const std::shared_ptr& p) { return static_cast(p.get()); } // Minimal big-endian encoding of a BIGNUM (no leading zeros). Bytes bnBytes(const BIGNUM* bn) { int n = BN_num_bytes(bn); Bytes out(static_cast(n < 0 ? 0 : n), 0); if (n > 0) { BN_bn2bin(bn, out.data()); } return out; } Bytes derLength(size_t len) { if (len < 0x80) { return {static_cast(len)}; } if (len < 0x100) { return {0x81, static_cast(len)}; } return {0x82, static_cast((len >> 8) & 0xff), static_cast(len & 0xff)}; } // DER INTEGER from a non-negative big-endian magnitude. Bytes derInteger(Bytes mag) { if (mag.empty()) { mag.push_back(0); } if (mag[0] & 0x80) { mag.insert(mag.begin(), 0x00); } Bytes out; out.push_back(0x02); Bytes len = derLength(mag.size()); out.insert(out.end(), len.begin(), len.end()); out.insert(out.end(), mag.begin(), mag.end()); return out; } Bytes derIntegerFromU64(uint64_t v) { BIGNUM* bn = BN_new(); BN_set_word(bn, v); Bytes r = derInteger(bnBytes(bn)); BN_free(bn); return r; } // libtomcrypt public key: SEQ{ BITSTRING(00 07 00), INT(32), INT(x), // INT(y) }. The BITSTRING carries a leading "unused bits" byte (0x00) // plus 0x07 0x00 in the reference; we reproduce it verbatim. std::string buildPublicKeyString(const BIGNUM* x, const BIGNUM* y) { Bytes content; const uint8_t bitStr[] = {0x03, 0x02, 0x07, 0x00}; content.insert(content.end(), std::begin(bitStr), std::end(bitStr)); Bytes i32 = derIntegerFromU64(32); Bytes ix = derInteger(bnBytes(x)); Bytes iy = derInteger(bnBytes(y)); content.insert(content.end(), i32.begin(), i32.end()); content.insert(content.end(), ix.begin(), ix.end()); content.insert(content.end(), iy.begin(), iy.end()); Bytes der; der.push_back(0x30); Bytes len = derLength(content.size()); der.insert(der.end(), len.begin(), len.end()); der.insert(der.end(), content.begin(), content.end()); return Util::base64Encode(Crypto::ByteView(der.data(), der.size())); } // Uncompressed EC point (0x04 || x || y) from a public EVP_PKEY. Bytes pubPoint(EVP_PKEY* pkey) { size_t len = 0; if (EVP_PKEY_get_octet_string_param( pkey, OSSL_PKEY_PARAM_PUB_KEY, nullptr, 0, &len) != 1) { fail("cannot read public point length"); } Bytes buf(len, 0); if (EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PUB_KEY, buf.data(), len, &len) != 1) { fail("cannot read public point"); } buf.resize(len); return buf; } int countLeadingZeroBits(Crypto::ByteView data) { int count = 0; for (uint8_t b : data) { if (b == 0) { count += 8; } else { for (int bit = 0; bit < 8; ++bit) { if ((b & (1 << bit)) == 0) { ++count; } else { return count; } } } } return count; } int securityLevelFor(const std::string& pubKeyString, uint64_t offset) { std::string s = pubKeyString + std::to_string(offset); auto h = Crypto::sha1(Crypto::ByteView( reinterpret_cast(s.data()), s.size())); return countLeadingZeroBits( Crypto::ByteView(h.data(), h.size())); } // libtomcrypt DER parse → the two public-key INTEGERs (x, y). See // reference parseDerSequence: collected = [bitByte, 32, x, y]. void parseServerPub(Crypto::ByteView der, BIGNUM** x, BIGNUM** y) { size_t pos = 0; auto readLen = [&](size_t& p) -> size_t { uint8_t first = der[p++]; if (first < 0x80) { return first; } int nb = first & 0x7f; size_t len = 0; for (int i = 0; i < nb; ++i) { len = (len << 8) | der[p++]; } return len; }; if (der.empty() || der[pos++] != 0x30) { fail("server key: expected SEQUENCE"); } readLen(pos); std::vector ints; while (pos < der.size()) { uint8_t tag = der[pos++]; size_t len = readLen(pos); if (tag == 0x02) { ints.push_back( BN_bin2bn(der.data() + pos, static_cast(len), nullptr)); } pos += len; } // ints = [32, x, y]; guard against short input. if (ints.size() < 3) { for (auto* b : ints) { BN_free(b); } fail("server key: too few integers"); } *x = ints[1]; *y = ints[2]; for (size_t i = 0; i < ints.size(); ++i) { if (i != 1 && i != 2) { BN_free(ints[i]); } } } } // namespace void Identity::PKeyDeleter::operator()(void* p) const noexcept { EVP_PKEY_free(static_cast(p)); } Identity Identity::generate(int securityLevel) { EVP_PKEY* pkey = nullptr; EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr); if (!ctx) { fail("keygen ctx"); } if (EVP_PKEY_keygen_init(ctx) != 1) { EVP_PKEY_CTX_free(ctx); fail("keygen init"); } OSSL_PARAM params[2] = { OSSL_PARAM_construct_utf8_string( OSSL_PKEY_PARAM_GROUP_NAME, const_cast("prime256v1"), 0), OSSL_PARAM_construct_end()}; EVP_PKEY_CTX_set_params(ctx, params); if (EVP_PKEY_keygen(ctx, &pkey) != 1) { EVP_PKEY_CTX_free(ctx); fail("keygen"); } EVP_PKEY_CTX_free(ctx); Identity id; id.pkey_ = std::shared_ptr(pkey, PKeyDeleter{}); Bytes point = pubPoint(pkey); if (point.size() != 65 || point[0] != 0x04) { fail("unexpected public point format"); } BIGNUM* x = BN_bin2bn(point.data() + 1, 32, nullptr); BIGNUM* y = BN_bin2bn(point.data() + 33, 32, nullptr); id.publicKeyString_ = buildPublicKeyString(x, y); BN_free(x); BN_free(y); auto uidHash = Crypto::sha1(Crypto::ByteView( reinterpret_cast(id.publicKeyString_.data()), id.publicKeyString_.size())); id.uid_ = Util::base64Encode( Crypto::ByteView(uidHash.data(), uidHash.size())); // Hashcash: find the offset giving the most leading-zero bits, up to // the requested level. if (securityLevel > 0) { uint64_t offset = 0; int best = securityLevelFor(id.publicKeyString_, offset); uint64_t checked = 0; while (best < securityLevel) { ++checked; int curr = securityLevelFor(id.publicKeyString_, checked); if (curr > best) { best = curr; offset = checked; } } id.keyOffset_ = offset; } return id; } int Identity::securityLevel() const { return securityLevelFor(publicKeyString_, keyOffset_); } Identity::Bytes Identity::sign(ByteView data) const { EVP_PKEY* pkey = asPkey(pkey_); EVP_MD_CTX* md = EVP_MD_CTX_new(); if (!md) { fail("sign ctx"); } size_t siglen = 0; if (EVP_DigestSignInit(md, nullptr, EVP_sha256(), nullptr, pkey) != 1 || EVP_DigestSign(md, nullptr, &siglen, data.data(), data.size()) != 1) { EVP_MD_CTX_free(md); fail("sign init"); } Bytes sig(siglen, 0); if (EVP_DigestSign(md, sig.data(), &siglen, data.data(), data.size()) != 1) { EVP_MD_CTX_free(md); fail("sign"); } sig.resize(siglen); EVP_MD_CTX_free(md); return sig; } Identity::Bytes Identity::sharedSecret(ByteView serverPublicKeyDer) const { BIGNUM* x = nullptr; BIGNUM* y = nullptr; parseServerPub(serverPublicKeyDer, &x, &y); // Build uncompressed point 0x04 || x(32) || y(32). Bytes point(65, 0); point[0] = 0x04; BN_bn2binpad(x, point.data() + 1, 32); BN_bn2binpad(y, point.data() + 33, 32); BN_free(x); BN_free(y); EVP_PKEY* peer = nullptr; { OSSL_PARAM_BLD* bld = OSSL_PARAM_BLD_new(); OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME, "prime256v1", 0); OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_PUB_KEY, point.data(), point.size()); OSSL_PARAM* p = OSSL_PARAM_BLD_to_param(bld); EVP_PKEY_CTX* pctx = EVP_PKEY_CTX_new_from_name(nullptr, "EC", nullptr); if (!pctx || EVP_PKEY_fromdata_init(pctx) != 1 || EVP_PKEY_fromdata(pctx, &peer, EVP_PKEY_PUBLIC_KEY, p) != 1) { if (pctx) { EVP_PKEY_CTX_free(pctx); } OSSL_PARAM_free(p); OSSL_PARAM_BLD_free(bld); fail("build peer key"); } EVP_PKEY_CTX_free(pctx); OSSL_PARAM_free(p); OSSL_PARAM_BLD_free(bld); } EVP_PKEY_CTX* dctx = EVP_PKEY_CTX_new(asPkey(pkey_), nullptr); size_t secretLen = 0; if (!dctx || EVP_PKEY_derive_init(dctx) != 1 || EVP_PKEY_derive_set_peer(dctx, peer) != 1 || EVP_PKEY_derive(dctx, nullptr, &secretLen) != 1) { if (dctx) { EVP_PKEY_CTX_free(dctx); } EVP_PKEY_free(peer); fail("ecdh derive init"); } Bytes secret(secretLen, 0); if (EVP_PKEY_derive(dctx, secret.data(), &secretLen) != 1) { EVP_PKEY_CTX_free(dctx); EVP_PKEY_free(peer); fail("ecdh derive"); } secret.resize(secretLen); EVP_PKEY_CTX_free(dctx); EVP_PKEY_free(peer); // Pad/truncate to 32 bytes, then SHA-1 (matches reference). Bytes keyArr(32, 0); if (secret.size() >= 32) { std::copy(secret.end() - 32, secret.end(), keyArr.begin()); } else { std::copy(secret.begin(), secret.end(), keyArr.begin() + (32 - secret.size())); } auto h = Crypto::sha1(Crypto::ByteView(keyArr.data(), keyArr.size())); return Bytes(h.begin(), h.end()); } void Identity::save(const std::string& path) const { EVP_PKEY* pkey = asPkey(pkey_); BIO* mem = BIO_new(BIO_s_mem()); if (!PEM_write_bio_PrivateKey(mem, pkey, nullptr, nullptr, 0, nullptr, nullptr)) { BIO_free(mem); fail("serialize private key"); } char* data = nullptr; long n = BIO_get_mem_data(mem, &data); std::string pem(data, static_cast(n)); BIO_free(mem); std::ofstream out(path, std::ios::trunc); if (!out) { fail("cannot open identity file for writing"); } out << "ECHOION_IDENTITY_V1\n"; out << keyOffset_ << "\n"; out << publicKeyString_ << "\n"; out << "-----PRIVATE-----\n"; out << pem; } Identity Identity::load(const std::string& path) { std::ifstream in(path); if (!in) { fail("cannot open identity file"); } std::string magic; std::getline(in, magic); if (magic != "ECHOION_IDENTITY_V1") { fail("bad identity file magic"); } std::string offsetLine; std::getline(in, offsetLine); Identity id; id.keyOffset_ = std::stoull(offsetLine); std::getline(in, id.publicKeyString_); std::string sep; std::getline(in, sep); // -----PRIVATE----- std::string pem((std::istreambuf_iterator(in)), std::istreambuf_iterator()); BIO* mem = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); EVP_PKEY* pkey = PEM_read_bio_PrivateKey(mem, nullptr, nullptr, nullptr); BIO_free(mem); if (!pkey) { fail("cannot parse private key"); } id.pkey_ = std::shared_ptr(pkey, PKeyDeleter{}); auto uidHash = Crypto::sha1(Crypto::ByteView( reinterpret_cast(id.publicKeyString_.data()), id.publicKeyString_.size())); id.uid_ = Util::base64Encode( Crypto::ByteView(uidHash.data(), uidHash.size())); return id; } } // namespace Echoion::Protocol