Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add ecc encrypt&decrypt #2597

Merged
merged 22 commits into from
Sep 15, 2021
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions src/neo/Cryptography/Helper.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.Wallets;
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;
using ECPoint = Neo.Cryptography.ECC.ECPoint;

namespace Neo.Cryptography
{
Expand Down Expand Up @@ -109,6 +112,98 @@ public static byte[] Sha256(this Span<byte> value)
return Sha256((ReadOnlySpan<byte>)value);
}

public static byte[] AES256Encrypt(this byte[] plainData, byte[] key, byte[] nonce, byte[] associatedData = null)
{
var keyLen = key is null ? 0 : key.Length;
var nonceLen = nonce is null ? 0 : nonce.Length;

if (keyLen != 32) throw new ArgumentException();
if (nonceLen != 12) throw new ArgumentException();

var msgLen = plainData is null ? 0 : plainData.Length;
var tagLen = 16;

var cipherBytes = new byte[msgLen];
var tag = new byte[tagLen];
using var cipher = new AesGcm(key);
cipher.Encrypt(nonce, plainData, cipherBytes, tag, associatedData);
var cipherWithTag = new byte[nonceLen + msgLen + tagLen];
Buffer.BlockCopy(nonce, 0, cipherWithTag, 0, nonceLen);
Buffer.BlockCopy(cipherBytes, 0, cipherWithTag, nonceLen, msgLen);
Buffer.BlockCopy(tag, 0, cipherWithTag, nonceLen + msgLen, tagLen);
return cipherWithTag;
}

public static byte[] AES256Decrypt(this byte[] encryptedData, byte[] key, byte[] associatedData = null)
{
if (key.Length != 32) throw new ArgumentException();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check encryptedData length?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The key length,which is checked here. It should be 32 bytes when we use a AES gcm mode

var nonce = encryptedData.Take(12).ToArray();
var cipherBytes = encryptedData.Skip(12).Take(encryptedData.Length - 28).ToArray();
var tag = encryptedData[^16..];
var decryptedData = new byte[cipherBytes.Length];
using var cipher = new AesGcm(key);
cipher.Decrypt(nonce, cipherBytes, tag, decryptedData, associatedData);
return decryptedData;
}

public static byte[] ECEncrypt(byte[] message, ECPoint pubKey)
{
// P=kG,R=rG =>{R,M+rP}
if (pubKey.IsInfinity) throw new ArgumentException();
BigInteger r, rx;
ECPoint R;
var curve = pubKey.Curve;
//r > N
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
do
{
do
{
r = rng.NextBigInteger((int)curve.N.GetBitLength());
} while (r.Sign == 0 || r.CompareTo(curve.N) >= 0);
R = ECPoint.Multiply(curve.G, r);
BigInteger x = R.X.Value;
rx = x.Mod(curve.N);
} while (rx.Sign == 0);
}
byte[] RBar = R.EncodePoint(true);
var EK = ECPoint.Multiply(pubKey, r).X.ToByteArray().Sha256(); // z = r * P = r* k * G
Random random = new Random();
byte[] Nonce = new byte[12];
random.NextBytes(Nonce);
return RBar.Concat(message.AES256Encrypt(EK, Nonce)).ToArray();
}

public static byte[] ECDecrypt(byte[] cypher, KeyPair key)
{
shargon marked this conversation as resolved.
Show resolved Hide resolved
// {R,M+rP}={rG, M+rP}=> M + rP - kR = M + r(kG) - k(rG) = M
if (cypher is null || cypher.Length < 33) throw new ArgumentException();
if (cypher[0] != 0x02 && cypher[0] != 0x03) throw new ArgumentException();
if (key.PublicKey.IsInfinity) throw new ArgumentException();
var RBar = cypher.Take(33).ToArray();
var EM = cypher.Skip(33).ToArray();
var R = ECPoint.FromBytes(RBar, key.PublicKey.Curve);
var k = new BigInteger(key.PrivateKey.Reverse().Concat(new byte[1]).ToArray());
var EK = ECPoint.Multiply(R, k).X.ToByteArray().Sha256(); // z = k * R = k * r * G
return EM.AES256Decrypt(EK);
}

internal static BigInteger NextBigInteger(this RandomNumberGenerator rng, int sizeInBits)
{
if (sizeInBits < 0)
throw new ArgumentException("sizeInBits must be non-negative");
if (sizeInBits == 0)
return 0;
byte[] b = new byte[sizeInBits / 8 + 1];
rng.GetBytes(b);
if (sizeInBits % 8 == 0)
b[b.Length - 1] = 0;
else
b[b.Length - 1] &= (byte)((1 << sizeInBits % 8) - 1);
return new BigInteger(b);
}

internal static bool Test(this BloomFilter filter, Transaction tx)
{
if (filter.Check(tx.Hash.ToArray())) return true;
Expand Down
35 changes: 35 additions & 0 deletions tests/neo.UnitTests/Cryptography/UT_Cryptography_Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.SmartContract;
using Neo.Wallets;
using Neo.Wallets.NEP6;
using System;
using System.Linq;
using System.Security;
using System.Text;

Expand Down Expand Up @@ -48,6 +51,38 @@ public void TestRIPEMD160()
resultStr.Should().Be("98c615784ccb5fe5936fbc0cbe9dfdb408d92f0f");
}

[TestMethod]
public void TestAESEncryptAndDecrypt()
{
NEP6Wallet wallet = new NEP6Wallet("", ProtocolSettings.Default);
wallet.Unlock("1");
wallet.CreateAccount();
WalletAccount account = wallet.GetAccounts().ToArray()[0];
KeyPair key = account.GetKey();
Random random = new Random();
byte[] nonce = new byte[12];
random.NextBytes(nonce);
var cypher = Neo.Cryptography.Helper.AES256Encrypt(Encoding.UTF8.GetBytes("hello world"), key.PrivateKey, nonce);
var m = Neo.Cryptography.Helper.AES256Decrypt(cypher, key.PrivateKey);
var message2 = Encoding.UTF8.GetString(m);
Assert.AreEqual("hello world", message2);
}

[TestMethod]
public void TestECEncryptAndDecrypt()
{
NEP6Wallet wallet = new NEP6Wallet("", ProtocolSettings.Default);
wallet.Unlock("1");
wallet.CreateAccount();
WalletAccount account = wallet.GetAccounts().ToArray()[0];
KeyPair key = account.GetKey();
var message = Encoding.ASCII.GetBytes("hello world");
var cypher = Neo.Cryptography.Helper.ECEncrypt(message, key.PublicKey);
var m = Neo.Cryptography.Helper.ECDecrypt(cypher, key);
var message2 = Encoding.ASCII.GetString(m);
Assert.AreEqual("hello world", message2);
}

[TestMethod]
public void TestTest()
{
Expand Down