public static UInt512 HmacSha512(this ReadOnlyByteSpan key, ReadOnlyByteSequence data)
        {
            var hash = new UInt512();

            new HMACSHA512(key).TransformFinalBlock(data, hash.Span);
            return(hash);
        }
Ejemplo n.º 2
0
        public static UInt256 Sha256(this ReadOnlyByteSpan data)
        {
            var hash = new UInt256();

            Sha256(data, hash.Span);
            return(hash);
        }
Ejemplo n.º 3
0
 protected void SetData(ReadOnlyByteSpan version, ReadOnlyByteSpan data, bool flag = false)
 {
     _versionData   = new byte[version.Length + data.Length + 1];
     _versionLength = version.Length;
     version.CopyTo(Version);
     data.CopyTo(KeyData);
     KeyData.Data[^ 1] = (byte)(flag ? 1 : 0);
Ejemplo n.º 4
0
        /// <summary>
        /// Applies AES encryption to data with the specified key.
        /// iv can be specified (must be 16 bytes) or left null.
        /// The actual iv used is added to the first 16 bytes of the output result unless noIV = true.
        /// Padding is PKCS7.
        /// Mode is CBC.
        /// </summary>
        /// <param name="data">The data to encrypt.</param>
        /// <param name="key">The encryption key to use. The same key must be used to decrypt.</param>
        /// <param name="iv">null or 16 bytes of random initialization vector data</param>
        /// <param name="noInitVector">If true, the initialization vector used is not prepended to the encrypted result.</param>
        /// <returns>16 bytes of IV followed by encrypted data bytes.</returns>
        public static byte[] AesEncrypt(ReadOnlyByteSpan data, byte[] key, byte[] iv = null, bool noInitVector = false)
        {
            using var aes = new AesCryptoServiceProvider { Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC, Key = key };
            using var ms  = new MemoryStream();
            if (iv == null)
            {
                aes.GenerateIV();
                iv = aes.IV;
            }
            else
            {
                aes.IV = iv;
            }

            if (!noInitVector)
            {
                ms.Write(iv);
            }

            using (var cs = new CryptoStream(ms, aes.CreateEncryptor(key, iv), CryptoStreamMode.Write))
            {
                cs.Write(data);
            }

            return(ms.ToArray());
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Computes double SHA256 of data: SHA256(SHA256(data))
        /// </summary>
        /// <param name="data">Input: bytes to be hashed.</param>
        /// <returns>SHA256 of SHA256 of data.</returns>
        public static UInt256 Hash256(this ReadOnlyByteSpan data)
        {
            var hash = new UInt256();

            data.Hash256(hash.Span);
            return(hash);
        }
Ejemplo n.º 6
0
        public static UInt512 Sha512(this ReadOnlyByteSpan data)
        {
            var hash = new UInt512();

            Sha512(data, hash.Span);
            return(hash);
        }
Ejemplo n.º 7
0
        public static UInt160 Sha1(this ReadOnlyByteSpan data)
        {
            var hash = new UInt160();

            Sha1(data, hash.Span);
            return(hash);
        }
Ejemplo n.º 8
0
        public static UInt160 Ripemd160(this ReadOnlyByteSpan data)
        {
            var hash = new UInt160();

            Ripemd160(data, hash.Span);
            return(hash);
        }
Ejemplo n.º 9
0
        public static void TransformFinalBlock(this HashAlgorithm alg, ReadOnlyByteSpan data, ByteSpan hash)
        {
            var length = data.Length;
            var array  = ArrayPool <byte> .Shared.Rent(Math.Min(MaxBufferSize, length));

            try
            {
                var mOff = 0;
                do
                {
                    var mLen = Math.Min(array.Length, data.Length - mOff);
                    data.Slice(mOff, mLen).CopyTo(array);
                    mOff += mLen;
                    if (mOff < length)
                    {
                        alg.TransformBlock(array, 0, mLen, null, 0);
                    }
                    else
                    {
                        alg.TransformFinalBlock(array, 0, mLen);
                        alg.Hash.CopyTo(hash);
                    }
                }while (mOff < length);
            }
            finally
            {
                Array.Clear(array, 0, array.Length);
                ArrayPool <byte> .Shared.Return(array);
            }
        }
Ejemplo n.º 10
0
        public static byte[] ComputeHash(this HashAlgorithm alg, ReadOnlyByteSpan buffer)
        {
            var hash = new byte[alg.HashSize];

            alg.TransformFinalBlock(buffer, hash);
            return(hash);
        }
Ejemplo n.º 11
0
        public static UInt256 HmacSha256(this ReadOnlyByteSpan key, ReadOnlyByteSpan data)
        {
            var hash = new UInt256();

            new HMACSHA256(key).TransformFinalBlock(data, hash.Span);
            return(hash);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Duplicates Python hash library pbkdf2_hmac for hash_name = 'sha512' and dklen = None
        ///
        /// Performance can be improved by pre-computing _trans_36 and _trans_5c.
        /// Unlike Python's hash functions, .NET doesn't currently support copying state between blocks.
        /// This results in having to recompute hash of innerSeed and outerSeed on each iteration.
        /// </summary>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <param name="iterations"></param>
        /// <returns></returns>
        public static UInt512 PbKdf2HmacSha512(ReadOnlyByteSpan password, ReadOnlyByteSpan salt, int iterations)
        {
            if (iterations < 1)
            {
                throw new ArgumentException();
            }

            byte[] passwordBytes = password;

            using var inner = new SHA512Managed();
            using var outer = new SHA512Managed();

            const int blocksize = 128; // match python hash library sha512 block size.

            if (passwordBytes.Length > blocksize)
            {
                inner.TransformFinalBlock(passwordBytes, 0, passwordBytes.Length);
                passwordBytes = inner.Hash;
                //inner.Initialize();
            }

            if (passwordBytes.Length < blocksize)
            {
                Array.Resize(ref passwordBytes, blocksize);
            }

            var trans36 = new byte[256];
            var trans5C = new byte[256];

            for (var i = 0; i < 256; i++)
            {
                trans36[i] = (byte)(i ^ 0x36);
                trans5C[i] = (byte)(i ^ 0x5c);
            }

            var innerSeed = passwordBytes.Select(pb => trans36[pb]).ToArray();
            var outerSeed = passwordBytes.Select(pb => trans5C[pb]).ToArray();

            var hash  = new UInt512();
            var xhash = new UInt512();

            var data = new byte[salt.Length + 4];

            salt.CopyTo(data);
            1.AsReadOnlySpan(bigEndian: true).CopyTo(data.AsSpan(salt.Length));
            var dataSpan = data.AsSpan();

            for (var i = 0; i < iterations; i++)
            {
                inner.TransformBlock(innerSeed);
                outer.TransformBlock(outerSeed);
                inner.TransformFinalBlock(dataSpan, hash.Span);
                outer.TransformFinalBlock(hash.Span, hash.Span);
                dataSpan = hash.Span;
                xhash    = i == 0 ? hash : xhash ^ hash;
            }

            return(xhash);
        }
Ejemplo n.º 13
0
        public string Encode(ReadOnlyByteSpan data1, ReadOnlyByteSpan data2)
        {
            var bytes = new byte[data1.Length + data2.Length].AsSpan();

            data1.CopyTo(bytes);
            data2.CopyTo(bytes.Slice(data1.Length));
            return(Encode(bytes));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Computes double SHA256 of data: SHA256(SHA256(data))
        /// </summary>
        /// <param name="data">Input: bytes to be hashed.</param>
        /// <param name="hash">Output: SHA256 of SHA256 of data.</param>
        public static void Hash256(this ReadOnlyByteSpan data, ByteSpan hash)
        {
            var x = new UInt256();

            using var sha = new SHA256Managed();
            TransformFinalBlock(sha, data, x.Span);
            TransformFinalBlock(sha, x.Span, hash);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Appends first 4 bytes of double SHA256 hash to bytes before standard Base58 encoding.
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public override string Encode(ReadOnlyByteSpan bytes)
        {
            var checksum = bytes.Hash256();
            var buf      = new byte[bytes.Length + 4];

            bytes.CopyTo(buf);
            checksum.Span.Slice(0, 4).CopyTo(buf.AsSpan().Slice(bytes.Length));
            return(Encoders.Base58.Encode(buf));
        }
Ejemplo n.º 16
0
 public PublicKey(ReadOnlyByteSpan bytes)
     : this()
 {
     if (bytes.Length > 0 && bytes.Length == PredictLength(bytes[0]))
     {
         _bytes = new byte[bytes.Length];
         bytes.CopyTo(_bytes);
     }
 }
Ejemplo n.º 17
0
        public ScriptNum(ReadOnlyByteSpan bytes, bool fRequireMinimal = false, uint nMaximumSize = MaximumElementSize)
            : this()
        {
            if (bytes.Length > nMaximumSize) throw new OverflowError("script number overflow");

            if (fRequireMinimal && !IsMinimallyEncoded(bytes, nMaximumSize)) throw new MinEncodeError("non-minimally encoded script number");

            _value = set_vch(bytes);
        }
Ejemplo n.º 18
0
 public void Decode(ReadOnlyByteSpan code)
 {
     Depth       = code[0];
     Fingerprint = BitConverter.ToInt32(code.Slice(1, 4));
     Child       = (uint)code[5] << 24 | (uint)code[6] << 16 | (uint)code[7] << 8 | code[8];
     code.Slice(9, 32).CopyTo(ChainCode.Span);
     PublicKey = new PublicKey();
     PublicKey.Set(code.Slice(41, 33));
 }
Ejemplo n.º 19
0
 public UInt160(ReadOnlyByteSpan span, bool reverse = false) : this()
 {
     if (span.Length < Length)
     {
         throw new ArgumentException($"{Length} bytes are required.");
     }
     span.Slice(0, Length).CopyTo(Span);
     if (reverse)
     {
         Span.Reverse();
     }
 }
Ejemplo n.º 20
0
        public override string Encode(ReadOnlyByteSpan bytes)
        {
            var s = new char[bytes.Length * 2];
            var i = 0;

            foreach (var b in bytes)
            {
                var chs = ByteToChs[b];
                s[i++] = chs[0];
                s[i++] = chs[1];
            }
            return(new string(s));
        }
Ejemplo n.º 21
0
 internal void Set(ReadOnlyByteSpan data, bool compressed = true)
 {
     if (data.Length != UInt256.Length || !Check(data))
     {
         IsValid = false;
     }
     else
     {
         data.CopyTo(_keyData.Span);
         IsCompressed = compressed;
         IsValid      = true;
     }
 }
Ejemplo n.º 22
0
        public void Set(ReadOnlyByteSpan data)
        {
            var len = data.Length == 0 ? 0 : PredictLength(data[0]);

            if (len > 0 && len == data.Length)
            {
                _bytes = new byte[data.Length];
                data.CopyTo(_bytes.AsSpan());
            }
            else
            {
                Invalidate();
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// The complement function is PrivateKey CreateCompatSignature.
        /// </summary>
        /// <param name="hash"></param>
        /// <param name="sig"></param>
        /// <returns></returns>
        public bool RecoverCompact(UInt256 hash, ReadOnlyByteSpan sig)
        {
            var(ok, vch) = Secp256K1.PublicKeyRecoverCompact(hash.Span, sig);

            if (!ok)
            {
                Invalidate();
            }
            else
            {
                _bytes = vch;
            }

            return(ok);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Hash used to implement BIP 32 key derivations.
        /// </summary>
        /// <param name="chainCode"></param>
        /// <param name="nChild"></param>
        /// <param name="header"></param>
        /// <param name="data"></param>
        /// <param name="output">512 bit, 64 byte hash.</param>
        public static void Bip32Hash(UInt256 chainCode, uint nChild, byte header, ReadOnlyByteSpan data, ByteSpan output)
        {
            var len = data.Length;
            var buf = new byte[1 + len + 4]; // header, data, nChild
            var s   = buf.AsSpan();

            s[0] = header;
            data.CopyTo(s.Slice(1, len));
            var num = s.Slice(1 + len, 4);

            num[0] = (byte)((nChild >> 24) & 0xFF);
            num[1] = (byte)((nChild >> 16) & 0xFF);
            num[2] = (byte)((nChild >> 8) & 0xFF);
            // ReSharper disable once ShiftExpressionRealShiftCountIsZero
            num[3] = (byte)((nChild >> 0) & 0xFF);

            HmacSha512(chainCode.Span, s, output);
        }
Ejemplo n.º 25
0
        public Int64 set_vch(ReadOnlyByteSpan vch)
        {
            if (vch.Length == 0)
                return 0;

            Int64 result = 0;
            for (var i = 0; i < vch.Length; ++i)
                result |= ((Int64)vch[i]) << 8 * i;

            // If the input vector's most significant byte is 0x80, remove it from
            // the result's msb and return a negative.
            var last = vch.Length - 1;
            if ((vch[last] & 0x80) != 0) {
                return -((Int64)((UInt64)result & ~(0x80UL << (8 * last))));
            }

            return result;
        }
Ejemplo n.º 26
0
 public ExtPublicKey(ReadOnlyByteSpan code)
 {
     Decode(code);
 }
Ejemplo n.º 27
0
 public void Decode(ReadOnlyByteSpan code)
 {
     Depth       = code[0];
     Fingerprint = BitConverter.ToInt32(code[1..5]);
Ejemplo n.º 28
0
 public int BigEndianInt32(ReadOnlyByteSpan data) => BinaryPrimitives.ReadInt32BigEndian(data);
Ejemplo n.º 29
0
 public int LittleEndianInt32(ReadOnlyByteSpan data) => BinaryPrimitives.ReadInt32LittleEndian(data);
Ejemplo n.º 30
0
 public override string Encode(ReadOnlyByteSpan data)
 {
     return(BitConverter.IsLittleEndian
         ? System.Text.Encoding.Unicode.GetString(data)
         : System.Text.Encoding.BigEndianUnicode.GetString(data));
 }