From 1a4acc18be3a8923aafcd7d3f46a08e2b4c2e6a2 Mon Sep 17 00:00:00 2001 From: Mike Hearn Date: Thu, 26 Jan 2012 18:40:24 +0100 Subject: [PATCH] Pubkeys are 65 bytes, not 32. --- src/com/google/bitcoin/core/ECKey.java | 7 +++++-- src/com/google/bitcoin/core/Utils.java | 14 ++++++++------ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/com/google/bitcoin/core/ECKey.java b/src/com/google/bitcoin/core/ECKey.java index d3290823..b790f9d1 100644 --- a/src/com/google/bitcoin/core/ECKey.java +++ b/src/com/google/bitcoin/core/ECKey.java @@ -129,7 +129,10 @@ public class ECKey implements Serializable { // Derive public from private. this.pub = publicKeyFromPrivate(privKey); } else if (pubKey != null) { - this.pub = Utils.bigIntegerTo32Bytes(pubKey); + // We expect the pubkey to be in regular encoded form, just as a BigInteger. Therefore the first byte is + // a special marker byte. + // TODO: This is probably not a useful API and may be confusing. + this.pub = Utils.bigIntegerToBytes(pubKey, 65); } } @@ -278,7 +281,7 @@ public class ECKey implements Serializable { * Returns a 32 byte array containing the private key. */ public byte[] getPrivKeyBytes() { - return Utils.bigIntegerTo32Bytes(priv); + return Utils.bigIntegerToBytes(priv, 32); } public static ECKey fromPrivKeyBytes(byte[] bytes) { diff --git a/src/com/google/bitcoin/core/Utils.java b/src/com/google/bitcoin/core/Utils.java index d694a349..af8d7495 100644 --- a/src/com/google/bitcoin/core/Utils.java +++ b/src/com/google/bitcoin/core/Utils.java @@ -64,15 +64,17 @@ public class Utils { /** * The regular {@link java.math.BigInteger#toByteArray()} method isn't quite what we often need: it appends a * leading zero to indicate that the number is positive and may need padding. - * @param b + * + * @param b the integer to format into a byte array + * @param numBytes the desired size of the resulting byte array * @return 32 byte long array. */ - public static byte[] bigIntegerTo32Bytes(BigInteger b) { - byte[] bytes = new byte[32]; + public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) { + byte[] bytes = new byte[numBytes]; byte[] biBytes = b.toByteArray(); - int start = (biBytes.length == 33) ? 1 : 0; - int length = Math.min(biBytes.length, 32); - System.arraycopy(biBytes, start, bytes, 32 - length, length); + int start = (biBytes.length == numBytes + 1) ? 1 : 0; + int length = Math.min(biBytes.length, numBytes); + System.arraycopy(biBytes, start, bytes, numBytes - length, length); return bytes; }