mirror of
https://github.com/wismna/ModernKeePassLib.git
synced 2025-10-04 08:00:18 -04:00
Setup solution
This commit is contained in:
399
ModernKeePassLib/Cryptography/KeyDerivation/AesKdf.GCrypt.cs
Normal file
399
ModernKeePassLib/Cryptography/KeyDerivation/AesKdf.GCrypt.cs
Normal file
@@ -0,0 +1,399 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
using ModernKeePassLib.Native;
|
||||
using ModernKeePassLib.Utility;
|
||||
|
||||
namespace ModernKeePassLib.Cryptography.KeyDerivation
|
||||
{
|
||||
public sealed partial class AesKdf : KdfEngine
|
||||
{
|
||||
private static bool TransformKeyGCrypt(byte[] pbData32, byte[] pbSeed32,
|
||||
ulong uRounds)
|
||||
{
|
||||
byte[] pbNewData32 = null;
|
||||
try
|
||||
{
|
||||
if(GCryptInitLib())
|
||||
{
|
||||
pbNewData32 = new byte[32];
|
||||
Array.Copy(pbData32, pbNewData32, 32);
|
||||
|
||||
if(TransformKeyGCryptPriv(pbNewData32, pbSeed32, uRounds))
|
||||
{
|
||||
Array.Copy(pbNewData32, pbData32, 32);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch(Exception) { }
|
||||
finally { if(pbNewData32 != null) MemUtil.ZeroByteArray(pbNewData32); }
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TransformKeyBenchmarkGCrypt(uint uTimeMs, out ulong uRounds)
|
||||
{
|
||||
uRounds = 0;
|
||||
|
||||
try
|
||||
{
|
||||
if(GCryptInitLib())
|
||||
return TransformKeyBenchmarkGCryptPriv(uTimeMs, ref uRounds);
|
||||
}
|
||||
catch(Exception) { }
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool GCryptInitLib()
|
||||
{
|
||||
if(!NativeLib.IsUnix()) return false; // Independent of workaround state
|
||||
if(!MonoWorkarounds.IsRequired(1468)) return false; // Can be turned off
|
||||
|
||||
// gcry_check_version initializes the library;
|
||||
// throws when LibGCrypt is not available
|
||||
NativeMethods.gcry_check_version(IntPtr.Zero);
|
||||
return true;
|
||||
}
|
||||
|
||||
// =============================================================
|
||||
// Multi-threaded implementation
|
||||
|
||||
// For some reason, the following multi-threaded implementation
|
||||
// is slower than the single-threaded implementation below
|
||||
// (threading overhead by Mono? LibGCrypt threading issues?)
|
||||
/* private sealed class GCryptTransformInfo : IDisposable
|
||||
{
|
||||
public IntPtr Data16;
|
||||
public IntPtr Seed32;
|
||||
public ulong Rounds;
|
||||
public uint TimeMs;
|
||||
|
||||
public bool Success = false;
|
||||
|
||||
public GCryptTransformInfo(byte[] pbData32, int iDataOffset,
|
||||
byte[] pbSeed32, ulong uRounds, uint uTimeMs)
|
||||
{
|
||||
this.Data16 = Marshal.AllocCoTaskMem(16);
|
||||
Marshal.Copy(pbData32, iDataOffset, this.Data16, 16);
|
||||
|
||||
this.Seed32 = Marshal.AllocCoTaskMem(32);
|
||||
Marshal.Copy(pbSeed32, 0, this.Seed32, 32);
|
||||
|
||||
this.Rounds = uRounds;
|
||||
this.TimeMs = uTimeMs;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if(this.Data16 != IntPtr.Zero)
|
||||
{
|
||||
Marshal.WriteInt64(this.Data16, 0);
|
||||
Marshal.WriteInt64(this.Data16, 8, 0);
|
||||
Marshal.FreeCoTaskMem(this.Data16);
|
||||
this.Data16 = IntPtr.Zero;
|
||||
}
|
||||
|
||||
if(this.Seed32 != IntPtr.Zero)
|
||||
{
|
||||
Marshal.FreeCoTaskMem(this.Seed32);
|
||||
this.Seed32 = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static GCryptTransformInfo[] GCryptRun(byte[] pbData32,
|
||||
byte[] pbSeed32, ulong uRounds, uint uTimeMs, ParameterizedThreadStart fL,
|
||||
ParameterizedThreadStart fR)
|
||||
{
|
||||
GCryptTransformInfo tiL = new GCryptTransformInfo(pbData32, 0,
|
||||
pbSeed32, uRounds, uTimeMs);
|
||||
GCryptTransformInfo tiR = new GCryptTransformInfo(pbData32, 16,
|
||||
pbSeed32, uRounds, uTimeMs);
|
||||
|
||||
Thread th = new Thread(fL);
|
||||
th.Start(tiL);
|
||||
|
||||
fR(tiR);
|
||||
|
||||
th.Join();
|
||||
|
||||
Marshal.Copy(tiL.Data16, pbData32, 0, 16);
|
||||
Marshal.Copy(tiR.Data16, pbData32, 16, 16);
|
||||
|
||||
tiL.Dispose();
|
||||
tiR.Dispose();
|
||||
|
||||
if(tiL.Success && tiR.Success)
|
||||
return new GCryptTransformInfo[2] { tiL, tiR };
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool TransformKeyGCryptPriv(byte[] pbData32, byte[] pbSeed32,
|
||||
ulong uRounds)
|
||||
{
|
||||
return (GCryptRun(pbData32, pbSeed32, uRounds, 0,
|
||||
new ParameterizedThreadStart(AesKdf.GCryptTransformTh),
|
||||
new ParameterizedThreadStart(AesKdf.GCryptTransformTh)) != null);
|
||||
}
|
||||
|
||||
private static bool GCryptInitCipher(ref IntPtr h, GCryptTransformInfo ti)
|
||||
{
|
||||
NativeMethods.gcry_cipher_open(ref h, NativeMethods.GCRY_CIPHER_AES256,
|
||||
NativeMethods.GCRY_CIPHER_MODE_ECB, 0);
|
||||
if(h == IntPtr.Zero) { Debug.Assert(false); return false; }
|
||||
|
||||
IntPtr n32 = new IntPtr(32);
|
||||
if(NativeMethods.gcry_cipher_setkey(h, ti.Seed32, n32) != 0)
|
||||
{
|
||||
Debug.Assert(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void GCryptTransformTh(object o)
|
||||
{
|
||||
IntPtr h = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
GCryptTransformInfo ti = (o as GCryptTransformInfo);
|
||||
if(ti == null) { Debug.Assert(false); return; }
|
||||
|
||||
if(!GCryptInitCipher(ref h, ti)) return;
|
||||
|
||||
IntPtr n16 = new IntPtr(16);
|
||||
for(ulong u = 0; u < ti.Rounds; ++u)
|
||||
{
|
||||
if(NativeMethods.gcry_cipher_encrypt(h, ti.Data16, n16,
|
||||
IntPtr.Zero, IntPtr.Zero) != 0)
|
||||
{
|
||||
Debug.Assert(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
ti.Success = true;
|
||||
}
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
finally
|
||||
{
|
||||
try { if(h != IntPtr.Zero) NativeMethods.gcry_cipher_close(h); }
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TransformKeyBenchmarkGCryptPriv(uint uTimeMs, ref ulong uRounds)
|
||||
{
|
||||
GCryptTransformInfo[] v = GCryptRun(new byte[32], new byte[32],
|
||||
0, uTimeMs,
|
||||
new ParameterizedThreadStart(AesKdf.GCryptBenchmarkTh),
|
||||
new ParameterizedThreadStart(AesKdf.GCryptBenchmarkTh));
|
||||
|
||||
if(v != null)
|
||||
{
|
||||
ulong uL = Math.Min(v[0].Rounds, ulong.MaxValue >> 1);
|
||||
ulong uR = Math.Min(v[1].Rounds, ulong.MaxValue >> 1);
|
||||
uRounds = (uL + uR) / 2;
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static void GCryptBenchmarkTh(object o)
|
||||
{
|
||||
IntPtr h = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
GCryptTransformInfo ti = (o as GCryptTransformInfo);
|
||||
if(ti == null) { Debug.Assert(false); return; }
|
||||
|
||||
if(!GCryptInitCipher(ref h, ti)) return;
|
||||
|
||||
ulong r = 0;
|
||||
IntPtr n16 = new IntPtr(16);
|
||||
int tStart = Environment.TickCount;
|
||||
while(true)
|
||||
{
|
||||
for(ulong j = 0; j < BenchStep; ++j)
|
||||
{
|
||||
if(NativeMethods.gcry_cipher_encrypt(h, ti.Data16, n16,
|
||||
IntPtr.Zero, IntPtr.Zero) != 0)
|
||||
{
|
||||
Debug.Assert(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
r += BenchStep;
|
||||
if(r < BenchStep) // Overflow check
|
||||
{
|
||||
r = ulong.MaxValue;
|
||||
break;
|
||||
}
|
||||
|
||||
uint tElapsed = (uint)(Environment.TickCount - tStart);
|
||||
if(tElapsed > ti.TimeMs) break;
|
||||
}
|
||||
|
||||
ti.Rounds = r;
|
||||
ti.Success = true;
|
||||
}
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
finally
|
||||
{
|
||||
try { if(h != IntPtr.Zero) NativeMethods.gcry_cipher_close(h); }
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
}
|
||||
} */
|
||||
|
||||
// =============================================================
|
||||
// Single-threaded implementation
|
||||
|
||||
private static bool GCryptInitCipher(ref IntPtr h, IntPtr pSeed32)
|
||||
{
|
||||
NativeMethods.gcry_cipher_open(ref h, NativeMethods.GCRY_CIPHER_AES256,
|
||||
NativeMethods.GCRY_CIPHER_MODE_ECB, 0);
|
||||
if(h == IntPtr.Zero) { Debug.Assert(false); return false; }
|
||||
|
||||
IntPtr n32 = new IntPtr(32);
|
||||
if(NativeMethods.gcry_cipher_setkey(h, pSeed32, n32) != 0)
|
||||
{
|
||||
Debug.Assert(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool GCryptBegin(byte[] pbData32, byte[] pbSeed32,
|
||||
ref IntPtr h, ref IntPtr pData32, ref IntPtr pSeed32)
|
||||
{
|
||||
pData32 = Marshal.AllocCoTaskMem(32);
|
||||
pSeed32 = Marshal.AllocCoTaskMem(32);
|
||||
|
||||
Marshal.Copy(pbData32, 0, pData32, 32);
|
||||
Marshal.Copy(pbSeed32, 0, pSeed32, 32);
|
||||
|
||||
return GCryptInitCipher(ref h, pSeed32);
|
||||
}
|
||||
|
||||
private static void GCryptEnd(IntPtr h, IntPtr pData32, IntPtr pSeed32)
|
||||
{
|
||||
NativeMethods.gcry_cipher_close(h);
|
||||
|
||||
Marshal.WriteInt64(pData32, 0);
|
||||
Marshal.WriteInt64(pData32, 8, 0);
|
||||
Marshal.WriteInt64(pData32, 16, 0);
|
||||
Marshal.WriteInt64(pData32, 24, 0);
|
||||
|
||||
Marshal.FreeCoTaskMem(pData32);
|
||||
Marshal.FreeCoTaskMem(pSeed32);
|
||||
}
|
||||
|
||||
private static bool TransformKeyGCryptPriv(byte[] pbData32, byte[] pbSeed32,
|
||||
ulong uRounds)
|
||||
{
|
||||
IntPtr h = IntPtr.Zero, pData32 = IntPtr.Zero, pSeed32 = IntPtr.Zero;
|
||||
if(!GCryptBegin(pbData32, pbSeed32, ref h, ref pData32, ref pSeed32))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
IntPtr n32 = new IntPtr(32);
|
||||
for(ulong i = 0; i < uRounds; ++i)
|
||||
{
|
||||
if(NativeMethods.gcry_cipher_encrypt(h, pData32, n32,
|
||||
IntPtr.Zero, IntPtr.Zero) != 0)
|
||||
{
|
||||
Debug.Assert(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Marshal.Copy(pData32, pbData32, 0, 32);
|
||||
return true;
|
||||
}
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
finally { GCryptEnd(h, pData32, pSeed32); }
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TransformKeyBenchmarkGCryptPriv(uint uTimeMs, ref ulong uRounds)
|
||||
{
|
||||
byte[] pbData32 = new byte[32];
|
||||
byte[] pbSeed32 = new byte[32];
|
||||
|
||||
IntPtr h = IntPtr.Zero, pData32 = IntPtr.Zero, pSeed32 = IntPtr.Zero;
|
||||
if(!GCryptBegin(pbData32, pbSeed32, ref h, ref pData32, ref pSeed32))
|
||||
return false;
|
||||
|
||||
uint uMaxMs = uTimeMs;
|
||||
ulong uDiv = 1;
|
||||
if(uMaxMs <= (uint.MaxValue >> 1)) { uMaxMs *= 2U; uDiv = 2; }
|
||||
|
||||
try
|
||||
{
|
||||
ulong r = 0;
|
||||
IntPtr n32 = new IntPtr(32);
|
||||
int tStart = Environment.TickCount;
|
||||
while(true)
|
||||
{
|
||||
for(ulong j = 0; j < BenchStep; ++j)
|
||||
{
|
||||
if(NativeMethods.gcry_cipher_encrypt(h, pData32, n32,
|
||||
IntPtr.Zero, IntPtr.Zero) != 0)
|
||||
{
|
||||
Debug.Assert(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
r += BenchStep;
|
||||
if(r < BenchStep) // Overflow check
|
||||
{
|
||||
r = ulong.MaxValue;
|
||||
break;
|
||||
}
|
||||
|
||||
uint tElapsed = (uint)(Environment.TickCount - tStart);
|
||||
if(tElapsed > uMaxMs) break;
|
||||
}
|
||||
|
||||
uRounds = r / uDiv;
|
||||
return true;
|
||||
}
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
finally { GCryptEnd(h, pData32, pSeed32); }
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
281
ModernKeePassLib/Cryptography/KeyDerivation/AesKdf.cs
Normal file
281
ModernKeePassLib/Cryptography/KeyDerivation/AesKdf.cs
Normal file
@@ -0,0 +1,281 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
#if KeePassUAP
|
||||
using Org.BouncyCastle.Crypto;
|
||||
using Org.BouncyCastle.Crypto.Engines;
|
||||
using Org.BouncyCastle.Crypto.Parameters;
|
||||
#else
|
||||
using System.Security.Cryptography;
|
||||
#endif
|
||||
|
||||
using ModernKeePassLib.Cryptography;
|
||||
using ModernKeePassLib.Native;
|
||||
using ModernKeePassLib.Utility;
|
||||
|
||||
namespace ModernKeePassLib.Cryptography.KeyDerivation
|
||||
{
|
||||
public sealed partial class AesKdf : KdfEngine
|
||||
{
|
||||
private static readonly PwUuid g_uuid = new PwUuid(new byte[] {
|
||||
0xC9, 0xD9, 0xF3, 0x9A, 0x62, 0x8A, 0x44, 0x60,
|
||||
0xBF, 0x74, 0x0D, 0x08, 0xC1, 0x8A, 0x4F, 0xEA });
|
||||
|
||||
public static readonly string ParamRounds = "R"; // UInt64
|
||||
public static readonly string ParamSeed = "S"; // Byte[32]
|
||||
|
||||
private const ulong BenchStep = 3001;
|
||||
|
||||
public override PwUuid Uuid
|
||||
{
|
||||
get { return g_uuid; }
|
||||
}
|
||||
|
||||
public override string Name
|
||||
{
|
||||
get { return "AES-KDF"; }
|
||||
}
|
||||
|
||||
public AesKdf()
|
||||
{
|
||||
}
|
||||
|
||||
public override KdfParameters GetDefaultParameters()
|
||||
{
|
||||
KdfParameters p = base.GetDefaultParameters();
|
||||
p.SetUInt64(ParamRounds, PwDefs.DefaultKeyEncryptionRounds);
|
||||
return p;
|
||||
}
|
||||
|
||||
public override void Randomize(KdfParameters p)
|
||||
{
|
||||
if(p == null) { Debug.Assert(false); return; }
|
||||
Debug.Assert(g_uuid.Equals(p.KdfUuid));
|
||||
|
||||
byte[] pbSeed = CryptoRandom.Instance.GetRandomBytes(32);
|
||||
p.SetByteArray(ParamSeed, pbSeed);
|
||||
}
|
||||
|
||||
public override byte[] Transform(byte[] pbMsg, KdfParameters p)
|
||||
{
|
||||
if(pbMsg == null) throw new ArgumentNullException("pbMsg");
|
||||
if(p == null) throw new ArgumentNullException("p");
|
||||
|
||||
Type tRounds = p.GetTypeOf(ParamRounds);
|
||||
if(tRounds == null) throw new ArgumentNullException("p.Rounds");
|
||||
if(tRounds != typeof(ulong)) throw new ArgumentOutOfRangeException("p.Rounds");
|
||||
ulong uRounds = p.GetUInt64(ParamRounds, 0);
|
||||
|
||||
byte[] pbSeed = p.GetByteArray(ParamSeed);
|
||||
if(pbSeed == null) throw new ArgumentNullException("p.Seed");
|
||||
|
||||
if(pbMsg.Length != 32)
|
||||
{
|
||||
Debug.Assert(false);
|
||||
pbMsg = CryptoUtil.HashSha256(pbMsg);
|
||||
}
|
||||
|
||||
if(pbSeed.Length != 32)
|
||||
{
|
||||
Debug.Assert(false);
|
||||
pbSeed = CryptoUtil.HashSha256(pbSeed);
|
||||
}
|
||||
|
||||
return TransformKey(pbMsg, pbSeed, uRounds);
|
||||
}
|
||||
|
||||
private static byte[] TransformKey(byte[] pbOriginalKey32, byte[] pbKeySeed32,
|
||||
ulong uNumRounds)
|
||||
{
|
||||
Debug.Assert((pbOriginalKey32 != null) && (pbOriginalKey32.Length == 32));
|
||||
if(pbOriginalKey32 == null) throw new ArgumentNullException("pbOriginalKey32");
|
||||
if(pbOriginalKey32.Length != 32) throw new ArgumentException();
|
||||
|
||||
Debug.Assert((pbKeySeed32 != null) && (pbKeySeed32.Length == 32));
|
||||
if(pbKeySeed32 == null) throw new ArgumentNullException("pbKeySeed32");
|
||||
if(pbKeySeed32.Length != 32) throw new ArgumentException();
|
||||
|
||||
byte[] pbNewKey = new byte[32];
|
||||
Array.Copy(pbOriginalKey32, pbNewKey, pbNewKey.Length);
|
||||
|
||||
try
|
||||
{
|
||||
#if !ModernKeePassLib
|
||||
if(NativeLib.TransformKey256(pbNewKey, pbKeySeed32, uNumRounds))
|
||||
return CryptoUtil.HashSha256(pbNewKey);
|
||||
#endif
|
||||
|
||||
if(TransformKeyGCrypt(pbNewKey, pbKeySeed32, uNumRounds))
|
||||
return CryptoUtil.HashSha256(pbNewKey);
|
||||
|
||||
if(TransformKeyManaged(pbNewKey, pbKeySeed32, uNumRounds))
|
||||
return CryptoUtil.HashSha256(pbNewKey);
|
||||
}
|
||||
finally { MemUtil.ZeroByteArray(pbNewKey); }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static bool TransformKeyManaged(byte[] pbNewKey32, byte[] pbKeySeed32,
|
||||
ulong uNumRounds)
|
||||
{
|
||||
#if KeePassUAP
|
||||
KeyParameter kp = new KeyParameter(pbKeySeed32);
|
||||
AesEngine aes = new AesEngine();
|
||||
aes.Init(true, kp);
|
||||
|
||||
for(ulong u = 0; u < uNumRounds; ++u)
|
||||
{
|
||||
aes.ProcessBlock(pbNewKey32, 0, pbNewKey32, 0);
|
||||
aes.ProcessBlock(pbNewKey32, 16, pbNewKey32, 16);
|
||||
}
|
||||
|
||||
aes.Reset();
|
||||
#else
|
||||
byte[] pbIV = new byte[16];
|
||||
|
||||
using(SymmetricAlgorithm a = CryptoUtil.CreateAes())
|
||||
{
|
||||
if(a.BlockSize != 128) // AES block size
|
||||
{
|
||||
Debug.Assert(false);
|
||||
a.BlockSize = 128;
|
||||
}
|
||||
a.KeySize = 256;
|
||||
a.Mode = CipherMode.ECB;
|
||||
|
||||
using(ICryptoTransform t = a.CreateEncryptor(pbKeySeed32, pbIV))
|
||||
{
|
||||
// !t.CanReuseTransform -- doesn't work with Mono
|
||||
if((t == null) || (t.InputBlockSize != 16) ||
|
||||
(t.OutputBlockSize != 16))
|
||||
{
|
||||
Debug.Assert(false);
|
||||
return false;
|
||||
}
|
||||
|
||||
for(ulong u = 0; u < uNumRounds; ++u)
|
||||
{
|
||||
t.TransformBlock(pbNewKey32, 0, 16, pbNewKey32, 0);
|
||||
t.TransformBlock(pbNewKey32, 16, 16, pbNewKey32, 16);
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public override KdfParameters GetBestParameters(uint uMilliseconds)
|
||||
{
|
||||
KdfParameters p = GetDefaultParameters();
|
||||
ulong uRounds;
|
||||
#if !ModernKeePassLib
|
||||
// Try native method
|
||||
if(NativeLib.TransformKeyBenchmark256(uMilliseconds, out uRounds))
|
||||
{
|
||||
p.SetUInt64(ParamRounds, uRounds);
|
||||
return p;
|
||||
}
|
||||
#endif
|
||||
if(TransformKeyBenchmarkGCrypt(uMilliseconds, out uRounds))
|
||||
{
|
||||
p.SetUInt64(ParamRounds, uRounds);
|
||||
return p;
|
||||
}
|
||||
|
||||
byte[] pbKey = new byte[32];
|
||||
byte[] pbNewKey = new byte[32];
|
||||
for(int i = 0; i < pbKey.Length; ++i)
|
||||
{
|
||||
pbKey[i] = (byte)i;
|
||||
pbNewKey[i] = (byte)i;
|
||||
}
|
||||
|
||||
#if KeePassUAP
|
||||
KeyParameter kp = new KeyParameter(pbKey);
|
||||
AesEngine aes = new AesEngine();
|
||||
aes.Init(true, kp);
|
||||
#else
|
||||
byte[] pbIV = new byte[16];
|
||||
|
||||
using(SymmetricAlgorithm a = CryptoUtil.CreateAes())
|
||||
{
|
||||
if(a.BlockSize != 128) // AES block size
|
||||
{
|
||||
Debug.Assert(false);
|
||||
a.BlockSize = 128;
|
||||
}
|
||||
a.KeySize = 256;
|
||||
a.Mode = CipherMode.ECB;
|
||||
|
||||
using(ICryptoTransform t = a.CreateEncryptor(pbKey, pbIV))
|
||||
{
|
||||
// !t.CanReuseTransform -- doesn't work with Mono
|
||||
if((t == null) || (t.InputBlockSize != 16) ||
|
||||
(t.OutputBlockSize != 16))
|
||||
{
|
||||
Debug.Assert(false);
|
||||
p.SetUInt64(ParamRounds, PwDefs.DefaultKeyEncryptionRounds);
|
||||
return p;
|
||||
}
|
||||
#endif
|
||||
|
||||
uRounds = 0;
|
||||
int tStart = Environment.TickCount;
|
||||
while(true)
|
||||
{
|
||||
for(ulong j = 0; j < BenchStep; ++j)
|
||||
{
|
||||
#if KeePassUAP
|
||||
aes.ProcessBlock(pbNewKey, 0, pbNewKey, 0);
|
||||
aes.ProcessBlock(pbNewKey, 16, pbNewKey, 16);
|
||||
#else
|
||||
t.TransformBlock(pbNewKey, 0, 16, pbNewKey, 0);
|
||||
t.TransformBlock(pbNewKey, 16, 16, pbNewKey, 16);
|
||||
#endif
|
||||
}
|
||||
|
||||
uRounds += BenchStep;
|
||||
if(uRounds < BenchStep) // Overflow check
|
||||
{
|
||||
uRounds = ulong.MaxValue;
|
||||
break;
|
||||
}
|
||||
|
||||
uint tElapsed = (uint)(Environment.TickCount - tStart);
|
||||
if(tElapsed > uMilliseconds) break;
|
||||
}
|
||||
|
||||
p.SetUInt64(ParamRounds, uRounds);
|
||||
#if KeePassUAP
|
||||
aes.Reset();
|
||||
#else
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
637
ModernKeePassLib/Cryptography/KeyDerivation/Argon2Kdf.Core.cs
Normal file
637
ModernKeePassLib/Cryptography/KeyDerivation/Argon2Kdf.Core.cs
Normal file
@@ -0,0 +1,637 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
// This implementation is based on the official reference C
|
||||
// implementation by Daniel Dinu and Dmitry Khovratovich (CC0 1.0).
|
||||
|
||||
// Relative iterations (* = B2ROUND_ARRAYS \\ G_INLINED):
|
||||
// * | false true
|
||||
// ------+-----------
|
||||
// false | 8885 9618
|
||||
// true | 9009 9636
|
||||
#define ARGON2_B2ROUND_ARRAYS
|
||||
#define ARGON2_G_INLINED
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ModernKeePassLib.Cryptography.Hash;
|
||||
using ModernKeePassLib.Utility;
|
||||
|
||||
namespace ModernKeePassLib.Cryptography.KeyDerivation
|
||||
{
|
||||
public sealed partial class Argon2Kdf : KdfEngine
|
||||
{
|
||||
private const ulong NbBlockSize = 1024;
|
||||
private const ulong NbBlockSizeInQW = NbBlockSize / 8UL;
|
||||
private const ulong NbSyncPoints = 4;
|
||||
|
||||
private const int NbPreHashDigestLength = 64;
|
||||
private const int NbPreHashSeedLength = NbPreHashDigestLength + 8;
|
||||
|
||||
#if ARGON2_B2ROUND_ARRAYS
|
||||
private static int[][] g_vFBCols = null;
|
||||
private static int[][] g_vFBRows = null;
|
||||
#endif
|
||||
|
||||
private sealed class Argon2Ctx
|
||||
{
|
||||
public uint Version = 0;
|
||||
|
||||
public ulong Lanes = 0;
|
||||
public ulong TCost = 0;
|
||||
public ulong MCost = 0;
|
||||
public ulong MemoryBlocks = 0;
|
||||
public ulong SegmentLength = 0;
|
||||
public ulong LaneLength = 0;
|
||||
|
||||
public ulong[] Mem = null;
|
||||
}
|
||||
|
||||
private sealed class Argon2ThreadInfo
|
||||
{
|
||||
public Argon2Ctx Context = null;
|
||||
public ManualResetEvent Finished = new ManualResetEvent(false);
|
||||
|
||||
public ulong Pass = 0;
|
||||
public ulong Lane = 0;
|
||||
public ulong Slice = 0;
|
||||
public ulong Index = 0;
|
||||
|
||||
public void Release()
|
||||
{
|
||||
if(this.Finished != null)
|
||||
{
|
||||
this.Finished.Dispose();
|
||||
this.Finished = null;
|
||||
}
|
||||
else { Debug.Assert(false); }
|
||||
}
|
||||
}
|
||||
|
||||
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 ModernKeePassLib || 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;
|
||||
}
|
||||
|
||||
private static void LoadBlock(ulong[] pqDst, ulong uDstOffset, byte[] pbIn)
|
||||
{
|
||||
// for(ulong i = 0; i < NbBlockSizeInQW; ++i)
|
||||
// pqDst[uDstOffset + i] = MemUtil.BytesToUInt64(pbIn, (int)(i << 3));
|
||||
|
||||
Debug.Assert((uDstOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue);
|
||||
int iDstOffset = (int)uDstOffset;
|
||||
for(int i = 0; i < (int)NbBlockSizeInQW; ++i)
|
||||
pqDst[iDstOffset + i] = MemUtil.BytesToUInt64(pbIn, i << 3);
|
||||
}
|
||||
|
||||
private static void StoreBlock(byte[] pbDst, ulong[] pqSrc)
|
||||
{
|
||||
for(int i = 0; i < (int)NbBlockSizeInQW; ++i)
|
||||
MemUtil.UInt64ToBytesEx(pqSrc[i], pbDst, i << 3);
|
||||
}
|
||||
|
||||
private static void CopyBlock(ulong[] vDst, ulong uDstOffset, ulong[] vSrc,
|
||||
ulong uSrcOffset)
|
||||
{
|
||||
// for(ulong i = 0; i < NbBlockSizeInQW; ++i)
|
||||
// vDst[uDstOffset + i] = vSrc[uSrcOffset + i];
|
||||
|
||||
// Debug.Assert((uDstOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue);
|
||||
// Debug.Assert((uSrcOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue);
|
||||
// int iDstOffset = (int)uDstOffset;
|
||||
// int iSrcOffset = (int)uSrcOffset;
|
||||
// for(int i = 0; i < (int)NbBlockSizeInQW; ++i)
|
||||
// vDst[iDstOffset + i] = vSrc[iSrcOffset + i];
|
||||
|
||||
#if ModernKeePassLib || KeePassUAP
|
||||
Array.Copy(vSrc, (int)uSrcOffset, vDst, (int)uDstOffset,
|
||||
(int)NbBlockSizeInQW);
|
||||
#else
|
||||
Array.Copy(vSrc, (long)uSrcOffset, vDst, (long)uDstOffset,
|
||||
(long)NbBlockSizeInQW);
|
||||
#endif
|
||||
}
|
||||
|
||||
private static void XorBlock(ulong[] vDst, ulong uDstOffset, ulong[] vSrc,
|
||||
ulong uSrcOffset)
|
||||
{
|
||||
// for(ulong i = 0; i < NbBlockSizeInQW; ++i)
|
||||
// vDst[uDstOffset + i] ^= vSrc[uSrcOffset + i];
|
||||
|
||||
Debug.Assert((uDstOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue);
|
||||
Debug.Assert((uSrcOffset + NbBlockSizeInQW - 1UL) <= (ulong)int.MaxValue);
|
||||
int iDstOffset = (int)uDstOffset;
|
||||
int iSrcOffset = (int)uSrcOffset;
|
||||
for(int i = 0; i < (int)NbBlockSizeInQW; ++i)
|
||||
vDst[iDstOffset + i] ^= vSrc[iSrcOffset + i];
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
#if !ARGON2_G_INLINED
|
||||
private static ulong BlaMka(ulong x, ulong y)
|
||||
{
|
||||
ulong xy = (x & 0xFFFFFFFFUL) * (y & 0xFFFFFFFFUL);
|
||||
return (x + y + (xy << 1));
|
||||
}
|
||||
|
||||
private static void G(ulong[] v, int a, int b, int c, int d)
|
||||
{
|
||||
ulong va = v[a], vb = v[b], vc = v[c], vd = v[d];
|
||||
|
||||
va = BlaMka(va, vb);
|
||||
vd = MemUtil.RotateRight64(vd ^ va, 32);
|
||||
vc = BlaMka(vc, vd);
|
||||
vb = MemUtil.RotateRight64(vb ^ vc, 24);
|
||||
va = BlaMka(va, vb);
|
||||
vd = MemUtil.RotateRight64(vd ^ va, 16);
|
||||
vc = BlaMka(vc, vd);
|
||||
vb = MemUtil.RotateRight64(vb ^ vc, 63);
|
||||
|
||||
v[a] = va;
|
||||
v[b] = vb;
|
||||
v[c] = vc;
|
||||
v[d] = vd;
|
||||
}
|
||||
#else
|
||||
private static void G(ulong[] v, int a, int b, int c, int d)
|
||||
{
|
||||
ulong va = v[a], vb = v[b], vc = v[c], vd = v[d];
|
||||
|
||||
ulong xy = (va & 0xFFFFFFFFUL) * (vb & 0xFFFFFFFFUL);
|
||||
va += vb + (xy << 1);
|
||||
|
||||
vd = MemUtil.RotateRight64(vd ^ va, 32);
|
||||
|
||||
xy = (vc & 0xFFFFFFFFUL) * (vd & 0xFFFFFFFFUL);
|
||||
vc += vd + (xy << 1);
|
||||
|
||||
vb = MemUtil.RotateRight64(vb ^ vc, 24);
|
||||
|
||||
xy = (va & 0xFFFFFFFFUL) * (vb & 0xFFFFFFFFUL);
|
||||
va += vb + (xy << 1);
|
||||
|
||||
vd = MemUtil.RotateRight64(vd ^ va, 16);
|
||||
|
||||
xy = (vc & 0xFFFFFFFFUL) * (vd & 0xFFFFFFFFUL);
|
||||
vc += vd + (xy << 1);
|
||||
|
||||
vb = MemUtil.RotateRight64(vb ^ vc, 63);
|
||||
|
||||
v[a] = va;
|
||||
v[b] = vb;
|
||||
v[c] = vc;
|
||||
v[d] = vd;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if ARGON2_B2ROUND_ARRAYS
|
||||
private static void Blake2RoundNoMsg(ulong[] pbR, int[] v)
|
||||
{
|
||||
G(pbR, v[0], v[4], v[8], v[12]);
|
||||
G(pbR, v[1], v[5], v[9], v[13]);
|
||||
G(pbR, v[2], v[6], v[10], v[14]);
|
||||
G(pbR, v[3], v[7], v[11], v[15]);
|
||||
G(pbR, v[0], v[5], v[10], v[15]);
|
||||
G(pbR, v[1], v[6], v[11], v[12]);
|
||||
G(pbR, v[2], v[7], v[8], v[13]);
|
||||
G(pbR, v[3], v[4], v[9], v[14]);
|
||||
}
|
||||
#else
|
||||
private static void Blake2RoundNoMsgCols16i(ulong[] pbR, int i)
|
||||
{
|
||||
G(pbR, i, i + 4, i + 8, i + 12);
|
||||
G(pbR, i + 1, i + 5, i + 9, i + 13);
|
||||
G(pbR, i + 2, i + 6, i + 10, i + 14);
|
||||
G(pbR, i + 3, i + 7, i + 11, i + 15);
|
||||
G(pbR, i, i + 5, i + 10, i + 15);
|
||||
G(pbR, i + 1, i + 6, i + 11, i + 12);
|
||||
G(pbR, i + 2, i + 7, i + 8, i + 13);
|
||||
G(pbR, i + 3, i + 4, i + 9, i + 14);
|
||||
}
|
||||
|
||||
private static void Blake2RoundNoMsgRows2i(ulong[] pbR, int i)
|
||||
{
|
||||
G(pbR, i, i + 32, i + 64, i + 96);
|
||||
G(pbR, i + 1, i + 33, i + 65, i + 97);
|
||||
G(pbR, i + 16, i + 48, i + 80, i + 112);
|
||||
G(pbR, i + 17, i + 49, i + 81, i + 113);
|
||||
G(pbR, i, i + 33, i + 80, i + 113);
|
||||
G(pbR, i + 1, i + 48, i + 81, i + 96);
|
||||
G(pbR, i + 16, i + 49, i + 64, i + 97);
|
||||
G(pbR, i + 17, i + 32, i + 65, i + 112);
|
||||
}
|
||||
#endif
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private static ulong IndexAlpha(Argon2Ctx ctx, Argon2ThreadInfo ti,
|
||||
uint uPseudoRand, bool bSameLane)
|
||||
{
|
||||
ulong uRefAreaSize;
|
||||
if(ti.Pass == 0)
|
||||
{
|
||||
if(ti.Slice == 0)
|
||||
{
|
||||
Debug.Assert(ti.Index > 0);
|
||||
uRefAreaSize = ti.Index - 1UL;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(bSameLane)
|
||||
uRefAreaSize = ti.Slice * ctx.SegmentLength +
|
||||
ti.Index - 1UL;
|
||||
else
|
||||
uRefAreaSize = ti.Slice * ctx.SegmentLength -
|
||||
((ti.Index == 0UL) ? 1UL : 0UL);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if(bSameLane)
|
||||
uRefAreaSize = ctx.LaneLength - ctx.SegmentLength +
|
||||
ti.Index - 1UL;
|
||||
else
|
||||
uRefAreaSize = ctx.LaneLength - ctx.SegmentLength -
|
||||
((ti.Index == 0) ? 1UL : 0UL);
|
||||
}
|
||||
Debug.Assert(uRefAreaSize <= (ulong)uint.MaxValue);
|
||||
|
||||
ulong uRelPos = uPseudoRand;
|
||||
uRelPos = (uRelPos * uRelPos) >> 32;
|
||||
uRelPos = uRefAreaSize - 1UL - ((uRefAreaSize * uRelPos) >> 32);
|
||||
|
||||
ulong uStart = 0;
|
||||
if(ti.Pass != 0)
|
||||
uStart = (((ti.Slice + 1UL) == NbSyncPoints) ? 0UL :
|
||||
((ti.Slice + 1UL) * ctx.SegmentLength));
|
||||
Debug.Assert(uStart <= (ulong)uint.MaxValue);
|
||||
|
||||
Debug.Assert(ctx.LaneLength <= (ulong)uint.MaxValue);
|
||||
return ((uStart + uRelPos) % ctx.LaneLength);
|
||||
}
|
||||
|
||||
private static void FillMemoryBlocks(Argon2Ctx ctx)
|
||||
{
|
||||
int np = (int)ctx.Lanes;
|
||||
Argon2ThreadInfo[] v = new Argon2ThreadInfo[np];
|
||||
|
||||
for(ulong r = 0; r < ctx.TCost; ++r)
|
||||
{
|
||||
for(ulong s = 0; s < NbSyncPoints; ++s)
|
||||
{
|
||||
for(int l = 0; l < np; ++l)
|
||||
{
|
||||
Argon2ThreadInfo ti = new Argon2ThreadInfo();
|
||||
ti.Context = ctx;
|
||||
|
||||
ti.Pass = r;
|
||||
ti.Lane = (ulong)l;
|
||||
ti.Slice = s;
|
||||
|
||||
#if ModernKeePassLib
|
||||
Task.Factory.StartNew(FillSegmentThr, ti);
|
||||
//ThreadPool.RunAsync(a => FillSegmentThr(ti));
|
||||
#else
|
||||
if(!ThreadPool.QueueUserWorkItem(FillSegmentThr, ti))
|
||||
{
|
||||
Debug.Assert(false);
|
||||
throw new OutOfMemoryException();
|
||||
}
|
||||
#endif
|
||||
v[l] = ti;
|
||||
}
|
||||
|
||||
for(int l = 0; l < np; ++l)
|
||||
{
|
||||
v[l].Finished.WaitOne();
|
||||
v[l].Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void FillSegmentThr(object o)
|
||||
{
|
||||
Argon2ThreadInfo ti = (o as Argon2ThreadInfo);
|
||||
if(ti == null) { Debug.Assert(false); return; }
|
||||
|
||||
try
|
||||
{
|
||||
Argon2Ctx ctx = ti.Context;
|
||||
if(ctx == null) { Debug.Assert(false); return; }
|
||||
|
||||
Debug.Assert(ctx.Version >= MinVersion);
|
||||
bool bCanXor = (ctx.Version >= 0x13U);
|
||||
|
||||
ulong uStart = 0;
|
||||
if((ti.Pass == 0) && (ti.Slice == 0)) uStart = 2;
|
||||
|
||||
ulong uCur = (ti.Lane * ctx.LaneLength) + (ti.Slice *
|
||||
ctx.SegmentLength) + uStart;
|
||||
|
||||
ulong uPrev = (((uCur % ctx.LaneLength) == 0) ?
|
||||
(uCur + ctx.LaneLength - 1UL) : (uCur - 1UL));
|
||||
|
||||
ulong[] pbR = new ulong[NbBlockSizeInQW];
|
||||
ulong[] pbTmp = new ulong[NbBlockSizeInQW];
|
||||
|
||||
for(ulong i = uStart; i < ctx.SegmentLength; ++i)
|
||||
{
|
||||
if((uCur % ctx.LaneLength) == 1)
|
||||
uPrev = uCur - 1UL;
|
||||
|
||||
ulong uPseudoRand = ctx.Mem[uPrev * NbBlockSizeInQW];
|
||||
ulong uRefLane = (uPseudoRand >> 32) % ctx.Lanes;
|
||||
if((ti.Pass == 0) && (ti.Slice == 0))
|
||||
uRefLane = ti.Lane;
|
||||
|
||||
ti.Index = i;
|
||||
ulong uRefIndex = IndexAlpha(ctx, ti, (uint)uPseudoRand,
|
||||
(uRefLane == ti.Lane));
|
||||
|
||||
ulong uRefBlockIndex = (ctx.LaneLength * uRefLane +
|
||||
uRefIndex) * NbBlockSizeInQW;
|
||||
ulong uCurBlockIndex = uCur * NbBlockSizeInQW;
|
||||
|
||||
FillBlock(ctx.Mem, uPrev * NbBlockSizeInQW, uRefBlockIndex,
|
||||
uCurBlockIndex, ((ti.Pass != 0) && bCanXor), pbR, pbTmp);
|
||||
|
||||
++uCur;
|
||||
++uPrev;
|
||||
}
|
||||
|
||||
MemUtil.ZeroArray<ulong>(pbR);
|
||||
MemUtil.ZeroArray<ulong>(pbTmp);
|
||||
}
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
|
||||
try { ti.Finished.Set(); }
|
||||
catch(Exception) { Debug.Assert(false); }
|
||||
}
|
||||
|
||||
#if ARGON2_B2ROUND_ARRAYS
|
||||
private static void InitB2RoundIndexArrays()
|
||||
{
|
||||
int[][] vCols = g_vFBCols;
|
||||
if(vCols == null)
|
||||
{
|
||||
vCols = new int[8][];
|
||||
Debug.Assert(vCols.Length == 8);
|
||||
int e = 0;
|
||||
for(int i = 0; i < 8; ++i)
|
||||
{
|
||||
vCols[i] = new int[16];
|
||||
for(int j = 0; j < 16; ++j)
|
||||
{
|
||||
vCols[i][j] = e;
|
||||
++e;
|
||||
}
|
||||
}
|
||||
|
||||
g_vFBCols = vCols;
|
||||
}
|
||||
|
||||
int[][] vRows = g_vFBRows;
|
||||
if(vRows == null)
|
||||
{
|
||||
vRows = new int[8][];
|
||||
for(int i = 0; i < 8; ++i)
|
||||
{
|
||||
vRows[i] = new int[16];
|
||||
for(int j = 0; j < 16; ++j)
|
||||
{
|
||||
int jh = j / 2;
|
||||
vRows[i][j] = (2 * i) + (16 * jh) + (j & 1);
|
||||
}
|
||||
}
|
||||
|
||||
g_vFBRows = vRows;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private static void FillBlock(ulong[] pMem, ulong uPrev, ulong uRef,
|
||||
ulong uNext, bool bXor, ulong[] pbR, ulong[] pbTmp)
|
||||
{
|
||||
CopyBlock(pbR, 0, pMem, uRef);
|
||||
XorBlock(pbR, 0, pMem, uPrev);
|
||||
CopyBlock(pbTmp, 0, pbR, 0);
|
||||
if(bXor) XorBlock(pbTmp, 0, pMem, uNext);
|
||||
|
||||
#if ARGON2_B2ROUND_ARRAYS
|
||||
int[][] vCols = g_vFBCols;
|
||||
int[][] vRows = g_vFBRows;
|
||||
for(int i = 0; i < 8; ++i)
|
||||
Blake2RoundNoMsg(pbR, vCols[i]);
|
||||
for(int i = 0; i < 8; ++i)
|
||||
Blake2RoundNoMsg(pbR, vRows[i]);
|
||||
#else
|
||||
for(int i = 0; i < (8 * 16); i += 16)
|
||||
Blake2RoundNoMsgCols16i(pbR, i);
|
||||
for(int i = 0; i < (8 * 2); i += 2)
|
||||
Blake2RoundNoMsgRows2i(pbR, i);
|
||||
#endif
|
||||
|
||||
CopyBlock(pMem, uNext, pbTmp, 0);
|
||||
XorBlock(pMem, uNext, pbR, 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;
|
||||
}
|
||||
}
|
||||
}
|
144
ModernKeePassLib/Cryptography/KeyDerivation/Argon2Kdf.cs
Normal file
144
ModernKeePassLib/Cryptography/KeyDerivation/Argon2Kdf.cs
Normal file
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace ModernKeePassLib.Cryptography.KeyDerivation
|
||||
{
|
||||
public sealed partial class Argon2Kdf : KdfEngine
|
||||
{
|
||||
private static readonly PwUuid g_uuid = new PwUuid(new byte[] {
|
||||
0xEF, 0x63, 0x6D, 0xDF, 0x8C, 0x29, 0x44, 0x4B,
|
||||
0x91, 0xF7, 0xA9, 0xA4, 0x03, 0xE3, 0x0A, 0x0C });
|
||||
|
||||
public static readonly string ParamSalt = "S"; // Byte[]
|
||||
public static readonly string ParamParallelism = "P"; // UInt32
|
||||
public static readonly string ParamMemory = "M"; // UInt64
|
||||
public static readonly string ParamIterations = "I"; // UInt64
|
||||
public static readonly string ParamVersion = "V"; // UInt32
|
||||
public static readonly string ParamSecretKey = "K"; // Byte[]
|
||||
public static readonly string ParamAssocData = "A"; // Byte[]
|
||||
|
||||
private const uint MinVersion = 0x10;
|
||||
private const uint MaxVersion = 0x13;
|
||||
|
||||
private const int MinSalt = 8;
|
||||
private const int MaxSalt = int.MaxValue; // .NET limit; 2^32 - 1 in spec
|
||||
|
||||
internal const ulong MinIterations = 1;
|
||||
internal const ulong MaxIterations = uint.MaxValue;
|
||||
|
||||
internal const ulong MinMemory = 1024 * 8; // For parallelism = 1
|
||||
// internal const ulong MaxMemory = (ulong)uint.MaxValue * 1024UL; // Spec
|
||||
internal const ulong MaxMemory = int.MaxValue; // .NET limit
|
||||
|
||||
internal const uint MinParallelism = 1;
|
||||
internal const uint MaxParallelism = (1 << 24) - 1;
|
||||
|
||||
internal const ulong DefaultIterations = 2;
|
||||
internal const ulong DefaultMemory = 1024 * 1024; // 1 MB
|
||||
internal const uint DefaultParallelism = 2;
|
||||
|
||||
public override PwUuid Uuid
|
||||
{
|
||||
get { return g_uuid; }
|
||||
}
|
||||
|
||||
public override string Name
|
||||
{
|
||||
get { return "Argon2"; }
|
||||
}
|
||||
|
||||
public Argon2Kdf()
|
||||
{
|
||||
}
|
||||
|
||||
public override KdfParameters GetDefaultParameters()
|
||||
{
|
||||
KdfParameters p = base.GetDefaultParameters();
|
||||
|
||||
p.SetUInt32(ParamVersion, MaxVersion);
|
||||
|
||||
p.SetUInt64(ParamIterations, DefaultIterations);
|
||||
p.SetUInt64(ParamMemory, DefaultMemory);
|
||||
p.SetUInt32(ParamParallelism, DefaultParallelism);
|
||||
|
||||
return p;
|
||||
}
|
||||
|
||||
public override void Randomize(KdfParameters p)
|
||||
{
|
||||
if(p == null) { Debug.Assert(false); return; }
|
||||
Debug.Assert(g_uuid.Equals(p.KdfUuid));
|
||||
|
||||
byte[] pb = CryptoRandom.Instance.GetRandomBytes(32);
|
||||
p.SetByteArray(ParamSalt, pb);
|
||||
}
|
||||
|
||||
public override byte[] Transform(byte[] pbMsg, KdfParameters p)
|
||||
{
|
||||
if(pbMsg == null) throw new ArgumentNullException("pbMsg");
|
||||
if(p == null) throw new ArgumentNullException("p");
|
||||
|
||||
byte[] pbSalt = p.GetByteArray(ParamSalt);
|
||||
if(pbSalt == null)
|
||||
throw new ArgumentNullException("p.Salt");
|
||||
if((pbSalt.Length < MinSalt) || (pbSalt.Length > MaxSalt))
|
||||
throw new ArgumentOutOfRangeException("p.Salt");
|
||||
|
||||
uint uPar = p.GetUInt32(ParamParallelism, 0);
|
||||
if((uPar < MinParallelism) || (uPar > MaxParallelism))
|
||||
throw new ArgumentOutOfRangeException("p.Parallelism");
|
||||
|
||||
ulong uMem = p.GetUInt64(ParamMemory, 0);
|
||||
if((uMem < MinMemory) || (uMem > MaxMemory))
|
||||
throw new ArgumentOutOfRangeException("p.Memory");
|
||||
|
||||
ulong uIt = p.GetUInt64(ParamIterations, 0);
|
||||
if((uIt < MinIterations) || (uIt > MaxIterations))
|
||||
throw new ArgumentOutOfRangeException("p.Iterations");
|
||||
|
||||
uint v = p.GetUInt32(ParamVersion, 0);
|
||||
if((v < MinVersion) || (v > MaxVersion))
|
||||
throw new ArgumentOutOfRangeException("p.Version");
|
||||
|
||||
byte[] pbSecretKey = p.GetByteArray(ParamSecretKey);
|
||||
byte[] pbAssocData = p.GetByteArray(ParamAssocData);
|
||||
|
||||
byte[] pbRet = Argon2d(pbMsg, pbSalt, uPar, uMem, uIt,
|
||||
32, v, pbSecretKey, pbAssocData);
|
||||
|
||||
if(uMem > (100UL * 1024UL * 1024UL)) GC.Collect();
|
||||
return pbRet;
|
||||
}
|
||||
|
||||
public override KdfParameters GetBestParameters(uint uMilliseconds)
|
||||
{
|
||||
KdfParameters p = GetDefaultParameters();
|
||||
Randomize(p);
|
||||
|
||||
MaximizeParamUInt64(p, ParamIterations, MinIterations,
|
||||
MaxIterations, uMilliseconds, true);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
142
ModernKeePassLib/Cryptography/KeyDerivation/KdfEngine.cs
Normal file
142
ModernKeePassLib/Cryptography/KeyDerivation/KdfEngine.cs
Normal file
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
namespace ModernKeePassLib.Cryptography.KeyDerivation
|
||||
{
|
||||
public abstract class KdfEngine
|
||||
{
|
||||
public abstract PwUuid Uuid
|
||||
{
|
||||
get;
|
||||
}
|
||||
|
||||
public abstract string Name
|
||||
{
|
||||
get;
|
||||
}
|
||||
|
||||
public virtual KdfParameters GetDefaultParameters()
|
||||
{
|
||||
return new KdfParameters(this.Uuid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generate random seeds and store them in <paramref name="p" />.
|
||||
/// </summary>
|
||||
public virtual void Randomize(KdfParameters p)
|
||||
{
|
||||
Debug.Assert(p != null);
|
||||
Debug.Assert(p.KdfUuid.Equals(this.Uuid));
|
||||
}
|
||||
|
||||
public abstract byte[] Transform(byte[] pbMsg, KdfParameters p);
|
||||
|
||||
public virtual KdfParameters GetBestParameters(uint uMilliseconds)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
protected void MaximizeParamUInt64(KdfParameters p, string strName,
|
||||
ulong uMin, ulong uMax, uint uMilliseconds, bool bInterpSearch)
|
||||
{
|
||||
if(p == null) { Debug.Assert(false); return; }
|
||||
if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return; }
|
||||
if(uMin > uMax) { Debug.Assert(false); return; }
|
||||
|
||||
if(uMax > (ulong.MaxValue >> 1))
|
||||
{
|
||||
Debug.Assert(false);
|
||||
uMax = ulong.MaxValue >> 1;
|
||||
|
||||
if(uMin > uMax) { p.SetUInt64(strName, uMin); return; }
|
||||
}
|
||||
|
||||
byte[] pbMsg = new byte[32];
|
||||
for(int i = 0; i < pbMsg.Length; ++i) pbMsg[i] = (byte)i;
|
||||
|
||||
ulong uLow = uMin;
|
||||
ulong uHigh = uMin + 1UL;
|
||||
long tLow = 0;
|
||||
long tHigh = 0;
|
||||
long tTarget = (long)uMilliseconds;
|
||||
|
||||
// Determine range
|
||||
while(uHigh <= uMax)
|
||||
{
|
||||
p.SetUInt64(strName, uHigh);
|
||||
|
||||
// GC.Collect();
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Transform(pbMsg, p);
|
||||
sw.Stop();
|
||||
|
||||
tHigh = sw.ElapsedMilliseconds;
|
||||
if(tHigh > tTarget) break;
|
||||
|
||||
uLow = uHigh;
|
||||
tLow = tHigh;
|
||||
uHigh <<= 1;
|
||||
}
|
||||
if(uHigh > uMax) { uHigh = uMax; tHigh = 0; }
|
||||
if(uLow > uHigh) uLow = uHigh; // Skips to end
|
||||
|
||||
// Find optimal number of iterations
|
||||
while((uHigh - uLow) >= 2UL)
|
||||
{
|
||||
ulong u = (uHigh + uLow) >> 1; // Binary search
|
||||
// Interpolation search, if possible
|
||||
if(bInterpSearch && (tLow > 0) && (tHigh > tTarget) &&
|
||||
(tLow <= tTarget))
|
||||
{
|
||||
u = uLow + (((uHigh - uLow) * (ulong)(tTarget - tLow)) /
|
||||
(ulong)(tHigh - tLow));
|
||||
if((u >= uLow) && (u <= uHigh))
|
||||
{
|
||||
u = Math.Max(u, uLow + 1UL);
|
||||
u = Math.Min(u, uHigh - 1UL);
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Assert(false);
|
||||
u = (uHigh + uLow) >> 1;
|
||||
}
|
||||
}
|
||||
|
||||
p.SetUInt64(strName, u);
|
||||
|
||||
// GC.Collect();
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
Transform(pbMsg, p);
|
||||
sw.Stop();
|
||||
|
||||
long t = sw.ElapsedMilliseconds;
|
||||
if(t == tTarget) { uLow = u; break; }
|
||||
else if(t > tTarget) { uHigh = u; tHigh = t; }
|
||||
else { uLow = u; tLow = t; }
|
||||
}
|
||||
|
||||
p.SetUInt64(strName, uLow);
|
||||
}
|
||||
}
|
||||
}
|
80
ModernKeePassLib/Cryptography/KeyDerivation/KdfParameters.cs
Normal file
80
ModernKeePassLib/Cryptography/KeyDerivation/KdfParameters.cs
Normal file
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
|
||||
using ModernKeePassLib.Collections;
|
||||
using ModernKeePassLib.Utility;
|
||||
|
||||
namespace ModernKeePassLib.Cryptography.KeyDerivation
|
||||
{
|
||||
public sealed class KdfParameters : VariantDictionary
|
||||
{
|
||||
private const string ParamUuid = @"$UUID";
|
||||
|
||||
private readonly PwUuid m_puKdf;
|
||||
public PwUuid KdfUuid
|
||||
{
|
||||
get { return m_puKdf; }
|
||||
}
|
||||
|
||||
public KdfParameters(PwUuid puKdf)
|
||||
{
|
||||
if(puKdf == null) throw new ArgumentNullException("puKdf");
|
||||
|
||||
m_puKdf = puKdf;
|
||||
SetByteArray(ParamUuid, puKdf.UuidBytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unsupported.
|
||||
/// </summary>
|
||||
public override object Clone()
|
||||
{
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
public static byte[] SerializeExt(KdfParameters p)
|
||||
{
|
||||
return VariantDictionary.Serialize(p);
|
||||
}
|
||||
|
||||
public static KdfParameters DeserializeExt(byte[] pb)
|
||||
{
|
||||
VariantDictionary d = VariantDictionary.Deserialize(pb);
|
||||
if(d == null) { Debug.Assert(false); return null; }
|
||||
|
||||
byte[] pbUuid = d.GetByteArray(ParamUuid);
|
||||
if((pbUuid == null) || (pbUuid.Length != (int)PwUuid.UuidSize))
|
||||
{
|
||||
Debug.Assert(false);
|
||||
return null;
|
||||
}
|
||||
|
||||
PwUuid pu = new PwUuid(pbUuid);
|
||||
KdfParameters p = new KdfParameters(pu);
|
||||
d.CopyTo(p);
|
||||
return p;
|
||||
}
|
||||
}
|
||||
}
|
96
ModernKeePassLib/Cryptography/KeyDerivation/KdfPool.cs
Normal file
96
ModernKeePassLib/Cryptography/KeyDerivation/KdfPool.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
KeePass Password Safe - The Open-Source Password Manager
|
||||
Copyright (C) 2003-2019 Dominik Reichl <dominik.reichl@t-online.de>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
*/
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
using ModernKeePassLib.Utility;
|
||||
|
||||
namespace ModernKeePassLib.Cryptography.KeyDerivation
|
||||
{
|
||||
public static class KdfPool
|
||||
{
|
||||
private static List<KdfEngine> g_l = new List<KdfEngine>();
|
||||
|
||||
public static IEnumerable<KdfEngine> Engines
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureInitialized();
|
||||
return g_l;
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureInitialized()
|
||||
{
|
||||
if(g_l.Count > 0) return;
|
||||
|
||||
g_l.Add(new AesKdf());
|
||||
g_l.Add(new Argon2Kdf());
|
||||
}
|
||||
|
||||
internal static KdfParameters GetDefaultParameters()
|
||||
{
|
||||
EnsureInitialized();
|
||||
return g_l[0].GetDefaultParameters();
|
||||
}
|
||||
|
||||
public static KdfEngine Get(PwUuid pu)
|
||||
{
|
||||
if(pu == null) { Debug.Assert(false); return null; }
|
||||
|
||||
EnsureInitialized();
|
||||
|
||||
foreach(KdfEngine kdf in g_l)
|
||||
{
|
||||
if(pu.Equals(kdf.Uuid)) return kdf;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static KdfEngine Get(string strName)
|
||||
{
|
||||
if(string.IsNullOrEmpty(strName)) { Debug.Assert(false); return null; }
|
||||
|
||||
EnsureInitialized();
|
||||
|
||||
foreach(KdfEngine kdf in g_l)
|
||||
{
|
||||
if(strName.Equals(kdf.Name, StrUtil.CaseIgnoreCmp)) return kdf;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void Add(KdfEngine kdf)
|
||||
{
|
||||
if(kdf == null) { Debug.Assert(false); return; }
|
||||
|
||||
EnsureInitialized();
|
||||
|
||||
if(Get(kdf.Uuid) != null) { Debug.Assert(false); return; }
|
||||
if(Get(kdf.Name) != null) { Debug.Assert(false); return; }
|
||||
|
||||
g_l.Add(kdf);
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user