Exemplo n.º 1
0
        private void Serialize()
        {
            // transaction type. Set as null/empty bytes as it will be
            // updated when serializing the different transaction types.
            Serializer.WriteInt(TransactionType.MultisigTransaction);

            // version
            Serializer.WriteInt(TransactionVersion.VersionOne);

            // timestamp
            Serializer.WriteInt(TimeStamp);

            //pubKey len
            Serializer.WriteInt(ByteLength.PublicKeyLength);

            // pub key

            Serializer.WriteBytes(CryptoBytes.FromHexString(PublicKey.Raw));

            // fee
            Serializer.WriteLong(Fee);

            // deadline
            Serializer.WriteInt(Deadline);

            Serializer.WriteInt(InnerLength);
        }
Exemplo n.º 2
0
        public void HChaCha20StateTestVector()
        {
            // https://tools.ietf.org/html/draft-irtf-cfrg-xchacha-03#section-2.2.1

            // Arrange
            var key    = CryptoBytes.FromHexString("00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f".Replace(":", string.Empty));
            var nonce  = CryptoBytes.FromHexString("00:00:00:09:00:00:00:4a:00:00:00:00:31:41:59:27".Replace(":", string.Empty));
            var cipher = new XChaCha20(key, 0);

            // Act
            var initialState = new uint[16];

            cipher.HChaCha20InitialState(initialState, nonce);

            // Assert
            var expectedInitialState = new uint[]
            {
                0x61707865, 0x3320646e, 0x79622d32, 0x6b206574,
                0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c,
                0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c,
                0x09000000, 0x4a000000, 0x00000000, 0x27594131
            };

            initialState.Should().BeEquivalentTo(expectedInitialState);
        }
Exemplo n.º 3
0
        public void HChaCha20BlockTestVector()
        {
            // https://tools.ietf.org/html/draft-irtf-cfrg-xchacha-03#section-2.2.1

            // Arrange
            var key    = CryptoBytes.FromHexString("00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f".Replace(":", string.Empty));
            var nonce  = CryptoBytes.FromHexString("00:00:00:09:00:00:00:4a:00:00:00:00:31:41:59:27".Replace(":", string.Empty));
            var cipher = new XChaCha20(key, 0);

            // Act
            var subKey = new byte[32];

            cipher.HChaCha20(subKey, nonce);
            var state = subKey.ToUInt16Array();
            //var stateHex = CryptoBytes.ToHexStringLower(subKey.ToArray());

            // Assert
            // HChaCha20 returns only the first and last rows
            var expectedState = new uint[]
            {
                0x423b4182, 0xfe7bb227, 0x50420ed3, 0x737d878a,
                //0x0aa76448, 0x7954cdf3, 0x846acd37, 0x7b3c58ad,
                //0x77e35583, 0x83e77c12, 0xe0076a2d, 0xbc6cd0e5,
                0xd5e4f9a0, 0x53a8748a, 0x13c42ec1, 0xdcecd326
            };

            // Same as above but in HEX
            //var expectedStateHex = "82413b4" + "227b27bfe" + "d30e4250" + "8a877d73"
            //                     + "a0f9e4d" + "58a74a853" + "c12ec413" + "26d3ecdc";

            state.Should().BeEquivalentTo(expectedState);
            //stateHex.Should().Be(expectedStateHex);
        }
Exemplo n.º 4
0
        public void ChaCha20BlockTestVector()
        {
            // https://tools.ietf.org/html/rfc8439#section-2.3.2

            // Arrange
            var key     = CryptoBytes.FromHexString("00:01:02:03:04:05:06:07:08:09:0a:0b:0c:0d:0e:0f:10:11:12:13:14:15:16:17:18:19:1a:1b:1c:1d:1e:1f".Replace(":", string.Empty));
            var nonce   = CryptoBytes.FromHexString("00:00:00:09:00:00:00:4a:00:00:00:00".Replace(":", string.Empty));
            var counter = 1;

            // Act
            var chacha20 = new ChaCha20(key, 1);
            var output   = new byte[ChaCha20.BLOCK_SIZE_IN_BYTES];

            chacha20.ProcessKeyStreamBlock(nonce, counter, output);

            // Assert
            var expected = new uint[16]
            {
                0xe4e7f110, 0x15593bd1, 0x1fdd0f50, 0xc47120a3,
                0xc7f4d1c7, 0x0368c033, 0x9aaa2204, 0x4e6cd4c3,
                0x466482d2, 0x09aa9f07, 0x05d7c214, 0xa2028bd9,
                0xd19c12b5, 0xb94e16de, 0xe883d0cb, 0x4e3c50a2,
            };

            output.ToUInt16Array().Should().Equal(expected);
        }
