コード例 #1
2
ファイル: SelfTest.cs プロジェクト: joshuadugie/KeePass-2.x
		private static void TestBlake2b()
		{
#if DEBUG
			Blake2b h = new Blake2b();

			// ======================================================
			// From https://tools.ietf.org/html/rfc7693

			byte[] pbData = StrUtil.Utf8.GetBytes("abc");
			byte[] pbExpc = new byte[64] {
				0xBA, 0x80, 0xA5, 0x3F, 0x98, 0x1C, 0x4D, 0x0D,
				0x6A, 0x27, 0x97, 0xB6, 0x9F, 0x12, 0xF6, 0xE9,
				0x4C, 0x21, 0x2F, 0x14, 0x68, 0x5A, 0xC4, 0xB7,
				0x4B, 0x12, 0xBB, 0x6F, 0xDB, 0xFF, 0xA2, 0xD1,
				0x7D, 0x87, 0xC5, 0x39, 0x2A, 0xAB, 0x79, 0x2D,
				0xC2, 0x52, 0xD5, 0xDE, 0x45, 0x33, 0xCC, 0x95,
				0x18, 0xD3, 0x8A, 0xA8, 0xDB, 0xF1, 0x92, 0x5A,
				0xB9, 0x23, 0x86, 0xED, 0xD4, 0x00, 0x99, 0x23
			};

			byte[] pbC = h.ComputeHash(pbData);
			if(!MemUtil.ArraysEqual(pbC, pbExpc))
				throw new SecurityException("Blake2b-1");

			// ======================================================
			// Computed using the official b2sum tool

			pbExpc = new byte[64] {
				0x78, 0x6A, 0x02, 0xF7, 0x42, 0x01, 0x59, 0x03,
				0xC6, 0xC6, 0xFD, 0x85, 0x25, 0x52, 0xD2, 0x72,
				0x91, 0x2F, 0x47, 0x40, 0xE1, 0x58, 0x47, 0x61,
				0x8A, 0x86, 0xE2, 0x17, 0xF7, 0x1F, 0x54, 0x19,
				0xD2, 0x5E, 0x10, 0x31, 0xAF, 0xEE, 0x58, 0x53,
				0x13, 0x89, 0x64, 0x44, 0x93, 0x4E, 0xB0, 0x4B,
				0x90, 0x3A, 0x68, 0x5B, 0x14, 0x48, 0xB7, 0x55,
				0xD5, 0x6F, 0x70, 0x1A, 0xFE, 0x9B, 0xE2, 0xCE
			};

			pbC = h.ComputeHash(MemUtil.EmptyByteArray);
			if(!MemUtil.ArraysEqual(pbC, pbExpc))
				throw new SecurityException("Blake2b-2");

			// ======================================================
			// Computed using the official b2sum tool

			string strS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.:,;_-\r\n";
			StringBuilder sb = new StringBuilder();
			for(int i = 0; i < 1000; ++i) sb.Append(strS);
			pbData = StrUtil.Utf8.GetBytes(sb.ToString());

			pbExpc = new byte[64] {
				0x59, 0x69, 0x8D, 0x3B, 0x83, 0xF4, 0x02, 0x4E,
				0xD8, 0x99, 0x26, 0x0E, 0xF4, 0xE5, 0x9F, 0x20,
				0xDC, 0x31, 0xEE, 0x5B, 0x45, 0xEA, 0xBB, 0xFC,
				0x1C, 0x0A, 0x8E, 0xED, 0xAA, 0x7A, 0xFF, 0x50,
				0x82, 0xA5, 0x8F, 0xBC, 0x4A, 0x46, 0xFC, 0xC5,
				0xEF, 0x44, 0x4E, 0x89, 0x80, 0x7D, 0x3F, 0x1C,
				0xC1, 0x94, 0x45, 0xBB, 0xC0, 0x2C, 0x95, 0xAA,
				0x3F, 0x08, 0x8A, 0x93, 0xF8, 0x75, 0x91, 0xB0
			};

			Random r = new Random();
			int p = 0;
			while(p < pbData.Length)
			{
				int cb = r.Next(1, pbData.Length - p + 1);
				h.TransformBlock(pbData, p, cb, pbData, p);
				p += cb;
			}
			Debug.Assert(p == pbData.Length);

			h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

			if(!MemUtil.ArraysEqual(h.Hash, pbExpc))
				throw new SecurityException("Blake2b-3");

			h.Clear();
#endif
		}
