Code Monkey home page Code Monkey logo

isopoh.cryptography.argon2's People

Contributors

dependabot[bot] avatar frankhommers avatar heikomilke avatar luckywraptor avatar mheyman avatar michielpost avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

isopoh.cryptography.argon2's Issues

Extreme memory utilization for concurrent usage that seems to be curtailed when run in 32 bit mode

We are using this library from a web service running in IIS to verify password hashes that are created with the library. When we have concurrent verifications run (even 10-15), the memory usage jumps to 2-4GB and sometimes depending on the number of verifications, jumps up to 8-12 GB. When we set the application to run in 32 bit mode, while the verification might be a bit slower, this is no longer an issue. Any thoughts?

LockFailException

Hi,

I'm intermittently getting the following exception when trying to verify as hash:

LockFailException

Failed to lock 9 bytes into RAM. Under current available value of 2048 bytes (try again, it may work). Failed to securely lock 9 (prevMin=204800, min=204800, prevMax=4294967295, max=4294967295, prevFlags=10, flags=10, prevCur=3515860229377112, cur=3515860229377112) bytes at 0x60A8A2A0. Error: Insufficient quota to complete the requested service..
at Isopoh.Cryptography.SecureArray.SecureArray.Init[T](T[] buf, SecureArrayType type)
at Isopoh.Cryptography.Argon2.Argon2.Verify(String encoded, String password, String secret, SecureArrayCall secureArrayCall)

Running on Hololens UWP

Hi everyone,
I tried using Argon2 on Hololens, but there seem to be problems accessing the windows api from a UWP project. Sometimes Hololens is a bit special...so not sure, if it is a general UWP Problem.

Here is the stack trace I got. I think UWP is restricted on accessing native APIs, but I did not dig into this. Do you have any experience on this?

Thanks
Alex

System.TypeInitializationException: The type initializer for 'Isopoh.Cryptography.SecureArray.SecureArray' threw an exception. ---> System.NotSupportedException: No SecureArray.DefaultCall support for current operating system (whatever that is, maybe "Microsoft Windows NT 10.0.19041.0", I think I know Windows, Linux, OSX, and web - and maybe iOS...). You  don't have to use the default SecureArrayCall - you can pass in a version of the calls that work for your operating system.
  at Isopoh.Cryptography.SecureArray.SecureArray.get_DefaultCall () [0x00000] in <00000000000000000000000000000000>:0 
  at Isopoh.Cryptography.SecureArray.SecureArray..cctor () [0x00000] in <00000000000000000000000000000000>:0 
  at Isopoh.Cryptography.SecureArray.SecureArray`1[T]..ctor (System.Int32 size, Isopoh.Cryptography.SecureArray.SecureArrayType type, Isopoh.Cryptography.SecureArray.SecureArrayCall call) [0x00000] in <00000000000000000000000000000000>:0 
  at Isopoh.Cryptography.SecureArray.SecureArray`1[T].Best (System.Int32 size, Isopoh.Cryptography.SecureArray.SecureArrayCall secureArrayCall) [0x00000] in <00000000000000000000000000000000>:0 
  at Isopoh.Cryptography.Argon2.Argon2.Hash (System.String password, System.String secret, System.Int32 timeCost, System.Int32 memoryCost, System.Int32 parallelism, Isopoh.Cryptography.Argon2.Argon2Type type, System.Int32 hashLength, Isopoh.Cryptography.SecureArray.SecureArrayCall secureArrayCall) [0x00000] in <00000000000000000000000000000000>:0 
  at Isopoh.Cryptography.Argon2.Argon2.Hash (System.String password, System.Int32 timeCost, System.Int32 memoryCost, System.Int32 parallelism, Isopoh.Cryptography.Argon2.Argon2Type type, System.Int32 hashLength, Isopoh.Cryptography.SecureArray.SecureArrayCall secureArrayCall) [0x00000] in <00000000000000000000000000000000>:0 
  at StoredCreds.PrepareCredentialsForStorage (Credentials credentials) [0x00000] in <00000000000000000000000000000000>:0 
  at UserSelectionMode.Activate (NavigationParameters navigationParameters) [0x00000] in <00000000000000000000000000000000>:0 

Hashing consumes massive amounts of memory after hashing multiple passwords