Exemplo n.º 5
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());
        }
Exemplo n.º 6
0
        public void Poly1305TestVector4()
        {
            // Tests against the test vector 4 in Appendix A.3 of RFC 7539.
            // https://tools.ietf.org/html/rfc7539#appendix-A.3

            // Arrange
            var key = CryptoBytes.FromHexString("1c9240a5eb55d38af333888604f6b5f0"
                                                + "473917c1402b80099dca5cbc207075c0");
            var dat = CryptoBytes.FromHexString("2754776173206272696c6c69672c2061"
                                                + "6e642074686520736c6974687920746f"
                                                + "7665730a446964206779726520616e64"
                                                + "2067696d626c6520696e207468652077"
                                                + "6162653a0a416c6c206d696d73792077"
                                                + "6572652074686520626f726f676f7665"
                                                + "732c0a416e6420746865206d6f6d6520"
                                                + "7261746873206f757467726162652e");

            // Act
            var mac = new byte[Poly1305.MAC_TAG_SIZE_IN_BYTES];

            Poly1305.ComputeMac(key, dat, mac);

            // Assert
            mac.Should().Equal(CryptoBytes.FromHexString("4541669a7eaaee61e708dc7cbcc5eb62"));
        }
        private void Serialize()
        {
            TotalBytesLength += 4;
            Serializer.WriteInt(Data.Modifications.Count);

            foreach (var mod in Data.Modifications)
            {
                TotalBytesLength += StructureLength.AggregateModification + ByteLength.FourBytes;
                Serializer.WriteInt(StructureLength.AggregateModification);
                Serializer.WriteInt(mod.ModificationType);
                Serializer.WriteInt(ByteLength.PublicKeyLength);
                Serializer.WriteBytes(CryptoBytes.FromHexString(mod.PublicKey.Raw));
            }
            if (Data.RelativeChange != 0)
            {
                TotalBytesLength += StructureLength.RelativeChange + ByteLength.FourBytes;
                Serializer.WriteInt(StructureLength.RelativeChange);
                Serializer.WriteInt(Data.RelativeChange);
            }
            else
            {
                TotalBytesLength += ByteLength.FourBytes;
                Serializer.WriteInt(ByteLength.Zero);
            }
        }
Exemplo n.º 8
0
 public static string Decode(string text, PrivateKey sk, string pk)
 {
     return(_Decode(
                CryptoBytes.FromHexString(StringUtils.ConvertToUnsecureString(sk.Raw)),
                CryptoBytes.FromHexString(pk),
                CryptoBytes.FromHexString(text)));
 }
Exemplo n.º 9
0
        private void Serialize()
        {
            var sumLen = 0;

            foreach (var p in MosaicProperties)
            {
                sumLen += p.PropertyLength + 4;
            }

            Length = 60 + NamespaceId.Length
                     + MosaicName.Length
                     + Description.Length
                     + sumLen;

            // mosaic definition length
            if (Model.MosaicLevy != null)
            {
                Serializer.WriteInt(Length + (Model.MosaicLevy.Length - 4));
            }
            else
            {
                Serializer.WriteInt(Length);
            }

            // length if creator public key
            Serializer.WriteInt(ByteLength.PublicKeyLength);

            // creator public key
            Serializer.WriteBytes(CryptoBytes.FromHexString(Creator.Raw));

            // mosaic id structure length
            Serializer.WriteInt(ByteLength.EightBytes + NamespaceId.Length + MosaicName.Length);

            // namespace id length
            Serializer.WriteInt(NamespaceId.Length);

            // namespace
            Serializer.WriteBytes(NamespaceId);

            // mosaic name length
            Serializer.WriteInt(MosaicName.Length);

            // mosaic name
            Serializer.WriteBytes(MosaicName);

            // description length
            Serializer.WriteInt(Description.Length);

            // description
            Serializer.WriteBytes(Description);

            // properties count
            Serializer.WriteInt(MosaicProperties.Count);

            foreach (var mp in MosaicProperties)
            {
                Serializer.WriteBytes(mp.GetBytes());
            }
        }
Exemplo n.º 10
0
 /// <summary>
 /// Converts a hex string to an array of bytes.
 /// </summary>
 /// <param name="hexStr">Hex string to convert, it may optionally start with the "0x" prefix.</param>
 /// <returns>Array of bytes.</returns>
 public static byte[] HexStringToBytes(string hexStr)
 {
     if (hexStr.StartsWith("0x"))
     {
         return(CryptoBytes.FromHexString(hexStr.Substring(2)));
     }
     return(CryptoBytes.FromHexString(hexStr));
 }
