Encode() 공개 정적인 메소드

public static Encode ( long intData ) : string
intData long
리턴 string
예제 #1
0
        public static string HashAlias(Alias alias)
        {
            var aliasClone = alias.Clone();

            aliasClone.Realm = "";
            return(Base58.Encode(Sha256Hash(Encoding.UTF8.GetBytes(ToJson(aliasClone)))));
        }
예제 #2
0
        public override void Deserialize(byte[] bytes, ref int index)
        {
            var addressBytes = new byte[28];

            Array.Copy(bytes, index, addressBytes, 0, addressBytes.Length);
            index += addressBytes.Length;

            var serialNoLenBytes = new byte[4];

            Array.Copy(bytes, index, serialNoLenBytes, 0, serialNoLenBytes.Length);
            SerialNoLen = BitConverter.ToInt32(serialNoLenBytes, 0);
            index      += serialNoLenBytes.Length;

            var serialNoBytes = new byte[SerialNoLen];

            Array.Copy(bytes, index, serialNoBytes, 0, serialNoBytes.Length);
            index += serialNoBytes.Length;

            var nameBytes = new byte[bytes.Length - index - 1];

            Array.Copy(bytes, index, nameBytes, 0, nameBytes.Length);
            index += nameBytes.Length;

            WalletAddress = Base58.Encode(addressBytes);
            SerialNo      = Encoding.UTF8.GetString(serialNoBytes);
            Name          = Encoding.UTF8.GetString(nameBytes);
        }
예제 #3
0
        public static string getSinFromPem(string pem)
        {
            string[] keyInfo   = keysFromPem(pem);
            string   hexPubKey = keyInfo [1];

            // Step 1 and 2
            // Hex to Bytes, SHA-256 and RIPEMD-160
            byte[] bytesPubKey1 = hexToBytes(hexPubKey);
            byte[] bytesPubKey2 = Utils.Sha256Hash160(bytesPubKey1);
            String shaAndRipe   = Utils.BytesToHexString(bytesPubKey2);

            // Step 3
            // Add 0F02 to Hex of Step 2
            String step3 = "0F02" + shaAndRipe;

            // Step 4
            // Hex to Bytes, Double SHA-256
            byte[] bytesPubKey3 = hexToBytes(step3);
            byte[] bytesPubKey4 = Utils.DoubleDigest(bytesPubKey3);             //Utils.doubleDigest(bytesPubKey3);

            // Step 5
            // Substring of first 4 bytes (first 8 characters)
            String step4Hex = Utils.BytesToHexString(bytesPubKey4);
            String step5    = step4Hex.Substring(0, 8);

            // Step 6
            // Combine step 3 and step 5
            String step6 = step3 + step5;

            // Convert to base 58
            byte[] step6bytes = hexToBytes(step6);
            String sin        = Base58.Encode(step6bytes);

            return(sin);
        }
예제 #4
0
        public static string KeyToString(byte[] key, string keyType, string prefix = null)
        {
            byte[] digest = null;

            if (keyType == "sha256x2")
            {
                digest = Sha256Manager.GetHash(Sha256Manager.GetHash(SerializationHelper.Combine(new List <byte[]>()
                {
                    new byte[] { 128 },
                    key
                })));
            }
            else if (!string.IsNullOrWhiteSpace(keyType))
            {
                digest = Ripemd160Manager.GetHash(SerializationHelper.Combine(new List <byte[]>()
                {
                    key,
                    Encoding.UTF8.GetBytes(keyType)
                }));
            }
            else
            {
                digest = Ripemd160Manager.GetHash(key);
            }

            return(prefix + Base58.Encode(SerializationHelper.Combine(new List <byte[]>()
            {
                key,
                digest.Take(4).ToArray()
            })));
        }
예제 #5
0
        public void Base58EncodeTest(string key, string value)
        {
            var b   = Hex.HexToBytes(value);
            var rez = Base58.Encode(b);

            Assert.IsTrue(key.Equals(rez));
        }