コード例 #2
0
ファイル: ConstantSchema.cs プロジェクト: dmirgaleev/netezos
        public static string GetGlobalAddress(IMicheline value)
        {
            var bytes = LocalForge.ForgeMicheline(value);
            var hash  = Blake2b.GetDigest(bytes);

            return(Base58.Convert(hash, Prefix.expr));
        }
コード例 #3
0
ファイル: KernelMap.cs プロジェクト: sandboxorg/PhotoSauce
            public static KernelMap <T> GetOrAdd(int isize, int osize, InterpolationSettings interpolator, int ichannels, double offset)
            {
                if (!(interpolator.WeightingFunction is IUniquelyIdentifiable iwf))
                {
                    return(KernelMap <T> .create(isize, osize, interpolator, ichannels, offset));
                }

                var hasher = Blake2b.CreateIncrementalHasher(Unsafe.SizeOf <Guid>());

                hasher.Update(isize);
                hasher.Update(osize);
                hasher.Update(ichannels);
                hasher.Update(offset);
                hasher.Update(iwf.UniqueID);
                hasher.Update(interpolator.Blur);

                Span <byte> hash = stackalloc byte[Unsafe.SizeOf <Guid>()];

                hasher.Finish(hash);
                var key = MemoryMarshal.Read <Guid>(hash);

                if (lruCache.TryGet(key, out var map))
                {
                    return(map);
                }

                return(lruCache.GetOrAdd(key, KernelMap <T> .create(isize, osize, interpolator, ichannels, offset)));
            }
コード例 #4
0
        /// <summary>Constructs a new <see cref="CubicInterpolator" /> with the specified <paramref name="b" /> and <paramref name="c" /> values.</summary>
        /// <param name="b">Controls the smoothness of the filter.  Larger values smooth/blur more.  Values &gt; 1.0 are not recommended.</param>
        /// <param name="c">Controls the sharpness of the filter.  Larger values sharpen more.  Values &gt; 1.0 are not recommended.</param>
        public CubicInterpolator(double b = 0.0, double c = 0.5)
        {
            if (b < 0.0)
            {
                throw new ArgumentOutOfRangeException(nameof(b), "Value must be greater than or equal to 0");
            }
            if (c < 0.0)
            {
                throw new ArgumentOutOfRangeException(nameof(c), "Value must be greater than or equal to 0");
            }

            support = b == 0.0 && c == 0.0 ? 1.0 : 2.0;

            p0 = (6.0 - 2.0 * b) / 6.0;
            p2 = (-18.0 + 12.0 * b + c * 6.0) / 6.0;
            p3 = (12.0 - 9.0 * b - c * 6.0) / 6.0;
            q0 = (8.0 * b + c * 24.0) / 6.0;
            q1 = (-12.0 * b - c * 48.0) / 6.0;
            q2 = (6.0 * b + c * 30.0) / 6.0;
            q3 = (-b - c * 6.0) / 6.0;

            displayString = $"{nameof(CubicInterpolator)}({b}, {c})";

            var hasher = Blake2b.CreateIncrementalHasher(Unsafe.SizeOf <Guid>());

            hasher.Update(fullName.AsSpan());
            hasher.Update(b);
            hasher.Update(c);
            uniqueID = hasher.FinalizeToGuid();
        }
コード例 #5
0
        /// <summary>
        /// Returns address from the given seed. Uses CPU for calculation.
        /// </summary>
        public static string TestCpu(byte[] seed)
        {
            byte[] secretBytes    = new byte[32];
            byte[] indexBytes     = new byte[4];
            byte[] publicKeyBytes = new byte[32];
            byte[] checksumBytes  = new byte[5];

            byte[] tmp = new byte[64];

            Job.AddressBuffer addressBuffer = new(Job.AddressPrefix.Length + 60);

            addressBuffer.Append(Job.AddressPrefix);

            var hasher = Blake2b.CreateIncrementalHasher(32);

            hasher.Update(seed);
            hasher.Update(indexBytes);
            hasher.Finish(secretBytes);

            Chaos.NaCl.Internal.Ed25519Ref10.Ed25519Operations.crypto_public_key(
                secretBytes, 0, publicKeyBytes, 0, tmp);

            Blake2b.ComputeAndWriteHash(5, publicKeyBytes, checksumBytes);
            Job.Reverse(checksumBytes);

            Job.NanoBase32(publicKeyBytes, ref addressBuffer);
            Job.NanoBase32(checksumBytes, ref addressBuffer);

            return(addressBuffer.ToString());
        }