After hashing multiple passwords, successive hash operations consume large amounts of RAM. Allocating the required memory takes a long time, and causes the hash operation to take a long time.

This caused problems in our application. The operating system itself has to get involved in allocating the required memory. During the allocation operation, no other processes (or threads) can be carried out on the server. The result was massive timeouts in the logins and other server operations.

The attached Argon2Test.zip is a complete Visual Studio 2013 solution that illustrates the error.

Start Argon2Test.exe (optionally with a number of hash operations to carry out - default is 200.)

The first few hash operations will be carried out quickly. Thereafter, depending on how much RAM your system has and the MemoryCost setting, successive hash operations will take longer while the memory allocations are being dealt with.

Argon2Test.zip

Netcore2 on mac Error

I am using this on Netcore2 and get this error when trying to run the application throw mac os.
The type initializer for Isopoh.Cryptography.secureArray.SecureArray throw new exception.

Warn users about the size of the nuget installation

Your package looked ideal. That is until I grabbed it off nuget and it must have installed about 50 dependencies - looking like all .net core (dev'ing on .net). You should put a warning somewhere on your readme about that. Now I'm left uninstalling loads of dependencies and your library..

Support for argon2id

I'm slightly confused whether the Argon2id variation of the algorithm is supported. I note that there is an option to switch between v1.3 and v1.2.1 in Argon2Version.cs, however Argon2Type.cs does not list Argon2id as an option.

Can you confirm which variations are supported?

Update dependencies for target `net6.0`

Hey, @mheyman!

I just found your repo & tried to install it into my .NET 6-based project.
However, your dependencies for target net6.0 explicitly list System.Thread, System.ThreadPool & System.ValueTuple, yet that very target already includes them on its own.

Would you therefore mind updating your dependencies regarding that platform?
I'd happily provide you with a PR, but couldn't find the required .nuspec file in your repo...

Retrieving version being used

Found this package a great asset for my project, however, I am wondering if there was a way for me to get the version number being used during the hashing process?

Release 1.1.11 breaks Verify method.

When upgrading to 1.1.11+ from 1.1.10 my Verify method is now broken .. is this expected? I don't see information regarding breaking changes for this release.

Stops Gif Animation on BackgroundWorker process.

Hi,

I'm using BackgroundWorker() in a STaThread application. I load my progressbar and GIF image in a separate form, which is then loaded by a separate instance of the BackgroundWorker(). All my progress bars and GIFs animations are working fine for all my application processes...until it met this line of code:
using (SecureArray<byte> hashA = argon2A.Hash())

GIFs and progress bars just stopped moving. I thought my computer stopped responding. I tried to experiment on some sample forms just to make sure what stops my GIFs from playing. The code below works fine.

`

    private void DoForms()
    {
        Form1 form1 = new Form1();
        var pb = new PictureBox();
        pb.Image = global::TPCamera.Properties.Resources.instacam;
        pb.SizeMode = PictureBoxSizeMode.AutoSize;
        form1.Controls.Add(pb);
        form1.Show();

        Form2 form2 = new Form2();
        pb = new PictureBox();
        pb.Image = global::TPCamera.Properties.Resources.instacam;
        pb.SizeMode = PictureBoxSizeMode.AutoSize;
        form2.Controls.Add(pb);
        form2.Show();

        var screenSaver = frmScreenSaver.CreateInstance();
        screenSaver.Show();

        bgw3 = new BackgroundWorker();
        bgw3.WorkerReportsProgress = true;
        bgw3.DoWork += new DoWorkEventHandler(form1.bgw1_DoWork);
        bgw3.ProgressChanged += form1.bgw1_ProgressChanged;
        bgw3.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(form1.bgw1_RunWorkerCompleted);
        bgw3.RunWorkerAsync(20000);

        bgw4 = new BackgroundWorker();
        bgw4.WorkerReportsProgress = true;
        bgw4.DoWork += new DoWorkEventHandler(this.bgw2_DoWork);
        bgw4.ProgressChanged += form2.bgw2_ProgressChanged;
        bgw4.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(form2.bgw2_RunWorkerCompleted);
        bgw4.RunWorkerAsync(10000);
    }

`

But if I insert an Argon2.Verify() like this:

       `var config = new Argon2Config();
        var password = txtPassword.Text.Trim();
        var passwordHash = txtPassword.Text.Trim().Encrypt(out config);`

Extender class to Encrypt password stops BackgroundWorker() process.

`

public static partial class Extenders
{
    public static string Encrypt(this string password, out Argon2Config config)
    {
        config = null;
        if (string.IsNullOrEmpty(password))
            return string.Empty;

        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
        byte[] salt = Encoding.UTF8.GetBytes("???????????????");
        byte[] secret = Encoding.UTF8.GetBytes("???????????????");
        byte[] associatedData = Encoding.UTF8.GetBytes("???????????????");

        //var _rng = RandomNumberGenerator.Create();
        //_rng.GetBytes(salt);
        //_rng.GetBytes(secret);
        //_rng.GetBytes(associatedData);

        config = new Argon2Config
        {
            Type = Argon2Type.DataIndependentAddressing,
            Version = Argon2Version.Nineteen,
            TimeCost = 10,
            MemoryCost = 32768,
            Lanes = 5,
            Threads = Environment.ProcessorCount,
            Password = passwordBytes,
            Salt = salt, // >= 8 bytes if not null
            Secret = secret,
            AssociatedData = associatedData,
            HashLength = 20 // >= 4
        };
        var argon2A = new Argon2(config);
        string hashString;
        using (SecureArray<byte> hashA = argon2A.Hash()) //===> this line of code stops GIFs
        {
            hashString = config.EncodeString(hashA.Buffer);
        }
         
        return hashString;
    }
}

`

Hash without salt is corrupt

Seems kind of basic, but the hash is corrupt if a salt isn't supplied.

Argon2.Hash(new Argon2Config {
    Password = Encoding.UTF8.GetBytes("test")
})
// $argon2id$v=19$m=65536,t=3,p=4
Argon2.Hash(new Argon2Config {
    Password = Encoding.UTF8.GetBytes("test"),
    Salt = [0, 0, 0, 0, 0, 0, 0, 0]
})
// $argon2id$v=19$m=65536,t=3,p=4$AAAAAAAAAAA$997Y916TCd1Fc7bOyGM7ZVs9tnPdyxDLqrm9sYAp0P8

Strip Base64 padding

The Argon2.Hash(password); method creates a hash string that contains B64 padding in salt and password hash. The hash formatting spec does not allow this.

The padding cause interoperability problems with stricter implementations like node-argon2

Output hash doesn't match output from argon2 linux utility

Hi, it looks like library has a bug or I'm using it wrong way.

Here is output from argon2 utility on debian linux

 echo "123" | argon2 12345678
Type:		Argon2i
Iterations:	3
Memory:		4096 KiB
Parallelism:	1
Hash:		ae1aaf1a29bbfe3f7d7bdd66c9d6478862b4d478d029a57f83631a9904f04ee7
Encoded:	$argon2i$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$rhqvGim7/j99e91mydZHiGK01HjQKaV/g2MamQTwTuc
0.019 seconds
Verification ok

Here is my code

var config = new Argon2Config
{
    Type = Argon2Type.DataIndependentAddressing,
    Password = Encoding.UTF8.GetBytes("123"),
    Salt = Encoding.UTF8.GetBytes("12345678"),
    MemoryCost = 4096,
    HashLength = 32,
    TimeCost = 3,
    Lanes = 1
};

var hash = Argon2.Hash(config); 
Console.WriteLine(hash); #  $argon2i$v=19$m=4096,t=3,p=1$MTIzNDU2Nzg$03ZOmEzTC+JV0iORcPgaoAuZMIFRTIEaxFjKo9fc+LY

As I see output is different after the second dollar sign

Could you please explain me why ?
Thanks

Details:

aptitude show argon2
Package: argon2                          
Version: 0~20171227-0.2
State: installed
Automatically installed: no
Multi-Arch: foreign
Priority: optional
Section: libs
Maintainer: Luca Bruno <[email protected]>
Architecture: amd64
Uncompressed Size: 65.5 k
Depends: libc6 (>= 2.14)
Description: memory-hard hashing function - utility
 Argon2 is a password-hashing function that can be used to hash passwords for credential storage, key derivation, or other applications. 
 
 There are two main versions of Argon2: Argon2i and Argon2d. Argon2i is the safest against side-channel attacks, while Argon2d provides the highest resistance
 against GPU cracking attacks. 
 
 Argon2i and Argon2d are parametrized by: 
 * A time cost, which defines the amount of computation realized and therefore the execution time, given in number of iterations 
 * A memory cost, which defines the memory usage, given in kibibytes 
 * A parallelism degree, which defines the number of parallel threads 
   
 This package contains the argon2 tool for hashing data on the command-line.
Homepage: https://github.com/P-H-C/phc-winner-argon2
Tags: role::shared-lib
<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
    <PackageReference Include="Isopoh.Cryptography.Argon2" Version="1.1.10" />
  </ItemGroup>

System.TypeInitializationException with .NET native on UWP

If compilation is activated in the release mode with .NET native, the following error message appears:

System.TypeInitializationException: 'A type initializer threw an exception. To determine which type, inspect the InnerException's StackTrace property.'
Inner exception:
TypeLoadException: Unresolved P/Invoke method 'libSystem!OsxMemset' from this method. Please look for this method in build warnings for more details. 

   at System.Runtime.CompilerServices.ClassConstructorRunner.EnsureClassConstructorRun(StaticClassConstructionContext* pContext) in f:\dd\ndp\fxcore\CoreRT\src\System.Private.CoreLib\src\System\Runtime\CompilerServices\ClassConstructorRunner.cs:line 114
   at System.Runtime.CompilerServices.ClassConstructorRunner.CheckStaticClassConstruction(Void* returnValue, StaticClassConstructionContext* pContext) in f:\dd\ndp\fxcore\CoreRT\src\System.Private.CoreLib\src\System\Runtime\CompilerServices\ClassConstructorRunner.cs:line 37
   at Isopoh.Cryptography.SecureArray.SecureArray..ctor(SecureArrayCall call)
   at Isopoh.Cryptography.SecureArray.SecureArray`1..ctor(Int32 size, SecureArrayType type, SecureArrayCall call)
   at Isopoh.Cryptography.SecureArray.SecureArray`1.Best(Int32 size, SecureArrayCall secureArrayCall)
   at Isopoh.Cryptography.Argon2.Argon2.Hash(String password, String secret, Int32 timeCost, Int32 memoryCost, Int32 parallelism, Argon2Type type, Int32 hashLength, SecureArrayCall secureArrayCall)
   at Isopoh.Cryptography.Argon2.Argon2.Hash(String password, Int32 timeCost, Int32 memoryCost, Int32 parallelism, Argon2Type type, Int32 hashLength, SecureArrayCall secureArrayCall)

compiling with net native produces the following errors:

microsoft.net.native.compiler\2.2.9-rel-29512-01\tools\Microsoft.NetNative.targets(805,5): warning :
MCG : warning MCG0007: Unresolved P/Invoke method 'psapi.dll!GetProcessMemoryInfo' for method 'System.Boolean Isopoh.Cryptography.SecureArray.WindowsNative.UnsafeNativeMethods.GetProcessMemoryInfo(System.IntPtr, Isopoh.Cryptography.SecureArray.WindowsNative.UnsafeNativeMethods.ProcessMemoryCounters, System.UInt32)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'ntdll.dll!RtlZeroMemory' for method 'System.Void Isopoh.Cryptography.SecureArray.WindowsNative.UnsafeNativeMethods.RtlZeroMemory(System.IntPtr, System.UIntPtr)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libSystem!mlock' for method 'System.Int32 Isopoh.Cryptography.SecureArray.OsxNative.UnsafeNativeMethods.OsxMlock(System.IntPtr, System.UIntPtr)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libSystem!munlock' for method 'System.Int32 Isopoh.Cryptography.SecureArray.OsxNative.UnsafeNativeMethods.OsxMunlock(System.IntPtr, System.UIntPtr)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libSystem!memset' for method 'System.IntPtr Isopoh.Cryptography.SecureArray.OsxNative.UnsafeNativeMethods.OsxMemset(System.IntPtr, System.Int32, System.UIntPtr)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libc!mlock' for method 'System.Int32 Isopoh.Cryptography.SecureArray.LinuxNative.UnsafeNativeMethods.LinuxMlock(System.IntPtr, System.UIntPtr)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libc!munlock' for method 'System.Int32 Isopoh.Cryptography.SecureArray.LinuxNative.UnsafeNativeMethods.LinuxMunlock(System.IntPtr, System.UIntPtr)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libc!memset' for method 'System.IntPtr Isopoh.Cryptography.SecureArray.LinuxNative.UnsafeNativeMethods.LinuxMemset(System.IntPtr, System.Int32, System.UIntPtr)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libc!getrlimit' for method 'System.Int32 Isopoh.Cryptography.SecureArray.LinuxNative.UnsafeNativeMethods.LinuxGetRLimit(System.Int32, Isopoh.Cryptography.SecureArray.LinuxNative.UnsafeNativeMethods.LinuxRlimit)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libc!setrlimit' for method 'System.Int32 Isopoh.Cryptography.SecureArray.LinuxNative.UnsafeNativeMethods.LinuxSetRLimit(System.Int32, Isopoh.Cryptography.SecureArray.LinuxNative.UnsafeNativeMethods.LinuxRlimit)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libc!strerror_r' for method 'System.IntPtr Isopoh.Cryptography.SecureArray.LinuxNative.UnsafeNativeMethods.LinuxSterrorR(System.Int32, System.IntPtr, System.UInt64)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'libc!sysctl' for method 'System.Int32 Microsoft.DotNet.PlatformAbstractions.Native.NativeMethods.Darwin.sysctl(System.Int32*, System.UInt32, System.Byte*, System.UInt32*, System.IntPtr, System.UInt32)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
MCG : warning MCG0007: Unresolved P/Invoke method 'ntdll!RtlGetVersion' for method 'System.Int32 Microsoft.DotNet.PlatformAbstractions.Native.NativeMethods.Windows.RtlGetVersion(Microsoft.DotNet.PlatformAbstractions.Native.NativeMethods.Windows.RTL_OSVERSIONINFOEX)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisfy those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.````

Memory allocate issue ?

Hi,
I'm using Rider and the IDE warn me about memory is it a normal or there is an issue with the memory allocated ?
image

Possible Timing-Attack on Argon2.Verify()

Argon2.Verify() and the open-coded verification in the usage sample in README.md both use !hashB.Buffer.Where((b, i) => b != hashToVerify[i]).Any() to compare hashes for verification.

This is not a time-constant operation and aborts as soon as the first non-equal byte is encountered. As such, the time the verify operation takes depends on user-controlled input and enables an attacker to mount a timing attack (see eg. Wikipedia)

You can avoid this by using a time-constant buffer comparison. See eg. the reference implementation of Argon2: https://github.com/P-H-C/phc-winner-argon2/blob/f30e1f11f2e2619f07a4950abe1419218c4900be/src/argon2.c#L239

Argon2.Verify() should either use CryptographicOperations.FixedTimeEquals() or an open-coded version of this.

pinvokestackimbalance on Windows memset call

We use Blake2b on a WPF application.

We updated the version from 1.1.12 to 2.0.0 and the library started to throw a Managed Debugging Assistant 'PInvokeStackImbalance' on the Isopoh.Cryptography.Blake2B.Create(Blake2BConfig? config, SecureArrayCall secureArrayCall) method.

image

Though the throw only occurs in debug, it also can cause troubles in release.

I could fix the issue by changing the memset PInvoke Calling Convention to CDecl

image

That is because ntdll exposes NAPI (Native API), lower level functions than other Win32API DLLs.

Some of the NAPI are also part of the CRT (C Runtime). All of those use the C calling convention (CDECL) instead of STDCALL (the default calling convention for higher level Win32 APIs)

In CDECL, the caller is responsible for freeing stack memory allocated by the call. In STDCALL that responsibility is from the calee.

That leaves the call with an unexpected stack size, which is the reason why the Managed Debugging Assistant throws the 'PInvokeStackImbalance' when debugging.

In a release build the PInvokeStackImbalance is not thrown, but some relate it could cause memory leak or stackoverflow in extreme cases.

Anyway, it is very bad for debugging and it is simply not the correct behavior.

That was tested in a x64 Windows 11, but there is no change in that for other Windows versions.

Unable to load DLL 'kernel32.dll'

DllNotFoundException: Unable to load DLL 'kernel32.dll': The specified module or one of its dependencies could not be found.
(Exception from HRESULT: 0x8007007E)
Isopoh.Cryptography.SecureArray.SecureArray.GetModuleHandle(string moduleName)

TypeInitializationException: The type initializer for 'Isopoh.Cryptography.SecureArray.SecureArray' threw an exception.
Isopoh.Cryptography.Argon2.Argon2.Verify(string encoded, string password, SecureArrayCall secureArrayCall)

dotnet core : 2.1.4
os : mac os x 10.13.3

don't work on mac os , is there anything i can do to handle this ?

Memory is not being released

I noticed that after I either use Hash() or Verify() functions, memory drastically increases but is not released. My service will go from around 150MB to 600 MB+ which is what is supposed to happen, right? Since that is point of Argon2, to be memory heavy, right? But memory is not released and service is just running with 600+ MB from now on.

I tried to explicitly call GC.Collect() after Argon2 functions, and it releases some because then memory usage is around 450 MB which is better but still not good. I also tried to explicitly dispose my DbContext which also drops memory usage for about 100 MB more but I don't understand why that is even happening. If I turn off all Argon2 functions (comment all Argon2 code), service runs with around 150MB and DbContext has not effecting it ever.

I suspect there is some issues with garbage collection with Argon2.

Blazor WebAssembly option for SecureArray.DefaultCall

I'm using this library with a new .net 5 Blazor webassembly project.

But i get the following error when calling ComputeHash:
System.NotSupportedException: No SecureArray.DefaultCall support for current operating system (whatever that is, maybe "Browser", I think I know Windows, Linux, OSX, and web - and maybe iOS...). You don't have to use the default SecureArrayCall - you can pass in a version of the calls that work for your operating system.

Is it possible to use this with Blazor Webassembly?

High Heap Using

image

I cannot clean memory.

Small Object Heap: code that allocates a lot of memory in SOH
Allocated object type: UInt64[]
Allocated size: 2,693.9 MB

at Argon2.FillBlockWithXor(BlockValues, BlockValues, BlockValues)
at Argon2.FillSegment(Position)
at Argon2.FillMemoryBlocks()
at Argon2.Hash()

Clarification on conflicting licenses (CC0/CC4/attribution?)

Please clarify the license, especially whether there is any attribution requirement when the code is used.

As of today,

SecureArray crashes when MemoryCost is over 3000000 and memory is not freed after hashing.

When memory cost is set to be over a couple GB (in my testing it was set around 3000000), SecureArray throws an exception saying "'Array dimensions exceeded supported range."

Also, after the hashing is complete memory is not correctly freed even after manually calling Dispose and GC.Collect().

Sadly, this implementation is not suitable for my purposes because of these issues.

No clear way to disable memory binding

I've read previous issues regarding memory locking with SecureArray, however it seems to be cranked up to 11 during normal usage on Windows 10 machine. In my instance however, it seems that system simply refuses to allow any locking, spitting errors on each attempt to do so. None of them break execution, yet it is a simply unnecessary resource waste. Just by looking at screenshot it should be simple to realize that this is ridiculous.

Is there a sensible way to disable memory locking to prevent this?

image

Code that is causing those errors:

image

Very slow on hashing

Not sure why is so slow on one of the servers that I have, the spec of the server is
4 cores, 2.5ghz, 16g memory, win2012 server and bellow is my argon2i config (.net 4.72)

Argon2Config Argon2DefaultConfig = new Argon2Config
        {
            Type = Argon2Type.DataIndependentAddressing,
            Version = Argon2Version.Nineteen,
            TimeCost = 3,
            Lanes = 4,
            MemoryCost = 64 * 1024,
            Threads = 1,
            HashLength = 32,
        };

I don't think it is a very high requirement. However, it takes 20s to hash a password. I don't what is wrong there.

Is there any gotcha?

Look forward to hearing the response

OutOfMemoryException when creating Argon2()

From time to time I've got an OutOfMemoryException when doing the following in version 1.1.10 (November, 18th 2020):

var argon2A = new Argon2(config);

My configuration looks like this:

{Isopoh.Cryptography.Argon2.Argon2Config}
    AssociatedData: null
    ClearPassword: false
    ClearSecret: false
    HashLength: 32
    Lanes: 4
    MemoryCost: 131072
    Password: null
    Salt: null
    Secret: null
    SecureArrayCall: {Isopoh.Cryptography.SecureArray.DefaultWindowsSecureArrayCall}
    Threads: 4
    TimeCost: 3
    Type: HybridAddressing
    Version: Nineteen

The exception states the following:
Failed to allocate 16777216-byte Argon2 block array, memory cost 131072, lane count 4.

The exception occurs sporadically but it's not comprehensible in which situation.
Since it is an x86 application I thought it's about the memory consumption of my application but i've doublechecked this - it's just around 600MB. If I'm going to decrease the memory cost at some point it works.

SecureArray.SetProcessWorkingSetSizeEx unbalances stack

When I use Argon2 in Release on Win10 x64bit, the following exception is thrown:
(seems like a mismatch in function signature - wrong params or their types)

Additional information: A call to PInvoke function 
'Isopoh.Cryptography.SecureArray!Isopoh.Cryptography.SecureArray.SecureArray::SetProcessWorkingSetSizeEx' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

Memory leak

Sample code:

using System;
using Isopoh.Cryptography.Argon2;

namespace SnippetTester
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i <= 1000000; i++)
            {
                Console.WriteLine("Argon2 (b,b) is: " + Argon2.Verify("$argon2i$v=19$m=65536,t=3,p=1$M2f6+jnVc4dyL3BfMQRzoA==$jO/fOrgqxX90XDVhiYZgIVJJcw0lzIXtRFRCEggXYV8=", "b"));
            }
        }
    }
}