Exemplo n.º 11
0
        private void Serialize(PublicKey PublicKey)
        {
            Serializer.WriteBytes(TransferMode);

            Serializer.WriteInt(ByteLength.PublicKeyLength);

            Serializer.WriteBytes(CryptoBytes.FromHexString(PublicKey.Raw));
        }
Exemplo n.º 12
0
        }                                      // used to identify the benchmark test

        public Rfc8439TestVector(string key, string plaintext, string nonce, string ciphertext, int initialCounter, string id)
        {
            Key            = CryptoBytes.FromHexString(key);
            PlainText      = CryptoBytes.FromHexString(plaintext);
            Nonce          = CryptoBytes.FromHexString(nonce);
            CipherText     = CryptoBytes.FromHexString(ciphertext);
            InitialCounter = initialCounter;
            Id             = id;
        }
Exemplo n.º 13
0
        }                                      // used to identify the benchmark test

        public XChaCha20Poly1305TestVector(string key, string nonce, string plaintext, string aad, string ciphertext, string tag, string id)
        {
            Key        = CryptoBytes.FromHexString(key);
            Nonce      = CryptoBytes.FromHexString(nonce);
            PlainText  = CryptoBytes.FromHexString(plaintext);
            Aad        = CryptoBytes.FromHexString(aad);
            CipherText = CryptoBytes.FromHexString(ciphertext);
            Tag        = CryptoBytes.FromHexString(tag);
            Id         = id;
        }
Exemplo n.º 14
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="KeyPair" /> class.
 /// </summary>
 /// <param name="privateKey">The private key</param>
 /// <param name="publicKey">The public key</param>
 public KeyPair(string privateKey, string publicKey)
 {
     Guard.NotNullOrEmpty(publicKey, nameof(publicKey));
     Guard.NotEqualTo(publicKey.Length, 64, new ArgumentOutOfRangeException(nameof(publicKey)));
     PrivateKeyString = privateKey;
     PublicKeyString  = publicKey;
     //PrivateKey = privateKey.FromHex();
     //PublicKey = publicKey.FromHex();
     PrivateKey = CryptoBytes.FromHexString(privateKey);
     PublicKey  = CryptoBytes.FromHexString(publicKey);
 }
Exemplo n.º 15
0
        public Salsa20TestVector(string name, string key, string iv, string block1, string block4, string block5, string block8)
        {
            Name = name;
            Key  = CryptoBytes.FromHexString(key);
            IV   = CryptoBytes.FromHexString(iv);

            ExpectedBlock1 = block1;
            ExpectedBlock4 = block4;
            ExpectedBlock5 = block5;
            ExpectedBlock8 = block8;
        }
Exemplo n.º 16
0
        /// <summary>
        ///     Create KeyPair from private key
        /// </summary>
        /// <param name="privateKey">The private key</param>
        /// <returns></returns>
        public static KeyPair CreateFromPrivateKey(string privateKey)
        {
            Guard.NotNullOrEmpty(privateKey, nameof(privateKey));
            Guard.NotEqualTo(privateKey.Length, 64, new ArgumentOutOfRangeException(nameof(privateKey)));

            // var privateKeyArray = privateKey.FromHex();
            // var publicKey = Ed25519.PublicKeyFromSeed(privateKeyArray).ToHexUpper();
            var privateKeyArray = CryptoBytes.FromHexString(privateKey);
            var publicKey       = CryptoBytes.ToHexStringUpper(Ed25519.PublicKeyFromSeed(privateKeyArray));

            return(new KeyPair(privateKey, publicKey));
        }
Exemplo n.º 17
0
        private void Serialize()
        {
            Serializer.WriteInt(0x24);

            Serializer.WriteInt(0x20);

            Serializer.WriteBytes(CryptoBytes.FromHexString(Data.TransactionHash));

            Serializer.WriteInt(0x28);

            Serializer.WriteBytes(Encoding.UTF8.GetBytes(Data.MultisigAddress.Encoded));
        }
Exemplo n.º 18
0
        /*
         * Still no idea... doesnt work either.. cant seem to fix it..
         * For some reason the produced hash isnt used and
         * breaks even more when it is.. 0.o
         *
         */
        private static byte[] GetSharedKey(PrivateKey privateKey, string publicKey, byte[] salt)
        {
            var shared = new byte[32];

            var hash = Ed25519.key_derive( // TODO: find out why hash isnt used.
                shared,
                salt,
                CryptoBytes.FromHexString(publicKey),
                CryptoBytes.FromHexString(StringUtils.ConvertToUnsecureString(privateKey.Raw)));


            return(shared);
        }