コード例 #6
0
ファイル: Blind.cs プロジェクト: yepeek/tzkt
        public static string GetBlindedAddress(string address, string secret)
        {
            var pkh   = Base58.Parse(address).GetBytes(3, 20);
            var key   = Hex.Parse(secret);
            var blind = Blake2b.ComputeHash(20, key, pkh);

            return(Base58.Convert(blind, Prefix));
        }
コード例 #7
0
        public static void Properties()
        {
            var a = new Blake2b();

            Assert.Equal(32, a.MinHashSize);
            Assert.Equal(32, a.DefaultHashSize);
            Assert.Equal(64, a.MaxHashSize);
        }
コード例 #8
0
        public string GetKeyHash(IMicheline key)
        {
            var optimized = Key.Optimize(Micheline.FromBytes(key.ToBytes()));
            var packed = new byte[] { 5 }.Concat(LocalForge.ForgeMicheline(optimized));
            var hash = Blake2b.GetDigest(packed);

            return(Base58.Convert(hash, Prefix.expr));
        }
コード例 #9
0
ファイル: CacheHash.cs プロジェクト: carbon/PhotoSauce
        public static string Create(string data)
        {
            Span <byte> hash = stackalloc byte[DigestLength];

            Blake2b.ComputeAndWriteHash(DigestLength, MemoryMarshal.AsBytes(data.AsSpan()), hash);

            return(Encode(hash));
        }
コード例 #10
0
ファイル: Blake2bTests.cs プロジェクト: judgie79/nsec
        public static void HashWithSpanTooLarge()
        {
            var a = new Blake2b();

            using (var k = new Key(a))
            {
                Assert.Throws <ArgumentException>("hash", () => a.Hash(k, ReadOnlySpan <byte> .Empty, new byte[a.MaxHashSize + 1]));
            }
        }
コード例 #11
0
ファイル: Blake2bTests.cs プロジェクト: judgie79/nsec
        public static void HashWithWrongKey()
        {
            var a = new Blake2b();

            using (var k = new Key(new Ed25519()))
            {
                Assert.Throws <ArgumentException>("key", () => a.Hash(k, ReadOnlySpan <byte> .Empty));
            }
        }
コード例 #12
0
        public byte[] GetRawHash()
        {
            IHashAlgorithm hasher  = new Blake2b();
            Span <byte>    rawHash = stackalloc byte[32];

            hasher.Digest(GetEncodedRaw(), rawHash);

            return(rawHash.ToArray());
        }
コード例 #13
0
ファイル: Blake2bTests.cs プロジェクト: judgie79/nsec
        public static void HashWithMaxSpanSuccess()
        {
            var a = new Blake2b();

            using (var k = new Key(a))
            {
                a.Hash(k, ReadOnlySpan <byte> .Empty, new byte[a.MaxHashSize]);
            }
        }
コード例 #14
0
ファイル: Blake2bTests.cs プロジェクト: judgie79/nsec
        public static void KeyProperties()
        {
            var a = new Blake2b();

            Assert.True(a.MinKeySize >= 0);
            Assert.True(a.DefaultKeySize > 0);
            Assert.True(a.DefaultKeySize >= a.MinKeySize);
            Assert.True(a.MaxKeySize >= a.DefaultKeySize);
        }
コード例 #15
0
ファイル: Blake2bTests.cs プロジェクト: judgie79/nsec
        public static void HashWithSizeTooSmall()
        {
            var a = new Blake2b();

            using (var k = new Key(a))
            {
                Assert.Throws <ArgumentOutOfRangeException>("hashSize", () => a.Hash(k, ReadOnlySpan <byte> .Empty, a.MinHashSize - 1));
            }
        }