예제 #6
0
        public static string SignHash(string privateKeyString, byte[] hash)
        {
            try
            {
                ECPrivateKeyParameters privateKeyParameters = EosKeyHelper.GetECPrivateKeyParametersFromString(privateKeyString);
                ISigner signer = SignerUtilities.GetSigner("NONEwithECDSA");
                signer.Init(true, privateKeyParameters);
                signer.BlockUpdate(hash, 0, hash.Length);
                byte[] sigBytes = signer.GenerateSignature();

                var check = new List <byte[]>()
                {
                    sigBytes, KEY_TYPE_BYTES
                };
                var checksum        = Ripemd160Manager.GetHash(SerializationHelper.Combine(check)).Take(CHECKSUM_LENGHT).ToArray();
                var signAndChecksum = new List <byte[]>()
                {
                    sigBytes, checksum
                };
                var finalSig = SIG_PREFIX + Base58.Encode(SerializationHelper.Combine(signAndChecksum));

                return(finalSig);
            }
            catch (Exception exc)
            {
                Console.WriteLine("Signing Failed: " + exc.ToString());
                return(null);
            }
        }
예제 #7
0
        public override bool IsValid(IList <Block> chain)
        {
            if (!base.IsValid(chain))
            {
                return(false);
            }

            var members = chain.SelectMany(b => b.Members.Where(m => m.Address.SequenceEqual(PublicKey))).ToArray();

            if (members.Length == 0)
            {
                // TODO: validar que el miembro sea de la organización ¿y que esté en el padrón o sea miembro desde antes del inicio de la votación?
                Messages.Add($"La persona [{Base58.Encode(PublicKey)}] no es miembro de esta comunidad");
                return(false);
            }

            var member = members[0];

            // TODO: ¿que pasa si los dos votos están entrando en el mismo bloque?
            foreach (var block in chain)
            {
                var previous = block.Votes.Any(v => v.QuestionId.Equals(QuestionId) && v.PublicKey.SequenceEqual(PublicKey));
                if (previous)
                {
                    Messages.Add($"La persona [{Base58.Encode(PublicKey)}] ya votó");
                    return(false);
                }
            }

            return(true);
        }
예제 #8
0
        public async Task SerializeAndSignMultiActionTx()
        {
            var keyStore = new InMemoryKeyStore();
            var keyPair  = KeyPair.FromString("ed25519:2wyRcSwSuHtRVmkMCGjPwnzZmQLeXLzLLyED1NDMt4BjnKgQL6tF85yBx6Jr26D2dUNeC716RBoTxntVHsegogYw");
            await keyStore.SetKeyAsync("test", "test.near", keyPair);

            var publicKey = keyPair.GetPublicKey();

            var actions = new[]
            {
                Action.CreateAccount(),
                Action.DeployContract(new byte[] { 1, 2, 3 }),
                Action.FunctionCall("qqq", new byte[] { 1, 2, 3 }, 1000, 1000000),
                Action.Transfer(123),
                Action.Stake(1000000, publicKey),
                Action.AddKey(publicKey, AccessKey.FunctionCallAccessKey("zzz", new [] { "www" }, null)),
                Action.DeleteKey(publicKey),
                Action.DeleteAccount("123")
            };

            var blockHash = new ByteArray32()
            {
                Buffer = Base58.Decode("244ZQ9cgj3CQ6bWBdytfrJMuMQ1jdXLFGnr4HhvtCTnM")
            };
            var signedTransaction = await SignedTransaction.SignTransactionAsync("123", 1, actions, blockHash, new InMemorySigner(keyStore), "test.near", "test");

            const string expected = "Fo3MJ9XzKjnKuDuQKhDAC6fra5H2UWawRejFSEpPNk3Y";
            var          actual   = Base58.Encode(signedTransaction.Item1);

            Assert.AreEqual(expected, actual);
        }