Expected: things work ok, without ballooning to take up all system memory.

Actually:

image

What's in the heap (around 5GB allocated at this stage:)

image

Cannot install Nuget package in project with 4.6.1 Framework

I get an error, when I try to install the Nuget package to a project which targets .NET Framework 4.6.1.

Could not install package 'Isopoh.Cryptography.Argon2 1.0.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.6.1', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

Memory leak in Verify()

Hi all,

I've noticed that Verify() keeps growing memory dramatically (bumps of 400-800MB each iteration!), the memory doesn't clean.
This is a high load production environment.

Only GC.Collect() after each Verify() keeps the memory sane.

Thanks

Incorrect output when generating more than 64 bytes

When comparing outputs and performance between this library and Konscious.Security.Cryptography.Argon2, I noticed that your output is different when requesting more than 64 bytes. I verified that your output is also different from that produced by antelle.net/argon2-browser, which means there is probably a bug in this library. This difference is present for all addressing modes (Argon2i, Argon2id, Argon2d).

There also isn't any kind of error when setting the memory cost to less than 8 (the minimum in the spec), but your output is different from Konscious.Security.Cryptography.Argon2 again. Not sure whose bug it is, but if you want to match the spec you should probably throw an ArgumentException when memory cost < 8.

Password verification fails if hash is not of the default length (32 bytes)