コード例 #16
0
        private Task <IFlurlResponse> FormRequest(string dest, long id, UpdatedManga manga, DatabaseUser user)
        {
            var hash = Convert.ToBase64String(Blake2b.ComputeHash(16,
                                                                  Encoding.UTF8.GetBytes($"{id}-{manga.Tome}-{manga.Number}")));
            var text =
                $"{manga.Date}: {manga.Name}.{Environment.NewLine}{manga.Tome} - {manga.Number}{Environment.NewLine}{manga.Href}";

            return(SendRequest(dest, hash, user.State, text, manga.Href.ToString()));
        }
コード例 #17
0
ファイル: Blake2bTests.cs プロジェクト: judgie79/nsec
        public static void Test(string msg, string hash)
        {
            var a = new Blake2b();

            var expected = hash.DecodeHex();
            var actual   = a.Hash(msg.DecodeHex(), expected.Length);

            Assert.Equal(expected, actual);
        }
コード例 #18
0
    public void Blake2b_Hash_Empty()
    {
        var hasher = new Blake2b();
        var hash   = new byte[64];

        hasher.Digest(Array.Empty <byte>(), hash);
        var result = hash.ToHexString();

        Assert.Equal("786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce", result);
    }
コード例 #19
0
            public static ColorProfile GetOrAdd(ReadOnlySpan <byte> bytes)
            {
                Span <byte> hash = stackalloc byte[Unsafe.SizeOf <Guid>()];

                Blake2b.ComputeAndWriteHash(Unsafe.SizeOf <Guid>(), bytes, hash);

                var guid = MemoryMarshal.Read <Guid>(hash);

                return((dic.TryGetValue(guid, out var wref) && wref.TryGetTarget(out var prof)) ? prof : addOrUpdate(guid, bytes));
            }
コード例 #20
0
    public void Blake2b_Hash()
    {
        var hasher = new Blake2b();
        var hash   = new byte[64];

        hasher.Digest(testValue2, hash);
        var result = hash.ToHexString();

        Assert.Equal("9cf604870022c048c8e05e701fd6718bfffdcf55d2c78264394cfced51964bc7cd9086133324d2c0ef637b8195ecee025889896b66f7418a83a910d853a00253", result);
    }
コード例 #21
0
        /// <summary>
        /// Helper to validate a BLAKE2 hash.
        /// </summary>
        /// <param name="data">Data to hash.</param>
        /// <param name="key">Key to hash.</param>
        /// <param name="expectedHash">Expected value.</param>
        private void CheckHash(byte[] data, byte[] key, byte[] expectedHash)
        {
            ulong[][] blocks = Blake2b.GetDataBlocks(data, key);
            byte[]    hash   = Blake2b.Hash(blocks, data.Length, (byte)key.Length, 64);

            for (int i = 0; i < 64; i++)
            {
                Assert.AreEqual(expectedHash[i], hash[i], $"hash byte #{i}");
            }
        }
コード例 #22
0
        public static string GetContractAddress(int index)
        {
            var hash = new byte[32]
            {
                72, 1, 189, 111, 8, 152, 13, 214, 38, 163, 228, 90, 249, 51, 127, 242,
                206, 198, 138, 55, 219, 134, 18, 158, 128, 96, 185, 73, 180, 9, 86, 229
            };
            var address = Blake2b.GetDigest(hash.Concat(GetBytes(index)).ToArray(), 160);

            return(Base58.Convert(address, new byte[] { 2, 90, 121 }));
        }
コード例 #23
0
        public Signature Sign(byte[] msg, byte[] prvKey)
        {
            var digest     = Blake2b.GetDigest(msg);
            var privateKey = new Ed25519PrivateKeyParameters(prvKey, 0);
            var signer     = new Ed25519Signer();

            signer.Init(true, privateKey);
            signer.BlockUpdate(digest, 0, digest.Length);

            return(new Signature(signer.GenerateSignature(), _SignaturePrefix));
        }
コード例 #24
0
        public async Task SendOk(long state)
        {
            const string content = "Everything's ok :)";

            await SendRequest(_config.Services.Tanser.Send,
                              Convert.ToBase64String(
                                  Blake2b.ComputeHash(16, Encoding.UTF8.GetBytes($"{state}-{content}"))
                                  ),
                              state,
                              content, null);
        }