예제 #9
0
        public void Community()
        {
            var community1 = new Community
            {
                Id       = new Guid("4814e8f885f74230b04d2daa4e2d88a4"),
                Name     = "Crypto Vote",
                CreateAt = DateTimeOffset.FromUnixTimeMilliseconds(1551715934000)
            };

            var keys = service.GeneratePair();

            var signer = new Signer(service);

            community1.Signature = signer.Sign(community1.GetData(), keys);
            var signatureBase58 = Base58.Encode(community1.Signature);

            community1.PublicKey = new byte[keys.PublicKey.Length];
            Buffer.BlockCopy(keys.PublicKey, 0, community1.PublicKey, 0, keys.PublicKey.Length);

            var json = JsonSerializer.Serialize(community1, JsonDefaultSettings.Options);

            Console.WriteLine(json);

            var community2      = JsonSerializer.Deserialize <Community>(json, JsonDefaultSettings.Options);
            var publicKeyBase58 = Base58.Encode(community2.PublicKey);

            var verifier = new SignatureVerify(service);

            Assert.IsTrue(verifier.Verify(community2));
            Assert.IsTrue(verifier.Verify(community2.GetData(), Base58.Decode(publicKeyBase58), community2.Signature));
            Assert.IsTrue(verifier.Verify(community2.GetData(), Base58.Decode(publicKeyBase58), Base58.Decode(signatureBase58)));
        }
예제 #10
0
        public void Member()
        {
            var member1 = new Member
            {
                Id          = new Guid("bedcbb2a476547d5b395524ffb6d157b"),
                CommunityId = new Guid("4814e8f885f74230b04d2daa4e2d88a4"),
                Name        = "Nelo Pauselli"
            };

            var keys = service.GeneratePair();

            var signer = new Signer(service);

            member1.Signature = signer.Sign(member1.GetData(), keys);
            var signatureBase58 = Base58.Encode(member1.Signature);

            member1.PublicKey = new byte[keys.PublicKey.Length];
            Buffer.BlockCopy(keys.PublicKey, 0, member1.PublicKey, 0, keys.PublicKey.Length);

            var json = JsonSerializer.Serialize(member1, JsonDefaultSettings.Options);

            Console.WriteLine(json);

            var member2         = JsonSerializer.Deserialize <Member>(json, JsonDefaultSettings.Options);
            var publicKeyBase58 = Base58.Encode(member2.PublicKey);

            var verifier = new SignatureVerify(service);

            Assert.IsTrue(verifier.Verify(member2));
            Assert.IsTrue(verifier.Verify(member2.GetData(), Base58.Decode(publicKeyBase58), member2.Signature));
            Assert.IsTrue(verifier.Verify(member2.GetData(), Base58.Decode(publicKeyBase58), Base58.Decode(signatureBase58)));
        }
예제 #11
0
        public void Main4Test()
        {
            Wallet.WalletClient wallet = GetMainNetWalletClient;

            var keyTriple = new KeyTriple("B7E85CA5910922C49DCCB92EE48DFEC13A60674845CB7152C86B88F31DA6DC67");

            byte[]       hashTransaction1 = StringHelper.HexStringToByteArray("a7e974c6e69fb7741bf5e08de8a2d8f6617826c59422b440de22e0612b03c393");
            BytesMessage bytesMessage1    = new BytesMessage();

            bytesMessage1.Value = ByteString.CopyFrom(hashTransaction1);
            Transaction transactionLoad1 = wallet.GetTransactionByIdAsync(bytesMessage1).GetAwaiter().GetResult();

            Transaction.Types.Contract contract         = transactionLoad1.RawData.Contract[0];
            TransferContract           transferContract = TransferContract.Parser.ParseFrom(contract.Parameter.Value.ToByteArray());

            byte[] publicKeyOwner = transferContract.OwnerAddress.ToByteArray();
            string encode         = Base58.Encode(publicKeyOwner);

            byte[] transactionRaw = transactionLoad1.RawData.ToByteArray();
            byte[] hash           = Sha256.Hash(transactionRaw);
            string signBase64     = transactionLoad1.Signature[0].ToBase64();

            byte[] byteArray = transactionLoad1.Signature[0].ToByteArray();
            bool   isSignatureValidFromBytes = new ECSigner().IsSignatureValidFromBytes(hash, byteArray, publicKeyOwner);
        }
