Ejemplo n.º 1
0
        internal static string _Encode(byte[] privateKey, byte[] pubKey, string msg, byte[] iv, byte[] salt)
        {
            var shared = new byte[32];

            Ed25519.key_derive(
                shared,
                salt,
                privateKey,
                pubKey);

            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = shared;

                aesAlg.IV = iv;

                aesAlg.Mode = CipherMode.CBC;

                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(msg);
                        }

                        return(CryptoBytes.ToHexStringLower(salt) + CryptoBytes.ToHexStringLower(iv) + CryptoBytes.ToHexStringLower(msEncrypt.ToArray()));
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public void RandomNonceTest()
        {
            var rnd = new Random();
            var key = new byte[Snuffle.KEY_SIZE_IN_BYTES];

            rnd.NextBytes(key);

            var aead = new ChaCha20Poly1305(key);

            var message     = new byte[0];
            var aad         = new byte[0];
            var ciphertexts = new HashSet <string>();
            var samples     = 1 << 17;

            for (var i = 0; i < samples; i++)
            {
                var ct    = aead.Encrypt(message, aad);
                var ctHex = CryptoBytes.ToHexStringLower(ct);

                Assert.IsFalse(ciphertexts.Contains(ctHex));
                ciphertexts.Add(ctHex);
            }

            Assert.AreEqual(samples, ciphertexts.Count);
        }
Ejemplo n.º 3
0
        public static string PublicKeyToAddress(byte[] publicKey, int networkPrefix)
        {
            KeccakDigest shaDigest = new KeccakDigest(256);

            byte[] bytesFirst = new byte[32];

            shaDigest.BlockUpdate(publicKey, 0, 32);
            shaDigest.DoFinal(bytesFirst, 0);

            RipeMD160Digest digestRipeMd160 = new RipeMD160Digest();

            byte[] bytesSecond = new byte[20];

            digestRipeMd160.BlockUpdate(bytesFirst, 0, 32);
            digestRipeMd160.DoFinal(bytesSecond, 0);

            byte[] bytesThird = CryptoBytes.FromHexString(
                string.Concat(networkPrefix,
                              CryptoBytes.ToHexStringLower(bytesSecond))
                );

            byte[] bytesFourth = new byte[32];

            shaDigest.BlockUpdate(bytesThird, 0, 21);
            shaDigest.DoFinal(bytesFourth, 0);

            byte[] bytesFifth = new byte[4];
            Array.Copy(bytesFourth, 0, bytesFifth, 0, 4);

            byte[] bytesSixth = new byte[25];
            Array.Copy(bytesThird, 0, bytesSixth, 0, 21);
            Array.Copy(bytesFifth, 0, bytesSixth, 21, 4);

            return(Base32.Encode(bytesSixth).ToUpper());
        }