コード例 #25
0
        public bool Verify(byte[] msg, byte[] sig, byte[] pubKey)
        {
            var keyedHash = Blake2b.GetDigest(msg);
            var publicKey = new Ed25519PublicKeyParameters(pubKey, 0);
            var verifier  = new Ed25519Signer();

            verifier.Init(false, publicKey);
            verifier.BlockUpdate(keyedHash, 0, keyedHash.Length);

            return(verifier.VerifySignature(sig));
        }
コード例 #26
0
ファイル: Blake2bTests.cs プロジェクト: judgie79/nsec
        public static void HashWithMaxSizeSuccess()
        {
            var a = new Blake2b();

            using (var k = new Key(a))
            {
                var b = a.Hash(k, ReadOnlySpan <byte> .Empty, a.MaxHashSize);

                Assert.NotNull(b);
                Assert.Equal(a.MaxHashSize, b.Length);
            }
        }
コード例 #27
0
ファイル: ColorProfile.cs プロジェクト: carbon/PhotoSauce
            public static ColorProfile GetOrAdd(ReadOnlySpan <byte> bytes)
            {
#if BUILTIN_SPAN
                Span <byte> hash = stackalloc byte[16];
                Blake2b.ComputeAndWriteHash(16, bytes, hash);
#else
                var hash = Blake2b.ComputeHash(16, bytes);
#endif

                var guid = new Guid(hash);
                return((dic.TryGetValue(guid, out var wref) && wref.TryGetTarget(out var prof)) ? prof : addOrUpdate(guid, bytes));
            }
コード例 #28
0
        public string CalculateIDWithUnsigned(string origin)
        {
            if (!SimpleWallet.IsValidAddress(origin))
            {
                throw new ArgumentException("origin expected address");
            }
            byte[]       signingHash = this.SigningHash();
            MemoryStream stream      = new MemoryStream();

            stream.Append(signingHash);
            stream.Append(origin.ToBytes());
            return(Blake2b.CalculateHash(stream.ToArray()).ToHexString());
        }
コード例 #29
0
ファイル: Blake2bTests.cs プロジェクト: xxponline/nsec
        public static void Properties()
        {
            var a = new Blake2b();

            Assert.Equal(32, Blake2b.MinHashSize);
            Assert.Equal(64, Blake2b.MaxHashSize);

            Assert.Equal(32, a.HashSize);

            Assert.Equal(32, HashAlgorithm.Blake2b_256.HashSize);

            Assert.Equal(64, HashAlgorithm.Blake2b_512.HashSize);
        }
コード例 #30
0
        /// <summary>
        /// Gets a hash of the current value stored in the session. Can be used to check if the value has changed since this method was last called.
        /// </summary>
        /// <param name="session">The ISession in which the value is stored.</param>
        /// <param name="key">The key the value is stored against for the session.</param>
        /// <returns>
        /// A hash of the current session key's value. This will change dramatically if any of the key's value changes.
        /// </returns>
        public static byte[] GetValueHash(this ISession session, string key)
        {
            var valueString = session.GetString(key);

            if (String.IsNullOrWhiteSpace(valueString))
            {
                return(null);
            }
            var valueBytes = Encoding.UTF8.GetBytes(valueString);

            byte[] computedHash = Blake2b.ComputeHash(valueBytes);
            return(computedHash);
        }
コード例 #31
0
        public override bool Verify(byte[] msg, byte[] sig, byte[] pubKey)
        {
            var digest = Blake2b.GetDigest(msg);
            var r      = sig.GetBytes(0, 32);
            var s      = sig.GetBytes(32, 32);

            var curve      = SecNamedCurves.GetByName("secp256k1");
            var parameters = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());
            var publicKey  = new ECPublicKeyParameters(curve.Curve.DecodePoint(pubKey), parameters);
            var signer     = new ECDsaSigner();

            signer.Init(false, publicKey);
            return(signer.VerifySignature(digest, new BigInteger(1, r), new BigInteger(1, s)));
        }
