예제 #1
0
        public static byte[] GetPrivateKeyFromNEP2(string nep2, string passphrase, int N = 16384, int r = 8, int p = 8)
        {
            if (nep2 == null)
            {
                throw new ArgumentNullException("nep2");
            }
            if (passphrase == null)
            {
                throw new ArgumentNullException("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, N, r, p, 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);
            var    pubkey  = GetPublicKeyFromPrivateKey(prikey);
            var    address = GetAddressFromPublicKey(pubkey);
            var    hash    = Sha256(Encoding.ASCII.GetBytes(address));

            hash = Sha256(hash);
            for (var i = 0; i < 4; i++)
            {
                if (hash[i] != addresshash[i])
                {
                    throw new Exception("check error.");
                }
            }
            //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);
        }