예제 #12
0
        public override string ToString()
        {
            var checksum = Ripemd160Manager.GetHash(this.Data).Take(4).ToArray();
            var public_key_with_checksum = this.Data.Concat(checksum).ToArray();

            return(PREFIX + Base58.Encode(public_key_with_checksum));
        }
예제 #13
0
        public void Base58Test()
        {
            string userCode = "3999999";
            string result   = Base58.Encode(Encoding.UTF8.GetBytes(userCode));

            Debug.WriteLine(result);
        }
        public void getTransactionFromTestNetTesst()
        {
            Wallet.WalletClient wallet = GetMainNetWalletClient;

            //	wallet.tra

            byte[]       hashTransaction = StringHelper.HexStringToByteArray("d2e635f7c2d85cbcd343721047447b122a3c19e86f30651d8ec6ee76f744d065");
            BytesMessage bytesMessage    = new BytesMessage();

            bytesMessage.Value = ByteString.CopyFrom(hashTransaction);
            //				Transaction transactionLoad = wallet.GetTransactionByIdAsync(bytesMessage).GetAwaiter().GetResult();
            //				Transaction transactionLoad = wallet.GetTransactionByIdAsync(bytesMessage).GetAwaiter().GetResult();
            NodeList nodeList = wallet.ListNodes(GetEmptyMessage);
            Block    result   = wallet.GetNowBlockAsync(GetEmptyMessage).GetAwaiter().GetResult();
            //TK4BAeF72P3gop24RsoqPJynWgBBDv9fXX
            var keyTriple = new KeyTriple("B7E85CA5910922C49DCCB92EE48DFEC13A60674845CB7152C86B88F31DA6DC67");

            byte[]  addressWallet = keyTriple.GetAddressWallet(TypeNet.Main);
            string  encode        = Base58.Encode(addressWallet);
            Account account       = new Account();

            account.Address = ByteString.CopyFrom(addressWallet);
            Account account1 = wallet.GetAccountAsync(account).GetAwaiter().GetResult();

            //	new WalletExtension



            byte[]       hashTransaction1 = StringHelper.HexStringToByteArray("a7e974c6e69fb7741bf5e08de8a2d8f6617826c59422b440de22e0612b03c393");
            BytesMessage bytesMessage1    = new BytesMessage();

            bytesMessage1.Value = ByteString.CopyFrom(hashTransaction1);
            Transaction      transactionLoad1 = wallet.GetTransactionByIdAsync(bytesMessage1).GetAwaiter().GetResult();
            TransferContract transferContract = TransferContract.Parser.ParseFrom(transactionLoad1.RawData.Contract[0].Parameter.Value.ToByteArray());
        }
예제 #15
0
        private void btnBase58Encode_Click(object sender, EventArgs e)
        {
            var    buff   = GetBase58PlainEncoding().GetBytes(txt_base58_plain.Text.Trim());
            string cipher = Base58.Encode(buff);

            txt_base58_cipher.Text = cipher;
        }