コード例 #32
0
		private static void Blake2bLong(byte[] pbOut, int cbOut,
			byte[] pbIn, int cbIn, Blake2b h)
		{
			Debug.Assert((h != null) && (h.HashSize == (64 * 8)));

			byte[] pbOutLen = new byte[4];
			MemUtil.UInt32ToBytesEx((uint)cbOut, pbOutLen, 0);

			if(cbOut <= 64)
			{
				Blake2b hOut = ((cbOut == 64) ? h : new Blake2b(cbOut));
				if(cbOut == 64) hOut.Initialize();

				hOut.TransformBlock(pbOutLen, 0, pbOutLen.Length, pbOutLen, 0);
				hOut.TransformBlock(pbIn, 0, cbIn, pbIn, 0);
				hOut.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

				Array.Copy(hOut.Hash, pbOut, cbOut);

				if(cbOut < 64) hOut.Clear();
				return;
			}

			h.Initialize();
			h.TransformBlock(pbOutLen, 0, pbOutLen.Length, pbOutLen, 0);
			h.TransformBlock(pbIn, 0, cbIn, pbIn, 0);
			h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

			byte[] pbOutBuffer = new byte[64];
			Array.Copy(h.Hash, pbOutBuffer, pbOutBuffer.Length);

			int ibOut = 64 / 2;
			Array.Copy(pbOutBuffer, pbOut, ibOut);
			int cbToProduce = cbOut - ibOut;

			h.Initialize();
			while(cbToProduce > 64)
			{
				byte[] pbHash = h.ComputeHash(pbOutBuffer);
				Array.Copy(pbHash, pbOutBuffer, 64);

				Array.Copy(pbHash, 0, pbOut, ibOut, 64 / 2);
				ibOut += 64 / 2;
				cbToProduce -= 64 / 2;

				MemUtil.ZeroByteArray(pbHash);
			}

			using(Blake2b hOut = new Blake2b(cbToProduce))
			{
				byte[] pbHash = hOut.ComputeHash(pbOutBuffer);
				Array.Copy(pbHash, 0, pbOut, ibOut, cbToProduce);

				MemUtil.ZeroByteArray(pbHash);
			}

			MemUtil.ZeroByteArray(pbOutBuffer);
		}
コード例 #33
0
		private static void FillFirstBlocks(Argon2Ctx ctx, byte[] pbBlockHash,
			Blake2b h)
		{
			byte[] pbBlock = new byte[NbBlockSize];

			for(ulong l = 0; l < ctx.Lanes; ++l)
			{
				MemUtil.UInt32ToBytesEx(0, pbBlockHash, NbPreHashDigestLength);
				MemUtil.UInt32ToBytesEx((uint)l, pbBlockHash, NbPreHashDigestLength + 4);

				Blake2bLong(pbBlock, (int)NbBlockSize, pbBlockHash,
					NbPreHashSeedLength, h);
				LoadBlock(ctx.Mem, l * ctx.LaneLength * NbBlockSizeInQW, pbBlock);

				MemUtil.UInt32ToBytesEx(1, pbBlockHash, NbPreHashDigestLength);

				Blake2bLong(pbBlock, (int)NbBlockSize, pbBlockHash,
					NbPreHashSeedLength, h);
				LoadBlock(ctx.Mem, (l * ctx.LaneLength + 1UL) * NbBlockSizeInQW, pbBlock);
			}

			MemUtil.ZeroByteArray(pbBlock);
		}
コード例 #34
0
		private static byte[] FinalHash(Argon2Ctx ctx, int cbOut, Blake2b h)
		{
			ulong[] pqBlockHash = new ulong[NbBlockSizeInQW];
			CopyBlock(pqBlockHash, 0, ctx.Mem, (ctx.LaneLength - 1UL) *
				NbBlockSizeInQW);
			for(ulong l = 1; l < ctx.Lanes; ++l)
				XorBlock(pqBlockHash, 0, ctx.Mem, (l * ctx.LaneLength +
					ctx.LaneLength - 1UL) * NbBlockSizeInQW);

			byte[] pbBlockHashBytes = new byte[NbBlockSize];
			StoreBlock(pbBlockHashBytes, pqBlockHash);

			byte[] pbOut = new byte[cbOut];
			Blake2bLong(pbOut, cbOut, pbBlockHashBytes, (int)NbBlockSize, h);

			MemUtil.ZeroArray<ulong>(pqBlockHash);
			MemUtil.ZeroByteArray(pbBlockHashBytes);
			return pbOut;
		}
