Diffie Hellman implementation- NodeJS

Diffie Hellman is a key exchange algorithm where client and server both generate public and private key, exchange their public key and combine this key with his own private key to generate same secret key.

But, here is a confusion in the implementation. Here is the code…

const crypto = require('crypto'); const express = require('express'); const app = express();  // Generate server's keys... const server = crypto.createDiffieHellman(139); const serverKey = server.generateKeys();  // Generate client's keys... const client = crypto.createDiffieHellman(server.getPrime(), server.getGenerator()); const clientKey = client.generateKeys();  // Exchange and generate the secret... const serverSecret = server.computeSecret(clientKey); const clientSecret = client.computeSecret(serverKey);   

First of all, server create an instance of DiffieHellman class to generate key. But, client need server’s prime (.getPrime()) and Generator (.getGenerator()) to generate another instance of DiffieHellman class to generate key.

So, server need to pass the value of server.getPrime() and server.getGenerator() to the client. What happen if any middle-man-attack rises in this time? Because, if somehow hacker get this two things then they can also generate same secret key. (-_-)

Any solution? Think this system without TLS.

Boolean Lattice Implementation

Let $ X = \{1,2,\dots n\}$ , and $ Y= \{ S\subset X: |S|\le 2\}$ . I am interested in "avoidance sets" $ A \subset Y$ which logically are supposed to correspond to $ f(A):=\bigwedge_{a\in A} \lnot a$ in the Boolean lattice defined over $ \mathcal{P}(X)$ . (if $ A = \{\}$ it shall correspond to $ X$ , the maximal element of our lattice)

Given a list of avoidance sets $ A_1,A_2,\dots A_k$ , I want to return an avoidance set $ A’$ such that $ f(A’)$ is the least upper bound of $ \bigvee_{1\le i \le k} f(A_i)$ . (by least upper bound I mean the least upper bound which can be represented by an avoidance set)

Can this be done in time linear to $ \sum_{1\le i \le k} |A_i|$ ? (you may assume that all the sets $ A_i$ are simplified, i.e. if $ \{a\}\in A_i$ and $ \{b\}\in A_i$ then $ \{a,b\} \not \in A_i$ )

C# Isopoh Argon2 Implementation hash does not verify


Summary

  • trying to implement password hashing using Argon2 in C#
  • I have already tried searching, and can’t find this specific issue. Nor does there seem to be a lot of good (easy for me to interpret?) examples for C# Argon2 (please let me know if there is a better way than Isopoh)
  • Using a C# implementation (Isopoh.Cryptography.Argon2) as recommended here
  • I can generate hashes with no issues, passing through various arguments for the Argon2Config
  • I can verify hashes with no issues ONLY IF the hash length is = 32. Anything seems to fail
  • However, I can verify ALL hashes online

This is my first post here so do let me know if I should make any amendments accordingly.

Thanks in advance for any help in resolving this!

Background

I’m testing out different ways of storing encrypted data. I already have a way to encrypt/decrypt data, But I am now looking at ways to implement proper password hashing (and to also use this hashed password as the key for the encryption of the other data – but I will raise this in another thread once I get to that point).

I am developing using VS2019 in a Windows 10 x64 environment. Whilst I’m not new to programming, I am learning C# (from VB.NET), and I’m certainly no expert in Cryptography.

I’m using an implementation of Argon2 that I found recommended in this post to learn how to securely store/hash passwords.

Issue

I can get the hashing process to work (whilst customising the configuration). However, when it comes to verifying the hash, I cannot verify the hash if I use any other hash length apart from 32 – I can play around with the other config settings and it works, but not the hash length.

BUT, where it gets really weird, when I generate a hash that uses a hash length not equal to 32, I verify it using this site, and I get a successful verification

Code

  • I’ve installed the Isopoh.Cryptography packages in the project via NuGet (using v1.1.4)

Namespace:

using System.Security.Cryptography; using Isopoh.Cryptography.Argon2; using Isopoh.Cryptography.SecureArray; 

Variable:

private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create(); 

Hashing code:

        string str_ConsoleText;          txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("[START NEW HASH]");         txtConsole.AppendText(Environment.NewLine);         str_ConsoleText = "Starting encryption process";         txtConsole.AppendText(str_ConsoleText);         txtConsole.AppendText(Environment.NewLine);          var stopwatch = Stopwatch.StartNew();          //var password = "password1";         var password = txtPasword.Text;         byte[] passwordBytes = Encoding.UTF8.GetBytes(password);         byte[] salt = new byte[16];                              Rng.GetBytes(salt);          txtSalt.Text = salt.ToString();          var config = new Argon2Config         {             Type = Argon2Type.HybridAddressing,             Version = Argon2Version.Nineteen,             TimeCost = Int32.Parse(txtIterations.Text),             MemoryCost = Int32.Parse(txtMemory.Text) * 1024,             Lanes = Int32.Parse(txtParallelism.Text),             Threads = Int32.Parse(txtThreads.Text),             Password = passwordBytes,             Salt = salt, // >= 8 bytes if not null             //Secret = secret, // from somewhere             //AssociatedData = associatedData, // from somewhere             HashLength = Int32.Parse(txtHashLength.Text) //20 // >= 4         };         var argon2A = new Isopoh.Cryptography.Argon2.Argon2(config);         string hashString;         using (SecureArray<byte> hashA = argon2A.Hash())         {             hashString = config.EncodeString(hashA.Buffer);         }          txtHashResult.Text = hashString;          stopwatch.Stop();          str_ConsoleText = "Encoded hash is: ";         txtConsole.AppendText(str_ConsoleText);         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText(hashString);         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("Details are:");         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("Time cost: " + config.TimeCost.ToString());         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("Memory cost: " + config.MemoryCost.ToString());         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("Lanes: " + config.Lanes.ToString());         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("Threads: " + config.Threads.ToString());         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("Salt: " + config.Salt.ToString());         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("Hash length: " + config.HashLength.ToString());         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText(Environment.NewLine);                  str_ConsoleText = $  "Encryption process took { stopwatch.ElapsedMilliseconds / 1024.0 } s";         txtConsole.AppendText(str_ConsoleText);         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("[END HASH]"); 