예제 #16
0
        public static Wallet Generate(bool compressed)
        {
            byte[] randomKey = Secp256K1Manager.GenerateRandomKey();
            byte[] array1    = ((IEnumerable <byte>) new byte[1]).Concat <byte>((IEnumerable <byte>)Ripemd160Manager.GetHash(Sha256Manager.GetHash(Secp256K1Manager.GetPublicKey(randomKey, compressed)))).ToArray <byte>();
            string pub       = Base58.Encode(((IEnumerable <byte>)array1).Concat <byte>(((IEnumerable <byte>)Sha256Manager.GetHash(Sha256Manager.GetHash(array1))).Take <byte>(4)).ToArray <byte>());

            byte[] array2;
            if (!compressed)
            {
                array2 = ((IEnumerable <byte>) new byte[1]
                {
                    (byte)128
                }).Concat <byte>((IEnumerable <byte>)randomKey).ToArray <byte>();
            }
            else
            {
                array2 = ((IEnumerable <byte>) new byte[1]
                {
                    (byte)128
                }).Concat <byte>((IEnumerable <byte>)randomKey).Concat <byte>((IEnumerable <byte>) new byte[1]
                {
                    (byte)1
                }).ToArray <byte>();
            }
            return(new Wallet(Base58.Encode(((IEnumerable <byte>)array2).Concat <byte>(((IEnumerable <byte>)Sha256Manager.GetHash(Sha256Manager.GetHash(array2))).Take <byte>(4)).ToArray <byte>()), pub));
        }
예제 #17
0
        public static Address GetLegacyAddress(string _private = "", bool _mainnet = true)
        {
            _private = _private == "" ? RandomPlus.RandomHex(64) : _private;

            BigInteger _privateInt = BigInteger.Parse("0" + _private, NumberStyles.HexNumber);

            byte[] _public = Secp256k1.PrivateKeyToPublicKey(_privateInt, false);

            RIPEMD160Managed _ripemd = new RIPEMD160Managed();

            byte[] _ripemdHashed = _ripemd.ComputeHash(SHA.EncodeSHA256(_public));
            byte[] _addedVersion = new byte[_ripemdHashed.Length + 1];
            _addedVersion[0] = (byte)(_mainnet ? 0x00 : 0x6f);
            Array.Copy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length);

            byte[] _shaHashed = SHA.EncodeSHA256(SHA.EncodeSHA256(_addedVersion));
            Array.Resize(ref _shaHashed, 4);

            byte[] _result = new byte[_addedVersion.Length + _shaHashed.Length];
            Array.Copy(_addedVersion, 0, _result, 0, _addedVersion.Length);
            Array.Copy(_shaHashed, 0, _result, _addedVersion.Length, _shaHashed.Length);

            string _key1 = string.Join("", (_mainnet ? "80" : "ef"), _private);
            string _key2 = HexPlus.ByteArrayToHexString(SHA.EncodeSHA256(SHA.EncodeSHA256(HexPlus.HexStringToByteArray(_key1))).Take(4).ToArray());

            Address _address = new Address
            {
                Text    = Base58.Encode(_result),
                Public  = HexPlus.ByteArrayToHexString(_public),
                Private = Base58.Encode(_key1 + _key2)
            };

            return(_address);
        }
예제 #18
0
        public Task <IEnumerable <string> > Sign(string chainId, IEnumerable <string> requiredKeys, byte[] signBytes,
                                                 IEnumerable <string> abiNames = null)
        {
            var data = new List <byte[]>()
            {
                Hex.HexToBytes(chainId),
                signBytes,
                new byte[32]
            };

            var hash = Sha256Manager.GetHash(SerializationHelper.Combine(data));

            return(Task.FromResult(requiredKeys.Select(key =>
            {
                var sign = Secp256K1Manager.SignCompressedCompact(hash, Keys[key]);
                var check = new List <byte[]>()
                {
                    sign, KeyTypeBytes
                };
                var checksum = Ripemd160Manager.GetHash(SerializationHelper.Combine(check)).Take(4).ToArray();
                var signAndChecksum = new List <byte[]>()
                {
                    sign, checksum
                };

                return "SIG_K1_" + Base58.Encode(SerializationHelper.Combine(signAndChecksum));
            })));
        }