コード例 #35
0
		private static byte[] Argon2d(byte[] pbMsg, byte[] pbSalt, uint uParallel,
			ulong uMem, ulong uIt, int cbOut, uint uVersion, byte[] pbSecretKey,
			byte[] pbAssocData)
		{
			pbSecretKey = (pbSecretKey ?? MemUtil.EmptyByteArray);
			pbAssocData = (pbAssocData ?? MemUtil.EmptyByteArray);

#if ARGON2_B2ROUND_ARRAYS
			InitB2RoundIndexArrays();
#endif

			Argon2Ctx ctx = new Argon2Ctx();
			ctx.Version = uVersion;

			ctx.Lanes = uParallel;
			ctx.TCost = uIt;
			ctx.MCost = uMem / NbBlockSize;
			ctx.MemoryBlocks = Math.Max(ctx.MCost, 2UL * NbSyncPoints * ctx.Lanes);

			ctx.SegmentLength = ctx.MemoryBlocks / (ctx.Lanes * NbSyncPoints);
			ctx.MemoryBlocks = ctx.SegmentLength * ctx.Lanes * NbSyncPoints;

			ctx.LaneLength = ctx.SegmentLength * NbSyncPoints;

			Debug.Assert(NbBlockSize == (NbBlockSizeInQW *
#if KeePassUAP
				(ulong)Marshal.SizeOf<ulong>()
#else
				(ulong)Marshal.SizeOf(typeof(ulong))
#endif
				));
			ctx.Mem = new ulong[ctx.MemoryBlocks * NbBlockSizeInQW];

			Blake2b h = new Blake2b();

			// Initial hash
			Debug.Assert(h.HashSize == (NbPreHashDigestLength * 8));
			byte[] pbBuf = new byte[4];
			MemUtil.UInt32ToBytesEx(uParallel, pbBuf, 0);
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			MemUtil.UInt32ToBytesEx((uint)cbOut, pbBuf, 0);
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			MemUtil.UInt32ToBytesEx((uint)ctx.MCost, pbBuf, 0);
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			MemUtil.UInt32ToBytesEx((uint)uIt, pbBuf, 0);
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			MemUtil.UInt32ToBytesEx(uVersion, pbBuf, 0);
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			MemUtil.UInt32ToBytesEx(0, pbBuf, 0); // Argon2d type = 0
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			MemUtil.UInt32ToBytesEx((uint)pbMsg.Length, pbBuf, 0);
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			h.TransformBlock(pbMsg, 0, pbMsg.Length, pbMsg, 0);
			MemUtil.UInt32ToBytesEx((uint)pbSalt.Length, pbBuf, 0);
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			h.TransformBlock(pbSalt, 0, pbSalt.Length, pbSalt, 0);
			MemUtil.UInt32ToBytesEx((uint)pbSecretKey.Length, pbBuf, 0);
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			h.TransformBlock(pbSecretKey, 0, pbSecretKey.Length, pbSecretKey, 0);
			MemUtil.UInt32ToBytesEx((uint)pbAssocData.Length, pbBuf, 0);
			h.TransformBlock(pbBuf, 0, pbBuf.Length, pbBuf, 0);
			h.TransformBlock(pbAssocData, 0, pbAssocData.Length, pbAssocData, 0);
			h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);
			byte[] pbH0 = h.Hash;
			Debug.Assert(pbH0.Length == 64);

			byte[] pbBlockHash = new byte[NbPreHashSeedLength];
			Array.Copy(pbH0, pbBlockHash, pbH0.Length);
			MemUtil.ZeroByteArray(pbH0);

			FillFirstBlocks(ctx, pbBlockHash, h);
			MemUtil.ZeroByteArray(pbBlockHash);

			FillMemoryBlocks(ctx);

			byte[] pbOut = FinalHash(ctx, cbOut, h);

			h.Clear();
			MemUtil.ZeroArray<ulong>(ctx.Mem);
			return pbOut;
		}