From 3890219540048b21d59ef721f84725a30b50e84f Mon Sep 17 00:00:00 2001 From: Andreas Schildbach Date: Tue, 16 May 2017 18:54:32 +0200 Subject: [PATCH] ECKey: Check that constructed private key doesn't exceed 32 bytes. --- core/src/main/java/org/bitcoinj/core/ECKey.java | 10 +++++----- core/src/test/java/org/bitcoinj/core/ECKeyTest.java | 7 +++++++ 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/core/src/main/java/org/bitcoinj/core/ECKey.java b/core/src/main/java/org/bitcoinj/core/ECKey.java index 8d3d15f6..1ebd31aa 100644 --- a/core/src/main/java/org/bitcoinj/core/ECKey.java +++ b/core/src/main/java/org/bitcoinj/core/ECKey.java @@ -185,18 +185,18 @@ public class ECKey implements EncryptableItem { } protected ECKey(@Nullable BigInteger priv, ECPoint pub) { + this(priv, new LazyECPoint(checkNotNull(pub))); + } + + protected ECKey(@Nullable BigInteger priv, LazyECPoint pub) { if (priv != null) { + checkArgument(priv.bitLength() <= 32 * 8, "private key exceeds 32 bytes: {} bits", priv.bitLength()); // Try and catch buggy callers or bad key imports, etc. Zero and one are special because these are often // used as sentinel values and because scripting languages have a habit of auto-casting true and false to // 1 and 0 or vice-versa. Type confusion bugs could therefore result in private keys with these values. checkArgument(!priv.equals(BigInteger.ZERO)); checkArgument(!priv.equals(BigInteger.ONE)); } - this.priv = priv; - this.pub = new LazyECPoint(checkNotNull(pub)); - } - - protected ECKey(@Nullable BigInteger priv, LazyECPoint pub) { this.priv = priv; this.pub = checkNotNull(pub); } diff --git a/core/src/test/java/org/bitcoinj/core/ECKeyTest.java b/core/src/test/java/org/bitcoinj/core/ECKeyTest.java index 2246c15b..bbd463ae 100644 --- a/core/src/test/java/org/bitcoinj/core/ECKeyTest.java +++ b/core/src/test/java/org/bitcoinj/core/ECKeyTest.java @@ -464,4 +464,11 @@ public class ECKeyTest { assertEquals(pubKey1, pubKey2); assertEquals(pubKey1.hashCode(), pubKey2.hashCode()); } + + @Test(expected = IllegalArgumentException.class) + public void fromPrivate_exceedsSize() { + final byte[] bytes = new byte[33]; + bytes[0] = 42; + ECKey.fromPrivate(bytes); + } }