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 21 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
59 changes: 59 additions & 0 deletions src/neo/Cryptography/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

using Neo.IO;
using Neo.Network.P2P.Payloads;
using Neo.Wallets;
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
Expand All @@ -18,6 +19,7 @@
using System.Security;
using System.Security.Cryptography;
using System.Text;
using ECPoint = Neo.Cryptography.ECC.ECPoint;

namespace Neo.Cryptography
{
Expand Down Expand Up @@ -119,6 +121,63 @@ 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[] ECDHDeriveKey(KeyPair local, ECPoint remote)
{
ReadOnlySpan<byte> pubkey_local = local.PublicKey.EncodePoint(false);
ReadOnlySpan<byte> pubkey_remote = remote.EncodePoint(false);
using ECDiffieHellman ecdh1 = ECDiffieHellman.Create(new ECParameters
{
Curve = ECCurve.NamedCurves.nistP256,
D = local.PrivateKey,
Q = new System.Security.Cryptography.ECPoint
{
X = pubkey_local[1..][..32].ToArray(),
Y = pubkey_local[1..][32..].ToArray()
}
});
using ECDiffieHellman ecdh2 = ECDiffieHellman.Create(new ECParameters
{
Curve = ECCurve.NamedCurves.nistP256,
Q = new System.Security.Cryptography.ECPoint
{
X = pubkey_remote[1..][..32].ToArray(),
Y = pubkey_remote[1..][32..].ToArray()
}
});
return ecdh1.DeriveKeyMaterial(ecdh2.PublicKey).Sha256();//z = r * P = r* k * G
}

internal static bool Test(this BloomFilter filter, Transaction tx)
{
if (filter.Check(tx.Hash.ToArray())) return true;
Expand Down
45 changes: 45 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,48 @@ 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 TestEcdhEncryptAndDecrypt()
{
NEP6Wallet wallet = new NEP6Wallet("", ProtocolSettings.Default);
wallet.Unlock("1");
wallet.CreateAccount();
wallet.CreateAccount();
WalletAccount account1 = wallet.GetAccounts().ToArray()[0];
KeyPair key1 = account1.GetKey();
WalletAccount account2 = wallet.GetAccounts().ToArray()[1];
KeyPair key2 = account2.GetKey();
Console.WriteLine($"Account:{1},privatekey:{key1.PrivateKey.ToHexString()},publicKey:{key1.PublicKey.ToArray().ToHexString()}");
Console.WriteLine($"Account:{2},privatekey:{key2.PrivateKey.ToHexString()},publicKey:{key2.PublicKey.ToArray().ToHexString()}");
var secret1 = Neo.Cryptography.Helper.ECDHDeriveKey(key1, key2.PublicKey);
var secret2 = Neo.Cryptography.Helper.ECDHDeriveKey(key2, key1.PublicKey);
Assert.AreEqual(secret1.ToHexString(), secret2.ToHexString());
var message = Encoding.ASCII.GetBytes("hello world");
Random random = new Random();
byte[] nonce = new byte[12];
random.NextBytes(nonce);
var cypher = message.AES256Encrypt(secret1, nonce);
cypher.AES256Decrypt(secret2);
Assert.AreEqual("hello world", Encoding.ASCII.GetString(cypher.AES256Decrypt(secret2)));
}

[TestMethod]
public void TestTest()
{
Expand Down