예제 #19
0
        public static string CreateAccountAddressByPublicKeyHash(byte[] pubkHash)
        {
            //byte[] prefix = new byte[] { 0x00 };   //1
            //byte[] prefix = new byte[] { 0x40, 0xE7, 0xE9, 0x26 };   //fiiit
            byte[] fullPrefix;

            if (GlobalParameters.IsTestnet)
            {
                fullPrefix = BitConverter.GetBytes(testnetPrefix);
            }
            else
            {
                fullPrefix = BitConverter.GetBytes(mainnetPrefix);
            }

            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(fullPrefix);
            }

            var payload = new List <byte>();

            payload.AddRange(fullPrefix);
            payload.AddRange(pubkHash);

            var checksum = HashHelper.DoubleHash(payload.ToArray()).Take(4);

            payload.AddRange(checksum);

            return(Base58.Encode(payload.ToArray()));
        }
예제 #20
0
        public static string ToAddress(UInt160 hash, bool p2sh)
        {
            byte version = p2sh ? P2SHVersion : CoinVersion;

            byte[] data = new byte[] { version }.Concat(hash.ToArray()).ToArray();
            return(Base58.Encode(data.Concat(data.Sha256().Sha256().Take(4)).ToArray()));
        }
예제 #21
0
        public static String deriveSIN(EcKey ecKey)
        {
            // Get sha256 hash and then the RIPEMD-160 hash of the public key (this call gets the result in one step).
            byte[] pubKeyHash = ecKey.PubKeyHash;

            // Convert binary pubKeyHash, SINtype and version to Hex
            String version       = "0F";
            String SINtype       = "02";
            String pubKeyHashHex = bytesToHex(pubKeyHash);

            // Concatenate all three elements
            String preSIN = version + SINtype + pubKeyHashHex;

            // Convert the hex string back to binary and double sha256 hash it leaving in binary both times
            byte[] preSINbyte = hexToBytes(preSIN);
            byte[] hash2Bytes = Utils.DoubleDigest(preSINbyte);

            // Convert back to hex and take first four bytes
            String hashString  = bytesToHex(hash2Bytes);
            String first4Bytes = hashString.Substring(0, 8);

            // Append first four bytes to fully appended SIN string
            String unencoded = preSIN + first4Bytes;

            byte[] unencodedBytes = new BigInteger(unencoded, 16).ToByteArray();
            String encoded        = Base58.Encode(unencodedBytes);

            return(encoded);
        }
예제 #22
0
        public void Vote()
        {
            var vote1 = new Vote
            {
                QuestionId = new Guid("bd746b3b276e454a8B1e041cf53a8747"),
                ChoiceId   = Guid.NewGuid(),
                Time       = DateTimeOffset.Now.ToUnixTimeMilliseconds()
            };

            var keys = service.GeneratePair();

            var signer = new Signer(service);

            vote1.Signature = signer.Sign(vote1.GetData(), keys);
            var signatureBase58 = Base58.Encode(vote1.Signature);

            vote1.PublicKey = new byte[keys.PublicKey.Length];
            Buffer.BlockCopy(keys.PublicKey, 0, vote1.PublicKey, 0, keys.PublicKey.Length);

            var json = JsonSerializer.Serialize(vote1, JsonDefaultSettings.Options);

            Console.WriteLine(json);

            var vote            = JsonSerializer.Deserialize <Vote>(json, JsonDefaultSettings.Options);
            var publicKeyBase58 = Base58.Encode(vote.PublicKey);

            var verifier = new SignatureVerify(service);
        }
예제 #23
0
        /// <summary>
        /// compress  private key
        /// https://sourceforge.net/p/bitcoin/mailman/bitcoin-development/thread/CAPg+sBhDFCjAn1tRRQhaudtqwsh4vcVbxzm+AA2OuFxN71fwUA@mail.gmail.com/
        /// </summary>
        /// <param name="_uncompressKey"></param>
        /// <returns></returns>
        public static string CompressPrivateKey(string _uncompressKey, bool _mainnet)
        {
            string _orgKey = string.Join("", (!_mainnet ? "ef" : "80"), _uncompressKey);
            string _addmin = HexPlus.ByteArrayToHexString(Lion.Encrypt.SHA.EncodeSHA256(Lion.Encrypt.SHA.EncodeSHA256(Lion.HexPlus.HexStringToByteArray(_orgKey))).Take(4).ToArray());

            return(Base58.Encode(_orgKey + _addmin));
        }