Exemplo n.º 19
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)));
        }
Exemplo n.º 20
0
        }                                      // used to identify the benchmark test

        public XChaCha20TestVector(string key, string nonce, string ciphertext, string plaintext, string id)
        {
            Key        = CryptoBytes.FromHexString(key);
            Nonce      = CryptoBytes.FromHexString(nonce);
            CipherText = CryptoBytes.FromHexString(ciphertext);
            PlainText  = CryptoBytes.FromHexString(plaintext);

            if (plaintext.Length == 0)
            {
                PlainText = new byte[CipherText.Length];
            }

            Id = id;
        }
Exemplo n.º 21
0
        public void Poly1305TestVector9()
        {
            // Tests against the test vector 9 in Appendix A.3 of RFC 7539.
            // https://tools.ietf.org/html/rfc7539#appendix-A.3

            // Arrange
            var key = CryptoBytes.FromHexString("02000000000000000000000000000000"
                                                + "00000000000000000000000000000000");
            var dat = CryptoBytes.FromHexString("fdffffffffffffffffffffffffffffff");

            // Act
            var mac = Poly1305.ComputeMac(key, dat);

            // Assert
            Assert.AreEqual(CryptoBytes.FromHexString("faffffffffffffffffffffffffffffff"), mac);
        }
Exemplo n.º 22
0
        public void ComputeMacTest()
        {
            // Tests against the test vectors in Section 2.5.2 of RFC 7539.
            // https://tools.ietf.org/html/rfc7539#section-2.5.2

            // Arrange
            var key = CryptoBytes.FromHexString("85d6be7857556d337f4452fe42d506a8"
                                                + "0103808afb0db2fd4abff6af4149f51b");
            var dat = Encoding.UTF8.GetBytes("Cryptographic Forum Research Group");

            // Act
            var mac = Poly1305.ComputeMac(key, dat);

            // Assert
            Assert.AreEqual(CryptoBytes.FromHexString("a8061dc1305136c6c22b8baf0c0127a9"), mac);
        }
Exemplo n.º 23
0
        public void Poly1305TestVector3()
        {
            // Tests against the test vector 3 in Appendix A.3 of RFC 7539.
            // https://tools.ietf.org/html/rfc7539#appendix-A.3

            // Arrange
            var key = CryptoBytes.FromHexString("36e5f6b5c5e06070f0efca96227a863e"
                                                + "00000000000000000000000000000000");
            var dat = Encoding.UTF8.GetBytes("Any submission to the IETF intended by the Contributor for publication as all or part of an IETF Internet-Draft or RFC and any statement made within the context of an IETF activity is considered an \"IETF Contribution\". Such statements include oral statements in IETF sessions, as well as written and electronic communications made at any time or place, which are addressed to");

            // Act
            var mac = Poly1305.ComputeMac(key, dat);

            // Assert
            Assert.AreEqual(CryptoBytes.FromHexString("f3477e7cd95417af89a6b8794c310cf0"), mac);
        }
        /// <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());
        }
Exemplo n.º 25
0
        public void Poly1305TestVector9()
        {
            // Tests against the test vector 9 in Appendix A.3 of RFC 7539.
            // https://tools.ietf.org/html/rfc7539#appendix-A.3

            // Arrange
            var key = CryptoBytes.FromHexString("02000000000000000000000000000000"
                                                + "00000000000000000000000000000000");
            var dat = CryptoBytes.FromHexString("fdffffffffffffffffffffffffffffff");

            // Act
            var mac = new byte[Poly1305.MAC_TAG_SIZE_IN_BYTES];

            Poly1305.ComputeMac(key, dat, mac);

            // Assert
            mac.Should().Equal(CryptoBytes.FromHexString("faffffffffffffffffffffffffffffff"));
        }
Exemplo n.º 26
0
        public void Poly1305TestVector11()
        {
            // Tests against the test vector 11 in Appendix A.3 of RFC 7539.
            // https://tools.ietf.org/html/rfc7539#appendix-A.3

            // Arrange
            var key = CryptoBytes.FromHexString("01000000000000000400000000000000"
                                                + "00000000000000000000000000000000");
            var dat = CryptoBytes.FromHexString("e33594d7505e43b90000000000000000"
                                                + "3394d7505e4379cd0100000000000000"
                                                + "00000000000000000000000000000000");

            // Act
            var mac = Poly1305.ComputeMac(key, dat);

            // Assert
            Assert.AreEqual(CryptoBytes.FromHexString("13000000000000000000000000000000"), mac);
        }
