private static string ScryptEncoder(string secret, string salt, int cost = 16384, int blockSize = 8, int parallel = 1, int?maxThreads = null, int derivedKeyLengthInBytes = 32) { var keyBytes = Encoding.UTF8.GetBytes(secret); byte[] saltBytes; if (string.IsNullOrEmpty(salt)) { saltBytes = PasswordGenerator.GetRandomByteArray(32); } else { saltBytes = Encoding.UTF8.GetBytes(salt); } var bytes = SCrypt.ComputeDerivedKey(keyBytes, saltBytes, cost, blockSize, parallel, maxThreads, derivedKeyLengthInBytes); //return Convert.ToBase64String(bytes); string maxThreadsString; if (maxThreads == null) { maxThreadsString = "0"; } else { maxThreadsString = maxThreads.ToString(); } string hash = "scrypt2:" + cost.ToString() + ":" + blockSize.ToString() + ":" + parallel.ToString() + ":" + maxThreadsString + ":" + derivedKeyLengthInBytes.ToString() + ":" + ByteArrayToString(saltBytes) + ":" + ByteArrayToString(bytes); return(hash); }
public static bool ComparePasswordWithHash(string password, string scryptHashString) { var scryptArray = scryptHashString.Split(":"); if (scryptArray.Length < 8) { return(false); } if (scryptArray[0] != "scrypt2") { return(false); } var saltBytes = StringToByteArray(scryptArray[6]); var hashBytes = StringToByteArray(scryptArray[7]); int cost = Convert.ToInt32(scryptArray[1]); int blockSize = Convert.ToInt32(scryptArray[2]); int parallel = Convert.ToInt32(scryptArray[3]); int?maxThreads = Convert.ToInt32(scryptArray[4]); int derivedKeyLength = Convert.ToInt32(scryptArray[5]); if (maxThreads == 0) { maxThreads = null; } var result = SCrypt.ComputeDerivedKey(Encoding.UTF8.GetBytes(password), saltBytes, cost, blockSize, parallel, maxThreads, derivedKeyLength); if (ByteArrayToString(result) == scryptArray[7]) { return(true); } return(false); }
public static byte[] GetOnlyHashBytes(byte[] password, CipherResult sO) { var bytes = SCrypt.ComputeDerivedKey(password, sO.Salt, sO.Cost, sO.BlockSize, sO.Parallel, null, sO.KeySizeInBytes); //return Convert.ToBase64String(bytes); return(bytes); }
public byte[] Enscrypt(byte[] salt, TimeSpan duration, out int iterations) { if (duration <= TimeSpan.FromSeconds(0)) { throw new ArgumentOutOfRangeException("duration", "duration must be greater than 0"); } var key = Password == "" ? new byte[] { } : CryptographicBuffer.ConvertStringToBinary(Password, BinaryStringEncoding.Utf8).ToArray(); var endTime = DateTime.Now + duration; salt = salt ?? new byte[0]; var result = salt = SCrypt.ComputeDerivedKey(key, salt, 512, 256, 1, null, 32); iterations = 1; while (DateTime.Now < endTime) { iterations++; salt = SCrypt.ComputeDerivedKey(key, salt, 512, 256, 1, null, 32); result.Xor(salt); } return(result); }
static uint256 GetPoWHash(BlockHeader header) { var headerBytes = header.ToBytes(); var h = SCrypt.ComputeDerivedKey(headerBytes, headerBytes, 1024, 1, 1, null, 32); return(new uint256(h)); }
private static string Hash(string password, byte[] salt) { var digest = SCrypt.ComputeDerivedKey(Encoding.UTF8.GetBytes(password), salt, Cost, BlockSize, Parallel, MaxThreads, DerivedKeyLength); return(Convert.ToBase64String(digest)); }
/// <summary> /// Initializes the state of Key Pair assuming the given Passphrase includes a higher then 100-bit /// entropy score using ZXCVBN analysis. Returns false if the Passphrase does not pass this test, and the /// object is not initialized as a result. Returns true with the Key Pair is ready for use. /// </summary> /// <param name="EMail"></param> /// <param name="Passphrase"></param> /// <returns>true if OK/Initialized, false if BAD PASSPHRASE</returns> public bool Initialize(string EMail, string Passphrase) { if (string.IsNullOrWhiteSpace(EMail)) { throw new ArgumentNullException("EMail"); } if (string.IsNullOrWhiteSpace(Passphrase)) { throw new ArgumentNullException("Passphrase"); } if ((int)ScorePotentialPassphrase(Passphrase).Entropy < 100) { return(false); } byte[] mangledPWD = Blake2S.ComputeHash(new UTF8Encoding().GetBytes(Passphrase.Trim())); _Secret = SCrypt.ComputeDerivedKey(mangledPWD, new UTF8Encoding().GetBytes(EMail.Trim()), 131072, 8, 1, 1, 32); _SecretChecksum = ComputeChecksum(_Secret); _PublicID = GeneratePublicIDFromSecret(_Secret, out _PublicChecksum); //PROTECT MEMORY AFTER LAST USE OF _Secret ProtectedMemory.Protect(_Secret, MemoryProtectionScope.SameProcess); _Public = GetBytesFromPublicKey(_PublicID); return(true); }
public static AesKeyIvPair GenKeyAndIv( byte[] pass, byte[] salt, CryptConfigFileHelperScryptParameters scryptParameters = null) { if (scryptParameters == null) { scryptParameters = new CryptConfigFileHelperScryptParameters(); } byte[] passHash; byte[] saltHash; using (var mySha256 = new SHA256Managed()) { passHash = mySha256.ComputeHash(pass); saltHash = mySha256.ComputeHash(salt); } var derivedKey = SCrypt.ComputeDerivedKey( passHash, saltHash, scryptParameters.Cost, scryptParameters.BlockSize, scryptParameters.Parallel, 1, 48 ); var initKey = new byte[32]; var iv = new byte[16]; Array.Copy(derivedKey, 0, initKey, 0, 32); Array.Copy(derivedKey, 32, iv, 0, 16); return(new AesKeyIvPair() { Iv = iv, Key = initKey }); }
public override uint256 GetPoWHash() { var headerBytes = this.ToBytes(); var h = SCrypt.ComputeDerivedKey(headerBytes, headerBytes, 1024, 1, 1, null, 32); return(new uint256(h)); }
internal static byte[] GenerateSteamParentalHash(byte[] password, byte[] salt, byte hashLength, ESteamParentalAlgorithm steamParentalAlgorithm) { if ((password == null) || (salt == null) || (hashLength == 0) || !Enum.IsDefined(typeof(ESteamParentalAlgorithm), steamParentalAlgorithm)) { ASF.ArchiLogger.LogNullError(nameof(password) + " || " + nameof(salt) + " || " + nameof(hashLength) + " || " + nameof(steamParentalAlgorithm)); return(null); } switch (steamParentalAlgorithm) { case ESteamParentalAlgorithm.Pbkdf2: using (HMACSHA1 hmacAlgorithm = new HMACSHA1(password)) { return(Pbkdf2.ComputeDerivedKey(hmacAlgorithm, salt, SteamParentalPbkdf2Iterations, hashLength)); } case ESteamParentalAlgorithm.SCrypt: return(SCrypt.ComputeDerivedKey(password, salt, SteamParentalSCryptIterations, SteamParentalSCryptBlocksCount, 1, null, hashLength)); default: ASF.ArchiLogger.LogGenericError(string.Format(Strings.WarningUnknownValuePleaseReport, nameof(steamParentalAlgorithm), steamParentalAlgorithm)); return(null); } }
public static string HashBlock(CBlock block) { string toHash = block.Header.PreviousBlockHash + block.Nonce + block.Timestamp + block.MerkleRoot; //si concatenano vari parametri del blocco TODO: usare i parmetri giusti, quelli usati qua sono solo per dimostrazione e placeholder return(Utilities.ByteArrayToHexString( SCrypt.ComputeDerivedKey( Encoding.ASCII.GetBytes(toHash), Encoding.ASCII.GetBytes(toHash), 1024, 1, 1, 1, 32) )); //calcola l'hash secondo il template di scrypt usato da litecoin }
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)); }
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)); }
/// <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)); }
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 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> /// 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)); }
/// <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[] 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 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)); }
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 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 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); }
/// <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)); }
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); }
protected byte[] Scrypt(byte[] masterKeySalt, byte[] mpBytes) { try { return(SCrypt.ComputeDerivedKey(mpBytes, masterKeySalt, MP_N, MP_r, MP_p, null, MP_dkLen)); } catch (Exception x) { //logger.bug(e); todo log return(null); } finally { Fill(mpBytes, (byte)0); } }
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); }
public void Return_Correct_DerivedKey_With_N_Of_1024() { var expectedDerivedKey = @"fd ba be 1c 9d 34 72 00 78 56 e7 19 0d 01 e9 fe 7c 6a d7 cb c8 23 78 30 e7 73 76 63 4b 37 31 62 2e af 30 d9 2e 22 a3 88 6f f1 09 27 9d 98 30 da c7 27 af b9 4a 83 ee 6d 83 60 cb df a2 cc 06 40"; var expectedResult = FormatExpectedResult(expectedDerivedKey); byte[] derivedBytes = SCrypt.ComputeDerivedKey (key: Encoding.ASCII.GetBytes("password"), salt: Encoding.ASCII.GetBytes("NaCl"), cost: 1024, blockSize: 8, parallel: 16, maxThreads: null, derivedKeyLength: 64); var result = Base16Encoding.Hex.GetString(derivedBytes); result.Should().Be(expectedResult); }
public void Return_Correct_DerivedKey_With_N_Of_16() { var expectedDerivedKey = @"77 d6 57 62 38 65 7b 20 3b 19 ca 42 c1 8a 04 97 f1 6b 48 44 e3 07 4a e8 df df fa 3f ed e2 14 42 fc d0 06 9d ed 09 48 f8 32 6a 75 3a 0f c8 1f 17 e8 d3 e0 fb 2e 0d 36 28 cf 35 e2 0c 38 d1 89 06"; var expectedResult = FormatExpectedResult(expectedDerivedKey); byte[] derivedBytes = SCrypt.ComputeDerivedKey (key: Encoding.ASCII.GetBytes(string.Empty), salt: Encoding.ASCII.GetBytes(string.Empty), cost: 16, blockSize: 1, parallel: 1, maxThreads: null, derivedKeyLength: 64); var result = Base16Encoding.Hex.GetString(derivedBytes); result.Should().Be(expectedResult); }