예제 #24
0
        public static Address GenerateAddress(out string _uncompressKey, string _existsPrivateKey = "", bool _mainNet = true)
        {
            string _netVersion = _mainNet ? "00" : "6f";
            string _privateKey = string.IsNullOrWhiteSpace(_existsPrivateKey) ? Lion.RandomPlus.RandomHex() : _existsPrivateKey;

            _uncompressKey = _privateKey;
            BigInteger    _bigPrivateKey = BigInteger.Parse("0" + _privateKey, System.Globalization.NumberStyles.HexNumber);
            var           _publicKey     = Secp256k1.PrivateKeyToPublicKey(_bigPrivateKey);
            SHA256Managed sha256         = new SHA256Managed();
            var           _ripemd        = new RIPEMD160Managed();
            var           _ripemdHashed  = _ripemd.ComputeHash(sha256.ComputeHash(_publicKey));
            var           _addedVersion  = new byte[_ripemdHashed.Length + 1];

            if (!_mainNet)
            {
                _addedVersion[0] = 0x6f;
            }
            Buffer.BlockCopy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length);
            var _doubleSha = sha256.ComputeHash(sha256.ComputeHash(_addedVersion));

            Array.Resize(ref _doubleSha, 4);

            byte[] _result = new byte[_addedVersion.Length + _doubleSha.Length];
            Buffer.BlockCopy(_addedVersion, 0, _result, 0, _addedVersion.Length);
            Buffer.BlockCopy(_doubleSha, 0, _result, _addedVersion.Length, _doubleSha.Length);

            Address _address = new Address();

            _address.Text       = Base58.Encode(_result);
            _address.PublicKey  = Lion.HexPlus.ByteArrayToHexString(_publicKey);
            _address.PrivateKey = CompressPrivateKey(_privateKey, _mainNet);
            _address.Text       = (_mainNet ? (_address.Text.StartsWith("1") ? "" : "1") : "") + _address.Text;
            return(_address);
        }
예제 #25
0
        public static Address GenerateAddress(string _privateKey = "", bool _mainNet = true)
        {
            _privateKey = _privateKey == "" ? RandomPlus.RandomHex(64) : _privateKey;

            BigInteger _privateInt = BigInteger.Parse("0" + _privateKey, System.Globalization.NumberStyles.HexNumber);

            byte[] _publicKey = Secp256k1.PrivateKeyToPublicKey(_privateInt);

            SHA256Managed    _sha256 = new SHA256Managed();
            RIPEMD160Managed _ripemd = new RIPEMD160Managed();

            byte[] _ripemdHashed = _ripemd.ComputeHash(_sha256.ComputeHash(_publicKey));
            byte[] _addedVersion = new byte[_ripemdHashed.Length + 1];
            _addedVersion[0] = (byte)(_mainNet ? 0x00 : 0x6f);
            Array.Copy(_ripemdHashed, 0, _addedVersion, 1, _ripemdHashed.Length);

            byte[] _shaHashed = _sha256.ComputeHash(_sha256.ComputeHash(_addedVersion));
            Array.Resize(ref _shaHashed, 4);

            byte[] _result = new byte[_addedVersion.Length + _shaHashed.Length];
            Array.Copy(_addedVersion, 0, _result, 0, _addedVersion.Length);
            Array.Copy(_shaHashed, 0, _result, _addedVersion.Length, _shaHashed.Length);

            string _key1 = string.Join("", (_mainNet ? "80" : "ef"), _privateKey);
            string _key2 = HexPlus.ByteArrayToHexString(SHA.EncodeSHA256(SHA.EncodeSHA256(HexPlus.HexStringToByteArray(_key1))).Take(4).ToArray());

            Address _address = new Address();

            _address.Text       = Base58.Encode(_result);
            _address.PublicKey  = HexPlus.ByteArrayToHexString(_publicKey);
            _address.PrivateKey = Base58.Encode(_key1 + _key2);
            _address.Text       = (_mainNet ? (_address.Text.StartsWith("1") ? "" : "1") : "") + _address.Text;
            return(_address);
        }