Exemplo n.º 27
0
        public static string Encode(string text, PrivateKey sk, string pk)
        {
            SecureRandom random = new SecureRandom();

            var salt = new byte[32];

            random.NextBytes(salt);

            var ivData = new byte[16];

            random.NextBytes(ivData);

            return(_Encode(
                       CryptoBytes.FromHexString(StringUtils.ConvertToUnsecureString(sk.Raw)),
                       CryptoBytes.FromHexString(pk),
                       text,
                       ivData,
                       salt));
        }
Exemplo n.º 28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Signature"/> class.
        /// </summary>
        /// <remarks>
        /// Uses twisted edwards elliptic curve, Ed25519, to produce signatures.
        /// </remarks>
        /// <param name="data">The data bytes to sign.</param>
        /// <param name="privateKey">The private key used to sign the bytes.</param>
        /// <example>
        /// This sample shows how to create a new instance of the <see cref="Signature"/> class and produce a signature.
        /// <code>
        /// class TestClass
        /// {
        ///     static void Main()
        ///     {
        ///         byte[] bytes = new byte[10];
        ///
        ///         Signature sig = new Signature(bytes, new PrivateKey("0705c2634de7e58325dabc58c4a794559be4d55d102d3aafcb189acb2e596add"));
        ///
        ///         string signature = sig._Signature;
        ///     }
        /// }
        /// </code>
        /// </example>
        public Signature(byte[] data, PrivateKey privateKey)
        {
            var sig = new byte[64];

            try
            {
                var sk = new byte[64];
                Array.Copy(CryptoBytes.FromHexString(StringUtils.ConvertToUnsecureString(privateKey.Raw)), sk, 32);
                Array.Copy(
                    CryptoBytes.FromHexString(
                        new PublicKey(PublicKeyConversion.ToPublicKey(privateKey)).Raw), 0,
                    sk, 32, 32);
                Ed25519.crypto_sign2(sig, data, sk, 32);
                CryptoBytes.Wipe(sk);
            }
            finally
            {
                _Signature = sig;
            }
        }
Exemplo n.º 29
0
        /*
         * Constructs the message object and initiates its serialization
         *
         * @Param: Serializer, The serializer to use during serialization
         * @Param: Message, The message string. Note: if null, a zero value byte[4] is serialized instead
         * @Param: Encrypted, Whether the message should be encrypted or not
         */

        internal Message(Connectivity.Connection con, PrivateKey senderKey, string address, string message, bool encrypted)

        {
            Encrypted = encrypted;

            MessageString = message;

            if (MessageString != null)
            {
                if (Encrypted)
                {
                    var a = new AccountClient(con).BeginGetAccountInfoFromAddress(body =>
                    {
                        PublicKey = body.Content.Account.PublicKey ?? throw new Exception("recipient public key cannot be null for encryption");
                    }, address);

                    a.AsyncWaitHandle.WaitOne();

                    if (PublicKey == null)
                    {
                        throw new ArgumentNullException("could not find recipient public key");
                    }

                    Sender = new PrivateKeyAccountClient(con, senderKey);

                    MessageBytes = CryptoBytes.FromHexString(Encryption.Encode(MessageString, senderKey, PublicKey));
                }
                else
                {
                    MessageBytes = Encoding.UTF8.GetBytes(MessageString);
                }

                PayloadLengthInBytes = MessageBytes.Length;
            }

            Serialize();

            CalculateMessageFee();
        }
Exemplo n.º 30
0
        public void Should_Sign_Data_And_Verify_Signature_SHA3_256()
        {
            var pk      = "A574ECE8F79DE11A39C6BADF0EF87C2C88730A5EA4CF2C0BD7E27103390BC4F4";
            var pubKey  = "2B0FF0CADE0D945A23D1AF7AF266A0BAB7E07B163756F5F16CC75F24A4EEF23B";
            var keyPair = KeyPair.CreateFromPrivateKey(pk);
            var message = "This is a test data";
            var data    = Encoding.UTF8.GetBytes(message);

            var encryptedData = CryptoUtils.Sha3_256(data);
            var encryptedHex  = CryptoBytes.ToHexStringUpper(encryptedData);

            var signature = keyPair.Sign(encryptedData);

            var sigHex = CryptoBytes.ToHexStringUpper(signature);

            var sig2 = CryptoBytes.FromHexString(sigHex);

            var publicAccount = PublicAccount.CreateFromPublicKey(pubKey, NetworkType.MIJIN_TEST);

            var isValid = publicAccount.VerifySignature(encryptedData, sig2);

            isValid.Should().BeTrue();
        }