Skip to content

Commit

Permalink
Sanity check in PrivateKey constructor using bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
ipdae committed Aug 15, 2019
1 parent b41da29 commit 993ad31
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ To be released.
the `Transaction<T>` more than once. [[#413]]
- `BlockChain<T>.Swap()` became to omit common block finding when `render` is
`false`. [[#423]]
- `PrivateKey(bytes)` became to valid check. [[#438]]

### Bug fixes

Expand Down Expand Up @@ -144,6 +145,7 @@ To be released.
[#424]: https://github.com/planetarium/libplanet/pull/424
[#426]: https://github.com/planetarium/libplanet/pull/426
[#434]: https://github.com/planetarium/libplanet/pull/434
[#438]: https://github.com/planetarium/libplanet/pull/438
[LiteDB #1268]: https://github.com/mbdavid/LiteDB/issues/1268
[floating-point determinism]: https://wp.me/p1fTCO-kT

Expand Down
12 changes: 12 additions & 0 deletions Libplanet.Tests/Crypto/PrivateKeyTest.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Text;
using Libplanet.Crypto;
using Xunit;
Expand All @@ -20,6 +21,17 @@ public void BytesTest()
Assert.Equal(bs, key.ByteArray);
}

[Fact]
public void BytesSanityCheckTest()
{
var bs = new byte[]
{
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
};
Assert.Throws<InvalidOperationException>(() => new PrivateKey(bs));
}

[Fact]
public void PublicKeyTest()
{
Expand Down
29 changes: 24 additions & 5 deletions Libplanet/Crypto/PrivateKey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,7 @@ public PrivateKey()
/// <seealso cref="ByteArray"/>
public PrivateKey(byte[] privateKey)
: this(
new ECPrivateKeyParameters(
"ECDSA",
new BigInteger(1, privateKey),
GetECParameters()
)
GenerateKeyFromBytes(privateKey)
)
{
}
Expand Down Expand Up @@ -269,6 +265,29 @@ private static ECPrivateKeyParameters GenerateKeyParam()
return gen.GenerateKeyPair().Private as ECPrivateKeyParameters;
}

private static ECPrivateKeyParameters GenerateKeyFromBytes(byte[] privateKey)
{
var param = new ECPrivateKeyParameters(
"ECDSA",
new BigInteger(1, privateKey),
GetECParameters()
);

var key = new PrivateKey(param);
try
{
var publicKey = key.PublicKey;
}
catch (ArgumentException)
{
throw new InvalidOperationException(
"Infinity is not a valid public key for ECDH"
);
}

return param;
}

private ECPoint CalculatePoint(ECPublicKeyParameters pubKeyParams)
{
ECDomainParameters dp = keyParam.Parameters;
Expand Down

0 comments on commit 993ad31

Please sign in to comment.