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 ef9b0e4
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
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 ef9b0e4

Please sign in to comment.