Verifying code:

        var stopwatch = Stopwatch.StartNew();          string str_ConsoleText;          var password = txtPasword.Text;         var passwordHash = txtHashResult.Text;          txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("[START VERIFY HASH]");         txtConsole.AppendText(Environment.NewLine);         str_ConsoleText = "Starting verification process";         txtConsole.AppendText(str_ConsoleText);         txtConsole.AppendText(Environment.NewLine);          txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText(Environment.NewLine);         str_ConsoleText = "[Hash to verify]: ";         txtConsole.AppendText(str_ConsoleText);         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText(passwordHash.ToString());         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText(Environment.NewLine);           if (Isopoh.Cryptography.Argon2.Argon2.Verify(passwordHash, password))         {             // do stuff             str_ConsoleText = "!!!!!!!!!!HASH VERIFICATION SUCCESS!!!!!!!!!!";             txtConsole.AppendText(str_ConsoleText);         }         else         {             str_ConsoleText = "******HASH VERIFICATION FAILED******";             txtConsole.AppendText(str_ConsoleText);         }           stopwatch.Stop();         txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText(Environment.NewLine);         str_ConsoleText = $  "Verification process took { stopwatch.ElapsedMilliseconds / 1024.0 } s";         txtConsole.AppendText(str_ConsoleText);         txtConsole.AppendText(Environment.NewLine);                                 txtConsole.AppendText(Environment.NewLine);         txtConsole.AppendText("[END VERIFY HASH]"); 

Outputs/Results

Password = Hello World!

Hash length = 32:

[START NEW HASH] Starting encryption process Encoded hash is:  $  argon2id$  v=19$  m=32768,t=4,p=8$  bPsTGKZu/reihfAlLEVlCA$  o79dNC9/toz7CbbFhhkSy4/E2a5pRETd7h+79R7V7iU Details are: Time cost: 4 Memory cost: 32768 Lanes: 8 Threads: 4 Salt: System.Byte[] Hash length: 32  Encryption process took 2.130859375 s [END HASH]  [START VERIFY HASH] Starting verification process      [Hash to verify]:  $  argon2id$  v=19$  m=32768,t=4,p=8$  bPsTGKZu/reihfAlLEVlCA$  o79dNC9/toz7CbbFhhkSy4/E2a5pRETd7h+79R7V7iU  !!!!!!!!!!HASH VERIFICATION SUCCESS!!!!!!!!!!  Verification process took 1.3115234375 s  [END VERIFY HASH] 

Argon2.online hash verification:

enter image description here

Hash length = 64:

[START NEW HASH] Starting encryption process Encoded hash is:  $  argon2id$  v=19$  m=32768,t=4,p=8$  h/zEPuZWQsBSAPhZn23gRQ$  6FZzr5DhOMemPTzZ5WY+4MgsxKsxYLNuRbiKo8og+FoYOJFfBsfdCtr1Zs8z6lXVX+E7FUYsGaLA2ZESH6aE0w Details are: Time cost: 4 Memory cost: 32768 Lanes: 8 Threads: 4 Salt: System.Byte[] Hash length: 64  Encryption process took 2.0400390625 s [END HASH]  [START VERIFY HASH] Starting verification process   [Hash to verify]:  $  argon2id$  v=19$  m=32768,t=4,p=8$  h/zEPuZWQsBSAPhZn23gRQ$  6FZzr5DhOMemPTzZ5WY+4MgsxKsxYLNuRbiKo8og+FoYOJFfBsfdCtr1Zs8z6lXVX+E7FUYsGaLA2ZESH6aE0w  ******HASH VERIFICATION FAILED******  Verification process took 1.3076171875 s  [END VERIFY HASH] 

Argon2.online hash verification: enter image description here

Understanding a CRC32 Implementation

I’m currently trying to understand an implementation of CRC32 about which I have a question.

On this page at section 6, there is the following code:

public uint Compute_CRC32_Simple(byte[] bytes) {     const uint polynomial = 0x04C11DB7; /* divisor is 32bit */     uint crc = 0; /* CRC value is 32bit */      foreach (byte b in bytes)     {         crc ^= (uint)(b << 24); /* move byte into MSB of 32bit CRC */          for (int i = 0; i < 8; i++)         {             if ((crc & 0x80000000) != 0) /* test for MSB = bit 31 */             {                 crc = (uint)((crc << 1) ^ polynomial);             }             else             {                 crc <<= 1;             }         }     }      return crc; } 

I’m particularly interested in understanding this line: crc ^= (uint)(b << 24); /* move byte into MSB of 32bit CRC */

What are the mathematics that make this line possible, both the shifting of the current byte (turned into an int) by 24 and the following XOR with the current crc? Unfortunately, the author doesn’t go into detail regarding this.

Can I use my own implementation of a widely used, supposedly secure cryptographic algorithm for securing data at rest?

I know you shouldn’t roll your own crypto and generally its not a good idea to implement (and then deploy) any extensively tested and recommended algorithms by yourself either.

I have already seen this question, and as far as I understand, the main problem with implementing things yourself is that you will probably remain vulnerable to a host of side-channel attacks.

But suppose I have already implemented AES (just for fun and as a learning experience). What if I now use that implementation for simply encrypting files locally (and then perhaps back them up on the cloud or on removable media)? Since nobody other than me would be using the implementation, most of the side channel attacks would not apply. For instance, since no attacker can request an encryption/decryption (the way it works with a server), no timing attack can be carried out. Would this scenario be sufficiently secure?

In other words would using my own implementation of AES provide security for data at rest or will using it still be a stupid idea?

PyCrypto based encrypted Property class for Google App Engine standard – is this AES implementation secure

I have a need to encrypt OAuth access and refresh tokens stored in the Google Cloud Datastore.

The goal here is to ensure that if the Datastore entities are accessed independently of the code, the OAuth tokens will be encrypted and thus unusable.

This is not intended to protect against situations where both the code and Datastore are exposed together.

To securely store the data, I have leveraged PyCrypto’s AES implementation, and created a custom property type that automatically encrypts/decrypts the properties when accessing them.

The logic is as follows:

  • To store – I generate a random initialization vector, encrypt the data, then I base64 encode both the initialization vector and the encrypted data, and store them together in a text property.

  • To retrieve – I fetch the text data, slice off the base64 encoded initialization vector, and proceed to decode then decrypt the remaining data.

In addition to securing my own application, I am considering publishing the details and distributing the relevant code for others, so I want to ensure I have a secure or "correct" implementation of this functionality

(Note I have stripped out App Engine specific code and just included relevant encryption code here, for simplicity. The actual implementation allows it to be dropped into existing Datastore models in a backwards-compatible fashion).

 from Crypto.Cipher import AES   from Crypto import Random  from base64 import b64encode,b64decode  from meta_secure import aes_key #aes_key is a 32 digit alphanumeric string (GUID)    #encryption scheme  def encrypt_value(value):     rand = Random.new()     init_vector = rand.read(16)     aes = AES.new(aes_key,AES.MODE_CFB,init_vector)     encrypted = b64encode(aes.encrypt(value))     return '%s%s'%(b64encode(init_vector),encrypted)    def decrypt_value(value):     init_vector = b64decode(value[:24])     aes = AES.new(aes_key,AES.MODE_CFB,init_vector)     decrypted = aes.decrypt(b64decode(value[24:]))     return decrypted     

Have I used PyCrypto and AES correctly for the goal as stated above?

Addressing SSL/TLS vulnerabilities in IoT Device client side implementation

I understand SSL/TLS is the most commonly data transmission protocol for a secured communication. I need to implement the same in one of the IoT device (ARM® Cortex®-M4 Core at 80 MHz). This will be TLS Client implementation.

Since the device is a small scale device, I am looking for a light weight SSL Library (bearSSL, mbedSSL, ..) to use.

Device needs to store as well as transmit data to server; and I need to ensure a secured communication with data confidentiality and integrity; avoiding any possible attack (MITM,..).

However as I got to read, there are vulnerabilities/pitfalls in SSL/TLS also, does just using a right library will ensure addressing them? Or there are specific things I need to do in my code implementation to address them?

Like right ciphersuite selection; generating and securely storing the keys (key management); …

request for some insight into this.

Data structure implementation of MST (Minimum spanning tree) through Fibonacci heaps

How can a fibonacci heap store the information needed by the algorithm? In order to achieve good efficiency, when would you run the Consolidate routine?

Algorithm :

MST(G) 2 T ← {} // set that will store the edges of the MST 3 for i ← 1..n 4 Vi ← {i} 5 Ei ← {(i, j) : j is a vertex and (i, j) is an edge of G} // set of all edges incident with vertex i 6 end for 7 while there is more than one set Vi 8 choose any Vi 9 extract minimum weight edge (u, v) from Ei 10 one of the endpoints u of this edge is in Vi ; let Vj be the set that contains the other endpoint v 11 if i 6= j then 12 T ← T ∪ {(u, v)} 13 combine Vi and Vj into Vi (destroying Vj ) 14 combine Ei and Ej into Ei (destroying Ej ) 15 end if 16 end while 17 return T 18 end MST 

Would you have to add any additional fields to nodes in the heaps or use any additional data structures?