예제 #26
0
        // Converts a set of public keys to a readable address
        public static string AddressFromKeys(string PublicSpendKey, string PublicViewKey, ulong Prefix)
        {
            // First we create a byte buffer
            byte[] Buffer = new byte[0];

            // Pack address prefix into buffer
            Buffer = Buffer.AppendVarInt(Prefix);

            // Add keys to buffer
            Buffer = Buffer.AppendBytes(HexStringToByteArray(PublicSpendKey));
            Buffer = Buffer.AppendBytes(HexStringToByteArray(PublicViewKey));

            // Append buffer checksum to buffer
            Buffer = Buffer.AppendBytes(Keccak.KeccakHash(Buffer, 4));

            /* Now we have to encode our address in base58 - but we do it in
             * a bit of an odd way, in blocks. We take 8 bytes at a time,
             * and convert it to base58. Then, if the block converts to less
             * than 11 base58 chars, we pad it with ones (1 is 0 in Base58)
             *
             * The final block however is not padded to 11 chars, rather it
             * is padded to the length of the hex string modulo 8.
             *
             * This ensures addresses are always the same length. */

            // Split buffer into chunks of 8
            var Chunks = Buffer.ChunkBy(8);

            // Create an output string for our address
            string Output = "";

            // The size of the remainder after chunking into groups of 8
            int LastChunkSize = Buffer.Length % 8;

            // Loop through all chunks
            for (int i = 0; i < Chunks.Count; i++)
            {
                // Encode the chunk into a base58 string
                string AddrChunk = Base58.Encode(Chunks[i]);

                // Pad to 11 chars with ones, i.e. 0 in base58 - we pad at the beginning
                if (i < Chunks.Count - 1)
                {
                    AddrChunk = AddrChunk.PadLeft(11, LeadingChar);
                }

                // Last iteration, we do different padding
                else
                {
                    AddrChunk = AddrChunk.PadLeft(LastChunkSize, LeadingChar);
                }

                // Add address chunk to output string
                Output += AddrChunk;
            }

            // Return resulting address string
            return(Output);
        }
예제 #27
0
        private static string GetKey(byte[] content)
        {
            RIPEMD160Managed ripemd160Managed = new RIPEMD160Managed();
            var part1 = ripemd160Managed.ComputeHash(content);
            var part2 = SHA1.Create().ComputeHash(content);

            return(Base58.Encode(part1.Concat(part2).ToArray()));
        }
예제 #28
0
 public string GetSignature(byte[] bytes)
 {
     if (privateKey == null)
     {
         throw new KeyError("Cannot sign the context. No private key in account.");
     }
     return(Base58.Encode(cipher.calculateSignature(this.privateKey, bytes)));
 }
예제 #29
0
        public void Java()
        {
            var input   = "QmPZ9gcCEpqKTo6aq61g2nXGUhM4iCL3ewB6LDXZCtioEB";
            var output  = Base58.Decode(input);
            var encoded = Base58.Encode(output);

            Assert.Equal(input, encoded);
        }
예제 #30
0
        public static void EncodeDoesNotModifyArray()
        {
            var b1 = new byte[] { 0, 1, 2, 3, 4, 5 };
            var b2 = new byte[] { 0, 1, 2, 3, 4, 5 };

            Base58.Encode(b1);
            Assert.Equal(b1, b2);
        }