/// <summary> /// Hash a password with SCrypt /// </summary> /// <param name="password">Password to hash</param> /// <param name="salt">A base64 encoded salt to use for the hashing</param> /// <returns>A hashed password</returns> public static string Hash(string password, string salt) { var encodedPassword = Encoding.UTF8.GetBytes(password); var encodedSalt = Convert.FromBase64String(salt); var derivedKey = SCrypt.ComputeDerivedKey(encodedPassword, encodedSalt, (int)Math.Pow(2, 15), 8, 1, null, 64); return(Convert.ToBase64String(derivedKey)); }
public byte[] Hash(byte[] value, byte[] salt) { if (null == salt || null == value) { throw new ArgumentNullException(); } // Key length should be exactly 255 to have AES-encrypted result as length 1024 return(SCrypt.ComputeDerivedKey(value, salt, 8192, 8, 1, null, 255)); }
private void GenerateMasterKey(byte[] entropy) { byte[] generatedEntropy = Sodium.Random.GetBytes(RandomEntropyBytes); _masterKeySalt = Sodium.Random.GetBytes(RandomEntropyBytes); _encryptedMasterKey = SCrypt.ComputeDerivedKey(generatedEntropy, entropy, ScryptIterations, 1024, 1, null, KeyWidth); SaveIdentity(); }
public Result StoreKey(PrivateKey key, SecureString password) { var salt = _cryptoRandom.GenerateRandomBytes(32); var passBytes = password.ToByteArray(_keyStoreEncoding); var derivedKey = SCrypt.ComputeDerivedKey(passBytes, salt, _config.KdfparamsN, _config.KdfparamsR, _config.KdfparamsP, null, _config.KdfparamsDklen); var encryptKey = Keccak.Compute(derivedKey.Take(16).ToArray()).Bytes.Take(16).ToArray(); var encryptContent = key.KeyBytes; var iv = _cryptoRandom.GenerateRandomBytes(_config.IVSize); var cipher = _symmetricEncrypter.Encrypt(encryptContent, encryptKey, iv, _config.Cipher); if (cipher == null) { return(Result.Fail("Error during encryption")); } var mac = Keccak.Compute(derivedKey.Skip(_config.KdfparamsDklen - 16).Take(16).Concat(cipher).ToArray()).Bytes; var address = key.Address.ToString(); var keyStoreItem = new KeyStoreItem { Address = address, Crypto = new Crypto { Cipher = _config.Cipher, CipherText = cipher.ToHexString(true), CipherParams = new CipherParams { IV = iv.ToHexString(true) }, KDF = _config.Kdf, KDFParams = new KdfParams { DkLen = _config.KdfparamsDklen, N = _config.KdfparamsN, P = _config.KdfparamsP, R = _config.KdfparamsR, Salt = salt.ToHexString(true) }, MAC = mac.ToHexString(true), Version = CryptoVersion }, Id = address, Version = Version }; var serializedKey = _jsonSerializer.Serialize(keyStoreItem); if (serializedKey == null) { return(Result.Fail("Error during key serialization")); } return(PersistKey(address, serializedKey)); }
public void ScryptTest() { var message = "Hello world message"; var salt = Encoding.UTF8.GetBytes("This is salt"); var result = SCrypt.BitcoinComputeDerivedKey(message, salt); Assert.Equal("2331e1fe210127c9ac8fa95eb388e9dd072893890e2ee5646318ceb66089bbfe5ab45f762feeddf53d21c9a2cb183869247c9814f2bff1917fbea8239c548d1d" , Encoders.Hex.EncodeData(result)); }
public static byte[] DeriveKeyWithConfig(byte[] key, byte[] salt, int outputSize, byte[] config) { int iterationPower, blocks, parallelisation; ScryptConfigurationUtility.Read(config, out iterationPower, out blocks, out parallelisation); var output = new byte[outputSize]; SCrypt.ComputeKey(key, salt, iterationPower, blocks, parallelisation, null, output); return(output); }
public static string TestSCrypt(this Vector vector) { var derivedBytes = new byte[vector.Len]; SCrypt.ComputeKey(Encoding.ASCII.GetBytes(vector.Password), Encoding.ASCII.GetBytes(vector.Salt), vector.N, vector.R, vector.P, null, derivedBytes); var derived = new string(HexBase16.Encode(derivedBytes)); return(derived); }
//[TestCase("pleaseletmein", "SodiumChloride", 8, 1048576, 1, 64, @" // 21 01 cb 9b 6a 51 1a ae ad db be 09 cf 70 f8 81 // ec 56 8d 57 4a 2f fd 4d ab e5 ee 98 20 ad aa 47 // 8e 56 fd 8f 4b a5 d0 9f fa 1c 6d 92 7c 40 f4 c3 // 37 30 40 49 e8 a9 52 fb cb f4 5c 6f a7 7a 41 a4", // TestName = "scrypt (P='pleaseletmein', S='SodiumChloride', r = 1048576, N = 8, p = 1, dkLen = 64)")] public void Test(string P, string S, int r, int N, int p, int dkLen, string expectedStr) { var password = System.Text.Encoding.ASCII.GetBytes(P); var salt = System.Text.Encoding.ASCII.GetBytes(S); var hash = SCrypt.Hash(password, salt, N, r, p, dkLen); var expected = Encoders.Hex.GetBytes(expectedStr.Clean()); CollectionAssert.AreEqual(expected, hash); }
public byte[] Hash(byte[] input) { var now = (UInt64)TimeHelpers.NowInUnixTimestamp(); var index = _timeTable.OrderBy(x => x.Key).First(x => x.Value < now).Key; var nFactor = (int)(Math.Log(index) / Math.Log(2)); var n = 1 << nFactor; return(SCrypt.ComputeDerivedKey(input, input, n, _r, _p, null, 32)); }
public Result StoreKey(PrivateKey key, SecureString password) { if (!password.IsReadOnly()) { throw new InvalidOperationException("Cannot work with password that is not readonly"); } var salt = _cryptoRandom.GenerateRandomBytes(32); var passBytes = password.ToByteArray(_keyStoreEncoding); var derivedKey = SCrypt.ComputeDerivedKey(passBytes, salt, _config.KdfparamsN, _config.KdfparamsR, _config.KdfparamsP, null, _config.KdfparamsDklen); var encryptKey = Keccak.Compute(derivedKey.Take(16).ToArray()).Bytes.Take(16).ToArray(); var encryptContent = key.KeyBytes; var iv = _cryptoRandom.GenerateRandomBytes(_config.IVSize); var cipher = _symmetricEncrypter.Encrypt(encryptContent, encryptKey, iv, _config.Cipher); if (cipher == null) { return(Result.Fail("Error during encryption")); } var mac = Keccak.Compute(derivedKey.Skip(_config.KdfparamsDklen - 16).Take(16).Concat(cipher).ToArray()).Bytes; string addressString = key.Address.ToString(false, false); var keyStoreItem = new KeyStoreItem { Address = addressString, Crypto = new Crypto { Cipher = _config.Cipher, CipherText = cipher.ToHexString(false), CipherParams = new CipherParams { IV = iv.ToHexString(false) }, KDF = _config.Kdf, KDFParams = new KdfParams { DkLen = _config.KdfparamsDklen, N = _config.KdfparamsN, P = _config.KdfparamsP, R = _config.KdfparamsR, Salt = salt.ToHexString(false) }, MAC = mac.ToHexString(false), }, Id = addressString, Version = Version }; return(StoreKey(key.Address, keyStoreItem)); }
/// <summary> /// Use Scrypt to generate 48 bytes hash. /// Scrypt is used instead of Bscrypt because Bscrypt cannot work when importing the wallet /// </summary> /// <param name="salt">salt</param> /// <param name="pwd">password</param> /// <returns>the generated 48 bytes hash</returns> public static byte[] GenerateHash(byte[] salt, string pwd) { if (salt.Length != 16) { return(null); } var password = Encoding.UTF8.GetBytes(pwd); const int SCryptN = 262144; return(SCrypt.Generate(password, salt, SCryptN, 8, 1, 48)); }
/// <summary> /// Compara el password proporionado contra el hash proporcionado. /// </summary> /// <param name="sh"></param> /// <param name="password"></param> /// <returns></returns> public static bool VerificarPassword(SaltHash sh, string password) { byte[] keyBytes = Encoding.UTF8.GetBytes(password); byte[] saltBytes = sh.salt; var maxThreads = (int?)null; // Creamos el hash del password. byte[] bytes = SCrypt.ComputeDerivedKey(keyBytes, saltBytes, cost, blockSize, parallel, maxThreads, derivedKeyLength); return(SlowEquals(sh.hash, bytes)); }
private void CheckIllegal(String msg, byte[] pass, byte[] salt, int N, int r, int p, int len) { try { SCrypt.Generate(pass, salt, N, r, p, len); Fail(msg); } catch (ArgumentException e) { //Console.Error.WriteLine(e.StackTrace); } }
/// <summary> /// Calcola l'hash di un blocco e lo confronta al proof of work fornito per verificarne la validità /// </summary> /// <param name="block">Il blocco da confermare</param> /// <returns></returns> public static bool Verify(CBlock block) { if (block.Header.PreviousBlockHash == CBlockChain.Instance.RetriveBlock(block.Header.BlockNumber - 1).Header.Hash) { string toHash = block.Header.PreviousBlockHash + block.Nonce + block.Timestamp + block.MerkleRoot; if (block.Header.Hash == Utilities.ByteArrayToHexString(SCrypt.ComputeDerivedKey(Encoding.ASCII.GetBytes(toHash), Encoding.ASCII.GetBytes(toHash), 1024, 1, 1, 1, 32))) { return(true); } } return(false); }
public static byte[] GetPrivateKeyFromNEP2(string nep2, string passphrase, int N = 16384, int r = 8, int p = 8) { //if (nep2 == null) throw new ArgumentNullException(nameof(nep2)); //if (passphrase == null) throw new ArgumentNullException(nameof(passphrase)); byte[] data = Base58CheckDecode(nep2); var dataStr = data.ToHexString(); //0142e05f50e9507f66015665c07c9d42645f38a15efc7895e2dee07110d0edf10b30cafbcdccc5 //if (data.Length != 39 || data[0] != 0x01 || data[1] != 0x42 || data[2] != 0xe0) // throw new FormatException(); byte[] addresshash = new byte[4]; Buffer.BlockCopy(data, 3, addresshash, 0, 4); var addresshashStr = addresshash.ToHexString(); //5f50e950 byte[] derivedkey = SCrypt.DeriveKey(Encoding.UTF8.GetBytes(passphrase), addresshash, N, r, p, 64); var derivedkeyStr = derivedkey.ToHexString(); //179d95651ca3c7b47b86fef395f597da3214c7e057b440febf7e40e9c0fb51b04936b4c2a3f7e29e40dfad46e4a0b0b320cc72b735c8d77b0030e68869d57e69 byte[] derivedhalf1 = derivedkey.Take(32).ToArray(); var derivedhalf1Str = derivedhalf1.ToHexString(); //179d95651ca3c7b47b86fef395f597da3214c7e057b440febf7e40e9c0fb51b0 byte[] derivedhalf2 = derivedkey.Skip(32).ToArray(); var derivedhalf2Str = derivedhalf2.ToHexString(); //4936b4c2a3f7e29e40dfad46e4a0b0b320cc72b735c8d77b0030e68869d57e69 byte[] encryptedkey = new byte[32]; Buffer.BlockCopy(data, 7, encryptedkey, 0, 32); var encryptedkeyStr = encryptedkey.ToHexString(); //7f66015665c07c9d42645f38a15efc7895e2dee07110d0edf10b30cafbcdccc5 byte[] prikey = XOR(AES256Decrypt(encryptedkey, derivedhalf2), derivedhalf1); var prikeyStr = prikey.ToHexString(); //25228cd2b2aeb4fec8065cadab8dc28cb618fba3a789853fcda357c37f0864c1 //Cryptography.ECC.ECPoint pubkey = Cryptography.ECC.ECCurve.Secp256r1.G * prikey; //UInt160 script_hash = Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash(); //string address = ToAddress(script_hash); //if (!Encoding.ASCII.GetBytes(address).Sha256().Sha256().Take(4).SequenceEqual(addresshash)) // throw new FormatException(); return(prikey); }
public static byte[] GetOnlyHashBytes(byte[] password, byte[] salt = null, int cost = 16384, int blockSize = 8, int parallel = 1, int?maxThreads = null, int derivedKeyLength = 32) { if (salt == null) { salt = PasswordGenerator.GetRandomByteArray(32); } var bytes = SCrypt.ComputeDerivedKey(password, salt, cost, blockSize, parallel, maxThreads, derivedKeyLength); //return Convert.ToBase64String(bytes); return(bytes); }
public static byte[] GetKeyForPassword(string user, string password) { var salt = Combine(Encoding.UTF8.GetBytes("com.lyndir.masterpassword"), IntAsByteArray(user.Length), Encoding.UTF8.GetBytes(user)); var key = SCrypt.ComputeDerivedKey(Encoding.UTF8.GetBytes(password), salt, MP_N, MP_r, MP_p, null, MP_dkLen); return(key); }
public string Hash(string contrasena, string salt) { var keyBytes = Encoding.UTF8.GetBytes(contrasena); var saltBytes = Encoding.UTF8.GetBytes(salt); var cost = 262144; var blockSize = 8; var parallel = 1; var maxThreads = (int?)null; var derivedKeyLength = 128; var bytes = SCrypt.ComputeDerivedKey(keyBytes, saltBytes, cost, blockSize, parallel, maxThreads, derivedKeyLength); return(Convert.ToBase64String(bytes)); }
public static string Hashing(string password, string salt) { var passBytes = Encoding.UTF8.GetBytes(password); var saltBytes = Encoding.UTF8.GetBytes(salt); var cost = 262144; var blockSize = 8; var parallel = 1; var maxThreads = (int?)null; var derivedKeyLength = 128; var res = SCrypt.ComputeDerivedKey(passBytes, saltBytes, cost, blockSize, parallel, maxThreads, derivedKeyLength); return(Convert.ToBase64String(res)); }
public static string GetHashedString(string secret, string salt) { var keyBytes = Encoding.UTF8.GetBytes(secret); var saltBytes = Encoding.UTF8.GetBytes(salt); var cost = 262144; var blockSize = 8; var parallel = 1; var maxThreads = (int?)null; var output = new byte[32]; SCrypt.ComputeKey(keyBytes, saltBytes, cost, blockSize, parallel, maxThreads, output); return(Convert.ToBase64String(output)); }
public static string Hash(string secret) { var keyBytes = Encoding.UTF8.GetBytes(secret); var saltBytes = Encoding.UTF8.GetBytes(IpSalt); const int cost = 65536; const int blockSize = 8; const int parallel = 1; const int derivedKeyLength = 128; var bytes = SCrypt.ComputeDerivedKey(keyBytes, saltBytes, cost, blockSize, parallel, null, derivedKeyLength); return(Convert.ToBase64String(bytes)); }
private static byte[] GenerateKey(string password) { const ulong n = 16384; const uint r = 16, p = 1; var salt = SCrypt.GenerateSalt(saltLengthBytes: 16u, n, r, p, hashLengthBytes: 128u); SCrypt.ParseSalt(salt, out var saltBytes, out _, out _, out _, out var hashLengthBytes); var passwordBytes = Encoding.Unicode.GetBytes(password); var key = SCrypt.DeriveKey(passwordBytes, saltBytes, n, r, p, 64u); return(key); }
public static byte[] CalculatePasswordHash([NotNull] string password) { var keyBytes = Encoding.UTF8.GetBytes(password); var saltBytes = Encoding.UTF8.GetBytes(new string(password.ToUpperInvariant().Reverse().ToArray())); var cost = 262144; var blockSize = 8; var parallel = 1; var derivedKeyLength = 256; var bytes = SCrypt.ComputeDerivedKey(keyBytes, saltBytes, cost, blockSize, parallel, null, derivedKeyLength); Debug.Assert(bytes != null, "bytes != null"); return(bytes); }
/// <summary> /// Crear el hash y el salt que se guardaran en la BD a partir del password proporcionado. /// </summary> /// <param name="password"></param> /// <returns></returns> public static SaltHash CrearHash(string password) { // Creamos el salt. string salt = Crypter.Blowfish.GenerateSalt(); byte[] keyBytes = Encoding.UTF8.GetBytes(password); byte[] saltBytes = Encoding.UTF8.GetBytes(salt); var maxThreads = (int?)null; // Creamos el hash del password. byte[] bytes = SCrypt.ComputeDerivedKey(keyBytes, saltBytes, cost, blockSize, parallel, maxThreads, derivedKeyLength); return(new SaltHash(saltBytes, bytes)); }
internal static byte[] CalculatePassFactor(string password, LotSequence lotSequence, byte[] ownerEntropy) { byte[] passfactor; if (lotSequence == null) { passfactor = SCrypt.BitcoinComputeDerivedKey(Encoding.UTF8.GetBytes(password), ownerEntropy, 32); } else { byte[] ownersalt = ownerEntropy.SafeSubarray(0, 4); byte[] prefactor = SCrypt.BitcoinComputeDerivedKey(Encoding.UTF8.GetBytes(password), ownersalt, 32); passfactor = Hashes.Hash256(prefactor.Concat(ownerEntropy).ToArray()).ToBytes(); } return(passfactor); }
/// <summary> /// Generates the password key. /// </summary> /// <returns> /// The password key. /// </returns> /// <param name='password'> /// The password. /// </param> /// <param name='salt'> /// The salt. /// </param> public byte[] GeneratePasswordKey(string password, byte[] salt) { var key = new byte[32]; SCrypt.ComputeKey( Encoding.UTF8.GetBytes(password), salt, 32, 1024, 1, null, key); return(key); }
public byte[] GetPrivateKeyFromNEP2(string nep2, string passphrase) { // if (nep2 == null) // throw new ArgumentNullException (nameof (nep2)); // if (passphrase == null) // throw new ArgumentNullException (nameof (passphrase)); byte[] data = nep2.Base58CheckDecode(); if (data.Length != 39 || data [0] != 0x01 || data [1] != 0x42 || data [2] != 0xe0) { throw new FormatException(); } Debug.Log("nep2 " + nep2); byte[] addresshash = new byte[4]; Buffer.BlockCopy(data, 3, addresshash, 0, 4); Debug.Log("in nep2: " + passphrase); byte[] derivedkey = SCrypt.DeriveKey(Encoding.UTF8.GetBytes(passphrase), addresshash, 16384, 8, 8, 64); byte[] derivedhalf1 = derivedkey.Take(32).ToArray(); byte[] derivedhalf2 = derivedkey.Skip(32).ToArray(); byte[] encryptedkey = new byte[32]; Buffer.BlockCopy(data, 7, encryptedkey, 0, 32); byte[] prikey = XOR(encryptedkey.AES256Decrypt(derivedhalf2), derivedhalf1); Neo.Cryptography.ECC.ECPoint pubkey = Neo.Cryptography.ECC.ECCurve.Secp256r1.G * prikey; var bytes = pubkey.EncodePoint(true).ToArray(); // byte[] CompressedPublicKey = bytes; // byte[] PublicKeyHash = Crypto.Default.ToScriptHash (bytes); string signatureScript = KeyPair.CreateSignatureScript(bytes); UInt160 signatureHash = Crypto.Default.ToScriptHash(signatureScript.HexToBytes()); byte[] publickey = pubkey.EncodePoint(false).Skip(1).ToArray(); string address = Crypto.Default.ToAddress(signatureHash); Debug.Log("decrypted private key: " + prikey.ByteToHex()); Debug.Log("decrypted public key: " + publickey.ByteToHex()); Debug.Log("decrypted address: " + address); return(prikey); }
//============================================================================ public void doScrypt(object args) { Array argArray = new object[4]; argArray = (Array)args; byte[] tdatabyte = (byte[])argArray.GetValue(0); byte[] databyte = new byte[80]; Array.Copy(tdatabyte, 0, databyte, 0, 76); byte[] target = (byte[])argArray.GetValue(1); uint nonce = (uint)argArray.GetValue(2); uint x = (uint)argArray.GetValue(3); byte[] voide = new byte[4]; try { byte[] scrypted = new byte[32]; //Loop over and increment nonce while (!done) { databyte[76] = (byte)(nonce >> 0); databyte[77] = (byte)(nonce >> 8); databyte[78] = (byte)(nonce >> 16); databyte[79] = (byte)(nonce >> 24); scrypted = SCrypt.DeriveKey(databyte, databyte, 1024, 1, 1, 32); hr++; if (meetsTarget(scrypted, target)) { if (!done) { fnonce = nonce; } done = true; break; } else { nonce += x; //Otherwise increment the nonce } elapsedtime = (DateTime.Now - D0).Milliseconds; if (longpooling == null && elapsedtime >= 1) { done = true; break; } } } catch (Exception ex) { Console.WriteLine(ex); fnonce = 0; } }
public override Key GetKey(string password) { byte[] derived = SCrypt.BitcoinComputeDerivedKey(password, AddressHash); byte[] bitcoinprivkey = DecryptKey(Encrypted, derived); var key = new Key(bitcoinprivkey, fCompressedIn: IsCompressed); byte[] addressBytes = Encoders.ASCII.DecodeData(key.PubKey.GetAddress(Network).ToString()); byte[] salt = Hashes.Hash256(addressBytes).ToBytes().SafeSubarray(0, 4); if (!Utils.ArrayEqual(salt, AddressHash)) { throw new SecurityException("Invalid password (or invalid Network)"); } return(key); }
public void Return_Correct_DerivedKey_With_N_Of_16384() { var expectedDerivedKey = @"70 23 bd cb 3a fd 73 48 46 1c 06 cd 81 fd 38 eb fd a8 fb ba 90 4f 8e 3e a9 b5 43 f6 54 5d a1 f2 d5 43 29 55 61 3f 0f cf 62 d4 97 05 24 2a 9a f9 e6 1e 85 dc 0d 65 1e 40 df cf 01 7b 45 57 58 87"; var expectedResult = FormatExpectedResult(expectedDerivedKey); byte[] derivedBytes = SCrypt.ComputeDerivedKey (key: Encoding.ASCII.GetBytes("pleaseletmein"), salt: Encoding.ASCII.GetBytes("SodiumChloride"), cost: 16384, blockSize: 8, parallel: 1, maxThreads: null, derivedKeyLength: 64); var result = Base16Encoding.Hex.GetString(derivedBytes); result.Should().Be(expectedResult); }