public static string GetNep2FromPrivateKey(byte[] prikey, string passphrase) { var pubkey = Helper.GetPublicKeyFromPrivateKey(prikey); var script_hash = Helper.GetScriptHashFromPublicKey(pubkey); string address = Helper.GetAddressFromScriptHash(script_hash); var b1 = Sha256(Encoding.ASCII.GetBytes(address)); var b2 = Sha256(b1); byte[] addresshash = b2.Take(4).ToArray(); byte[] derivedkey = SCrypt.DeriveKey(Encoding.UTF8.GetBytes(passphrase), addresshash, 16384, 8, 8, 64); byte[] derivedhalf1 = derivedkey.Take(32).ToArray(); byte[] derivedhalf2 = derivedkey.Skip(32).ToArray(); var xorinfo = XOR(prikey, derivedhalf1); byte[] encryptedkey = AES256Encrypt(xorinfo, derivedhalf2); byte[] buffer = new byte[39]; buffer[0] = 0x01; buffer[1] = 0x42; buffer[2] = 0xe0; Buffer.BlockCopy(addresshash, 0, buffer, 3, addresshash.Length); Buffer.BlockCopy(encryptedkey, 0, buffer, 7, encryptedkey.Length); return(Base58CheckEncode(buffer)); }
public static byte[] GetPrivateKeyFromNEP2(string nep2, string passphrase) { if (nep2 == null) { throw new ArgumentNullException(nameof(nep2)); } if (passphrase == null) { throw new ArgumentNullException(nameof(passphrase)); } byte[] data = Base58CheckDecode(nep2); if (data.Length != 39 || data[0] != 0x01 || data[1] != 0x42 || data[2] != 0xe0) { throw new FormatException(); } byte[] addresshash = new byte[4]; Buffer.BlockCopy(data, 3, addresshash, 0, 4); byte[] derivedkey = SCrypt.DeriveKey(Encoding.UTF8.GetBytes(passphrase), addresshash, 16384, 8, 8, 64); byte[] derivedhalf1 = derivedkey.Take(32).ToArray(); byte[] derivedhalf2 = derivedkey.Skip(32).ToArray(); byte[] encryptedkey = new byte[32]; Buffer.BlockCopy(data, 7, encryptedkey, 0, 32); byte[] prikey = XOR(AES256Decrypt(encryptedkey, derivedhalf2), derivedhalf1); //Cryptography.ECC.ECPoint pubkey = Cryptography.ECC.ECCurve.Secp256r1.G * prikey; //UInt160 script_hash = Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash(); //string address = ToAddress(script_hash); //if (!Encoding.ASCII.GetBytes(address).Sha256().Sha256().Take(4).SequenceEqual(addresshash)) // throw new FormatException(); return(prikey); }