If parameter hashLength has a value different from the default one (32) when a password hash is computed, then subsequent verification of the password using this hash fails, e.g.:

string password = "password";
string hash = Argon2.Hash(password, hashLength: 16);
bool isPasswordValid = Argon2.Verify(hash, password);

Here isPasswordValid contains the value false.

The only workaround is to use an overload of Verify with config parameter that allows specifying the length of the hash manually:

string password = "password";
string hash = Argon2.Hash(password, hashLength: 16);

var config = new Argon2Config
{
    HashLength = 16,
    Password = Encoding.UTF8.GetBytes(password)
};
var isPasswordValid = Argon2.Verify(hash, config);`

Here isPasswordValid is set to true. This workaround is not always easy to use. For instance, it may be problematic to specify the hash length manually, if the hash is fetched from a DB column in which hashes of different lengths are stored.

All in all, the described behavior looks like a bug to me.
I think a user expects any overload of Verify method (even the one that allows specifying the hash length manually through the config parameter) to determine the hash length automatically from the supplied modular hash-string, e.g.:

  1. Supplied hash-string: $argon2id$v=19$m=65536,t=3,p=1$i7b+qK1wdFdRO4+d6d+EIQ$lftJwq/kAzpF2mUYlZ7/6Q.
  2. Base64-encoded hash: lftJwq/kAzpF2mUYlZ7/6Q.
  3. Hash length: 16.

Documentation Typos

To is missing in 2nd line below in the argon2Verify variable:

var argon2ToVerify = new Argon2(configOfPasswordToVerify);
using(var hashToVerify = argon2Verify.Hash())

A is missing in the 3rd line below in the argon2 variable:

var argon2A = new Argon2(config);
string hashString;
using(SecureArray<byte> hashA = argon2.Hash())

Errors appearing after creating first project with .Net "core" 5.

Errors appearing after creating first project with .Net "core" 5.

Whilst debugging something else I am noticing a lot of errors as follows:

Exception caught: 'Isopoh.Cryptography.SecureArray.LockFailException' in Isopoh.Cryptography.SecureArray.dll ("Failed to lock 67108864 bytes into RAM. Set SecureArray.ReportMaxLockableOnLockFail=true to enable reporting. Failed to securely lock 67108864 (prevMin=204800, min=204800, prevMax=112463872, max=273539072, prevFlags=10, flags=10, prevCur=160841728, cur=160841728) bytes at 0x1324463A0D0. Error: Insufficient quota to complete the requested service..") Exception caught: 'Isopoh.Cryptography.SecureArray.LockFailException' in Isopoh.Cryptography.SecureArray.dll ("Failed to lock 67108864 bytes into RAM. Set SecureArray.ReportMaxLockableOnLockFail=true to enable reporting. Failed to securely lock 67108864 (prevMin=204800, min=204800, prevMax=112463872, max=273539072, prevFlags=10, flags=10, prevCur=160841728, cur=160841728) bytes at 0x1324463A0D0. Error: Insufficient quota to complete the requested service..")

And

Exception thrown: 'System.DllNotFoundException' in Isopoh.Cryptography.SecureArray.dll ("Unable to load DLL 'libc' or one of its dependencies: The specified module could not be found. (0x8007007E)") Exception thrown: 'System.DllNotFoundException' in Isopoh.Cryptography.SecureArray.dll ("Unable to load DLL 'libc' or one of its dependencies: The specified module could not be found. (0x8007007E)")

This is my usual Windows 10 dev machine using the latest Visual Studio.

Hashing becomes slower and slower over time

The more lanes are configured, the faster the issue occurs.
Run this simple loop with the latest version, after about 10-15 iterations the hash time increases a lot and eventually it will take minutes. Reproduced on multiple computers.

It looks like we get more and more LockFailException being thrown when constructing SecuryArrays. On top of that it looks like the GetMaxLockable method takes a long time to execute.

See attached test cs file.

Program.zip

Here is the output of a sample run (expected time is around 2 sec):

Time elapsed: 1996 ms
Time elapsed: 1526 ms
Time elapsed: 1507 ms
Time elapsed: 1737 ms
Time elapsed: 1935 ms
Time elapsed: 1665 ms
Time elapsed: 1904 ms
Time elapsed: 1952 ms
Time elapsed: 1565 ms
Time elapsed: 2080 ms
Time elapsed: 1745 ms
Time elapsed: 1525 ms
Time elapsed: 1660 ms
Time elapsed: 4944 ms
Time elapsed: 10502 ms
Time elapsed: 5073 ms
Time elapsed: 9015 ms
Time elapsed: 8111 ms

Exploding memory usage

I just installed your library and did nothing special. At program start, I was hashing 3 string (testing purposes). Later, I called Argon2.Verify and nothing else.

My application suddenly exploded to like over 600MB of memory usage - holy hell. I uninstalled the package again and tried to verify, if this was the issue - it was.

I appreciate your time and effort writing this library, but can we do something about this abnormous memory usage? I mean I already read about that "reduce cost blabla" post of the other users, but shouldn't be a standard config pretty much do it as well?

Maybe someone finds a fix / workaround.

(Why am I using a separate issue? Because it's a separate problem: static helper <> instantiation with specified config... :))

Using Argon2.Hash() with string Secret fails Verify()

When using the the basic Argon2.Hash(string Password) method, I can successfully hash and verify my passwords. But when I introduce the string secret parameter, my passwords no long are verified. Example:

// WORKS
var plaintextPassword = "MyPassword";
var hashedPassword= Argon2.Hash(plaintextPassword);
var check = Argon2.Verify(hashedPassword, plaintextPassword);
// check == True
// DOES NOT WORK
var plaintextPassword = "MyPassword";
var hashedPassword= Argon2.Hash(plaintextPassword, "mysecret");
var check = Argon2.Verify(hashedPassword, plaintextPassword);
// check == False

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.