From 3d050c5d2098361a98d8a2e34478b5d2e72a477c Mon Sep 17 00:00:00 2001 From: Steve McCoole Date: Fri, 1 Nov 2019 10:55:18 -0500 Subject: [PATCH 1/2] Potential fix for extracting public key from some private keys. The BigNum to Hex conversion can sometimes produce a shorter string than expected and that causes subsequent processing to fail. This PR adds padding out to 64 characters for both the x and y portions, but that may be too hard coded? --- EosioSwiftEcc/Recover/EccRecoverKey.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/EosioSwiftEcc/Recover/EccRecoverKey.swift b/EosioSwiftEcc/Recover/EccRecoverKey.swift index ec690ee9..d428ac80 100644 --- a/EosioSwiftEcc/Recover/EccRecoverKey.swift +++ b/EosioSwiftEcc/Recover/EccRecoverKey.swift @@ -60,15 +60,22 @@ public class EccRecoverKey { let xBNstr = BN_bn2hex(xBN)! let yBNstr = BN_bn2hex(yBN)! + let xHex = String(cString: xBNstr) + let xPad = max(64, xHex.count) + let xHexPadded = String(repeatElement("0", count: xPad - xHex.count) + xHex) + let yHex = String(cString: yBNstr) + let yPad = max(64, yHex.count) + let yHexPadded = String(repeatElement("0", count: yPad - yHex.count) + yHex) + CRYPTO_free(xBNstr) CRYPTO_free(yBNstr) BN_free(xBN) BN_free(yBN) EC_POINT_free(pubKeyPoint) - recoveredPubKeyHex = "04" + xHex + yHex + recoveredPubKeyHex = "04" + xHexPadded + yHexPadded } EC_GROUP_free(group) BN_CTX_free(ctx) From 3d204dd44eb6f20f4841ceff1d9d1e6b9f4a8604 Mon Sep 17 00:00:00 2001 From: Steve McCoole Date: Fri, 1 Nov 2019 16:53:29 -0500 Subject: [PATCH 2/2] Added test for public key conversion and extraction that would fail without padding. --- .../EosioSwiftEccRecoverKeyTests.swift | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/EosioSwiftEccTests/EosioSwiftEccRecoverKeyTests.swift b/EosioSwiftEccTests/EosioSwiftEccRecoverKeyTests.swift index e5eefd34..a89e4f2d 100644 --- a/EosioSwiftEccTests/EosioSwiftEccRecoverKeyTests.swift +++ b/EosioSwiftEccTests/EosioSwiftEccRecoverKeyTests.swift @@ -78,6 +78,20 @@ class EosioSwiftEccRecoverKeyTests: XCTestCase { } + func test_eosioK1_private_to_public_needs_padding() { + do { + let privateKey = "5KLuCa3aEXW2kLyj2xbHjn9fsoZmmBNBTbVHhnkzVXtgjipDyQF" + let publicKey = try EccRecoverKey.recoverPublicKey(privateKey: Data(eosioPrivateKey: privateKey), curve: .k1) + guard let eosLegacyPublicKey = publicKey.toCompressedPublicKey?.toEosioLegacyPublicKey else { + XCTFail("Should not fail to convert to EOSIO Legacy Public key.") + return + } + XCTAssert(eosLegacyPublicKey == "EOS7mbBaD7UFLQKVE3oGkAp4ToFaFjaedjJA2WBpTBY8yXgnwK53e") + } catch let error { + XCTFail("Should not error extracting public from private key: \(error.localizedDescription)") + } + } + func test_eosioK1_private_to_public() { do { let privateKey = try Data(eosioPrivateKey: privateKeyK1)