Ejemplo n.º 4
0
        public static KeyPairViewModel GenerateFromPrivateKey(byte[] privateKey, int networkPrefix)
        {
            Array.Reverse(privateKey);
            byte[] publicKey = Ed25519.PublicKeyFromSeed(privateKey);
            Array.Reverse(privateKey);

            string address = PublicKeyToAddress(publicKey, networkPrefix);

            return(new KeyPairViewModel(CryptoBytes.ToHexStringLower(privateKey), CryptoBytes.ToHexStringLower(publicKey), address));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Produces a <see cref="PrivateKeyAccountClient"/> from a given <see cref="SecureString"/> of any size.
        /// </summary>
        /// <remarks>
        /// Takes a SecureString, hashes with Sha3 and converts the produced bytes to a 64 char hex string. The <see cref="StringUtils"/> class contains methods to convert to or from <see cref="SecureString"/>.
        /// </remarks>
        /// <param name="data">The data to convert to a private key.</param>
        /// <returns>A <see cref="PrivateKeyAccountClient"/> that can be used to initiate transactions.</returns>
        public PrivateKeyAccountClient FromNewDataPrivateKey(SecureString data)
        {
            var digestSha3 = new KeccakDigest(256);
            var dataBytes  = Encoding.Default.GetBytes(StringUtils.ConvertToUnsecureString(data));
            var pkBytes    = new byte[32];

            digestSha3.BlockUpdate(dataBytes, 0, 32);
            digestSha3.DoFinal(pkBytes, 0);
            var sk = StringUtils.ToSecureString(CryptoBytes.ToHexStringLower(pkBytes));

            return(FromPrivateKey(new PrivateKey(sk)));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Produces a public key from a given private key.
        /// </summary>
        /// <param name="privateKey">The private key to derive a public key from.</param>
        /// <remarks>
        /// As well as 64 char private keys, 66 char negative private keys are supported also supported. This does not affect the public key produced.
        /// </remarks>
        /// <returns>The derived public key string</returns>
        /// <exception cref="ArgumentException">invalid private key. Exacption bounds: Must be only hex string. Must be equal to 64 or 66 chars in length.</exception>
        /// <example>
        /// This sample shows how to use the <see cref="ToPublicKey"/> method.
        /// <code>
        /// class TestClass
        /// {
        ///     static void Main()
        ///     {
        ///         string publicKey = PublicKeyConversion.ToPublicKey(new PrivateKey("0705c2634de7e58325dabc58c4a794559be4d55d102d3aafcb189acb2e596add"));
        ///     }
        /// }
        /// </code>
        /// </example>
        public static string ToPublicKey(PrivateKey privateKey)
        {
            if (!StringUtils.OnlyHexInString(privateKey.Raw) ||
                privateKey.Raw.Length == 64 && privateKey.Raw.Length == 66)
            {
                throw new ArgumentException("invalid private key");
            }

            var privateKeyArray = CryptoBytes.FromHexString(StringUtils.ConvertToUnsecureString(privateKey.Raw));

            Array.Reverse(privateKeyArray);

            return(CryptoBytes.ToHexStringLower(Ed25519.PublicKeyFromSeed(privateKeyArray)));
        }
Ejemplo n.º 7
0
 private static FilterLog ConvertEthFilterLogToFilterLog(EthFilterLog log)
 {
     return(new FilterLog
     {
         Address = Address.FromBytes(log.Address.ToByteArray()).LocalAddress,
         Data = CryptoUtils.BytesToHexString(log.Data.ToByteArray()),
         Removed = log.Removed,
         Topics = log.Topics.Select(t => (object)t.ToStringUtf8()).ToArray(),
         Type = "",
         BlockHash = CryptoBytes.ToHexStringLower(log.BlockHash.ToByteArray()),
         BlockNumber = new HexBigInteger(log.BlockNumber),
         LogIndex = new HexBigInteger(log.LogIndex),
         TransactionHash = CryptoBytes.ToHexStringLower(log.TransactionHash.ToByteArray()),
         TransactionIndex = new HexBigInteger(log.TransactionIndex)
     });
 }
        /// <summary>
        /// Converts a public key to a main net or test net address. Network byte determines which network version to convert to.
        /// </summary>
        /// <param name="network">The network byte.</param>
        /// <param name="publicKey">The public key.</param>
        /// <returns>The unhyphenated address string.</returns>
        /// <exception cref="ArgumentException">invalid public key. Thrown when a public key is not a 64 char hex string.</exception>
        /// <example>
        /// This sample shows how to use the <see cref="ToEncoded"/> method.
        /// <code>
        /// class TestClass
        /// {
        ///     static void Main()
        ///     {
        ///         Connection connection = new Connection();
        ///
        ///         string address = AddressEncoding.ToEncoded(connection.GetNetworkVersion(), new PublicKey("0705c2634de7e58325dabc58c4a794559be4d55d102d3aafcb189acb2e596add"));
        ///     }
        /// }
        /// </code>
        /// </example>
        public static string ToEncoded(byte network, PublicKey publicKey)
        {
            if (!StringUtils.OnlyHexInString(publicKey.Raw) || publicKey.Raw.Length != 64)
            {
                throw new ArgumentException("invalid public key");
            }

            // step 1) sha-3(256) public key
            var digestSha3 = new KeccakDigest(256);
            var stepOne    = new byte[32];

            digestSha3.BlockUpdate(CryptoBytes.FromHexString(publicKey.Raw), 0, 32);
            digestSha3.DoFinal(stepOne, 0);

            // step 2) perform ripemd160 on previous step
            var digestRipeMd160 = new RipeMD160Digest();
            var stepTwo         = new byte[20];

            digestRipeMd160.BlockUpdate(stepOne, 0, 32);
            digestRipeMd160.DoFinal(stepTwo, 0);

            // step3) prepend network byte
            var stepThree =
                CryptoBytes.FromHexString(string.Concat(network == 0x68 ? 68 : 98, CryptoBytes.ToHexStringLower(stepTwo)));

            // step 4) perform sha3 on previous step
            var stepFour = new byte[32];

            digestSha3.BlockUpdate(stepThree, 0, 21);
            digestSha3.DoFinal(stepFour, 0);

            // step 5) retrieve checksum
            var stepFive = new byte[4];

            Array.Copy(stepFour, 0, stepFive, 0, 4);

            // step 6) append stepFive to resulst of stepThree
            var stepSix = new byte[25];

            Array.Copy(stepThree, 0, stepSix, 0, 21);
            Array.Copy(stepFive, 0, stepSix, 21, 4);

            // step 7) return base 32 encode address byte array

            return(new Utils.Base32Encoder().Encode(stepSix).ToUpper());
        }
Ejemplo n.º 9
0
        public static PrivateKey Create()
        {
            var ng    = RandomNumberGenerator.Create();
            var bytes = new byte[2048];

            ng.GetNonZeroBytes(bytes);

            var digestSha3 = new KeccakDigest(256);
            var stepOne    = new byte[32];

            digestSha3.BlockUpdate(bytes, 0, 32);
            digestSha3.DoFinal(stepOne, 0);

            var pk = new PrivateKey(StringUtils.ToSecureString(CryptoBytes.ToHexStringLower(stepOne)));

            bytes   = null;
            stepOne = null;
            return(pk);
        }
Ejemplo n.º 10
0
    protected void btnGerarChave_Click(object sender, EventArgs e)
    {
        RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
        var byteArray = new byte[32];

        provider.GetBytes(byteArray);

        var oi = CryptoBytes.ToHexStringLower(byteArray);

        byte[] chavePri, chavePu;

        Ed25519.KeyPairFromSeed(out chavePu, out chavePri, byteArray);

        var pri = CryptoBytes.ToHexStringLower(chavePri);
        var pu  = CryptoBytes.ToHexStringLower(chavePu);


        chaveSementeGerada.Text = oi;
        chavePublicaGerada.Text = pu;
    }
Ejemplo n.º 11
0
        public void WycheproofTestVectors()
        {
            var json = GetWycheproofTestVector();

            var vector = JsonConvert.DeserializeObject <WycheproofVector>(json); //Utf8Json.JsonSerializer.Deserialize<WycheproofVector>(json);

            var errors = 0;

            foreach (var group in vector.TestGroups)
            {
                foreach (var test in group.Tests)
                {
                    var id = $"TestCase {test.TcId}";
                    if (!string.IsNullOrEmpty(test.Comment))
                    {
                        id += $" ({test.Comment})";
                    }

                    var iv         = CryptoBytes.FromHexString(test.Iv);
                    var key        = CryptoBytes.FromHexString(test.Key);
                    var msg        = CryptoBytes.FromHexString(test.Msg);
                    var aad        = CryptoBytes.FromHexString(test.Aad);
                    var ct         = CryptoBytes.FromHexString(test.Ct);
                    var tag        = CryptoBytes.FromHexString(test.Tag);
                    var ciphertext = iv.Concat(ct).Concat(tag).ToArray();

                    // Result is one of "valid", "invalid", "acceptable".
                    // "valid" are test vectors with matching plaintext, ciphertext and tag.
                    // "invalid" are test vectors with invalid parameters or invalid ciphertext and tag.
                    // "acceptable" are test vectors with weak parameters or legacy formats.

                    var result = test.Result;

                    try
                    {
                        var aead      = new ChaCha20Poly1305(key);
                        var decrypted = aead.Decrypt(ciphertext, aad);

                        if (test.Result == "invalid")
                        {
                            TestContext.WriteLine($"FAIL {id}: accepting invalid ciphertext, cleartext: {test.Msg}, decrypted: {CryptoBytes.ToHexStringLower(decrypted)}");
                            errors++;

                            continue;
                        }

                        if (!CryptoBytes.ConstantTimeEquals(msg, decrypted))
                        {
                            TestContext.WriteLine($"FAIL {id}: incorrect decryption, result: {CryptoBytes.ToHexStringLower(decrypted)}, expected: {test.Msg}");
                            errors++;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (test.Result == "valid")
                        {
                            TestContext.WriteLine($"FAIL {id}: cannot decrypt, exception: {ex}");
                            errors++;
                        }
                    }
                }
            }

            Assert.AreEqual(0, errors);
        }
Ejemplo n.º 12
0
 public void ToHexStringLowerNull()
 {
     Assert.AreEqual(null, CryptoBytes.ToHexStringLower(null));
 }
Ejemplo n.º 13
0
 public void ToHexStringLower()
 {
     Assert.AreEqual(HexStringLower, CryptoBytes.ToHexStringLower(_bytes));
 }
Ejemplo n.º 14
0
 public void ToHexStringLowerNull()
 {
     CryptoBytes.ToHexStringLower(null).Should().BeNull();
 }
Ejemplo n.º 15
0
 public void ToHexStringLower()
 {
     CryptoBytes.ToHexStringLower(_bytes).Should().Be(HexStringLower);
 }