//Admin Hashing public static void AdminCreatePasswordHash(string adminMail, string password, out byte[] adminMailHash, out byte[] adminPasswordHash, out byte[] passwordSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = hmac.Key; adminPasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); adminMailHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(adminMail)); } }
private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt) { if (password == null) { throw new ArgumentNullException("password"); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentException("Value cannot be empty or whitespace only string.", "password"); } if (storedHash.Length != 64) { throw new ArgumentException("Invalid length of password hash (64 bytes expected).", "passwordHash"); } if (storedSalt.Length != 128) { throw new ArgumentException("Invalid length of password salt (128 bytes expected).", "passwordHash"); } using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt)) { var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); for (int i = 0; i < computedHash.Length; i++) { if (computedHash[i] != storedHash[i]) { return(false); } } } return(true); }
public static string Encode(string publicKey, int choice = 2) { byte[] hashMessage = null; byte[] messageBytes = m_encoding.GetBytes(publicKey); switch (choice%6) { case 0: var hmacmd5 = new HMACMD5(m_keyBytes); hashMessage = hmacmd5.ComputeHash(messageBytes); break; case 1: var hmacripedmd160 = new HMACRIPEMD160(m_keyBytes); hashMessage = hmacripedmd160.ComputeHash(messageBytes); break; case 2: var hmacsha1 = new HMACSHA1(m_keyBytes); hashMessage = hmacsha1.ComputeHash(messageBytes); break; case 3: var hmacsha256 = new HMACSHA256(m_keyBytes); hashMessage = hmacsha256.ComputeHash(messageBytes); break; case 4: var hmacsha384 = new HMACSHA384(m_keyBytes); hashMessage = hmacsha384.ComputeHash(messageBytes); break; case 5: var hmacsha512 = new HMACSHA512(m_keyBytes); hashMessage = hmacsha512.ComputeHash(messageBytes); break; } return Convert.ToBase64String(hashMessage); }
static JsonWebToken() { HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>> { {JwtHashAlgorithm.RS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return sha.ComputeHash(value); } } }, {JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new HMACSHA384(key)) { return sha.ComputeHash(value); } } }, {JwtHashAlgorithm.HS512, (key, value) => { using (var sha = new HMACSHA512(key)) { return sha.ComputeHash(value); } } } }; }
public static string HMACSHA512(string key, string message) { using (var hasher = new crypto.HMACSHA512(Encoding.UTF8.GetBytes(key))) { return(hasher.ComputeHash(Encoding.UTF8.GetBytes(message)).ToHexString()); } }
void createPasswordHash(string password, out byte[] passHash, out byte[] passSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512()){ passSalt = hmac.Key; passHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); } }
public (byte[] passwordHash, byte[] passwordSalt) CreatePasswordHash(string password) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { return(hmac.ComputeHash(Encoding.UTF8.GetBytes(password)), hmac.Key); } }
//private async Task<IEnumerable<ExchangeOrderResult>> QueryClosedOrdersAsync(string symbol, string path) //{ // List<ExchangeOrderResult> orders = new List<ExchangeOrderResult>(); // JToken result = await MakeJsonRequestAsync<JToken>(path, null, await GetNoncePayloadAsync()); // //result = result["closed"]; // foreach (JProperty order in result) // { // orders.Add(ParseOrder(order.Name, order.Value)); // } // //if (exchangeSymbolToNormalizedSymbol.TryGetValue(symbol, out string normalizedSymbol)) // //{ // // foreach (JProperty order in result) // // { // // if (normalizedSymbol == null || order.Value["descr"]["pair"].ToStringInvariant() == normalizedSymbol.ToUpperInvariant()) // // { // // orders.Add(ParseOrder(order.Name, order.Value)); // // } // // } // //} // return orders; //} protected override async Task ProcessRequestAsync(IHttpWebRequest request, Dictionary <string, object> payload) { if (payload == null || PrivateApiKey == null || PublicApiKey == null || !payload.ContainsKey("nonce")) { await CryptoUtility.WritePayloadFormToRequestAsync(request, payload); } else { string nonce = payload["nonce"].ToStringInvariant(); payload.Remove("nonce"); string form = CryptoUtility.GetFormForPayload(payload); // nonce must be first on Kraken form = "nonce=" + nonce + (string.IsNullOrWhiteSpace(form) ? string.Empty : "&" + form); using (SHA256 sha256 = SHA256Managed.Create()) { string hashString = nonce + form; byte[] sha256Bytes = sha256.ComputeHash(hashString.ToBytesUTF8()); byte[] pathBytes = request.RequestUri.AbsolutePath.ToBytesUTF8(); byte[] sigBytes = new byte[sha256Bytes.Length + pathBytes.Length]; pathBytes.CopyTo(sigBytes, 0); sha256Bytes.CopyTo(sigBytes, pathBytes.Length); byte[] privateKey = System.Convert.FromBase64String(CryptoUtility.ToUnsecureString(PrivateApiKey)); using (System.Security.Cryptography.HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(privateKey)) { string sign = System.Convert.ToBase64String(hmac.ComputeHash(sigBytes)); request.AddHeader("API-Sign", sign); } } request.AddHeader("API-Key", CryptoUtility.ToUnsecureString(PublicApiKey)); await CryptoUtility.WriteToRequestAsync(request, form); } }
public static string CryptoSHA512(string TextToCryptograph) { var sha512 = new HMACSHA512(); byte[] passwordArray = System.Text.Encoding.Default.GetBytes(TextToCryptograph); return Convert.ToBase64String(sha512.ComputeHash(passwordArray)); }
public static void CreatePasswordHash(string username, string password, out byte[] passwordHash, out byte[] passwordSalt) { if (username == null || password == null) { throw new ArgumentNullException("Username or password"); } var email = new EmailAddressAttribute(); if (email.IsValid(username)) { username = $"{username.Substring(0, username.IndexOf('@'))}{key}"; } else { username = username + key; } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentException("Value cannot be empty or whitespace only string.", "password"); } using (var hmac = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = hmac.Key; passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password + username)); } }
private static bool VerifyHashedPassword(string password, byte[] hashToCheck, byte[] hashSalt) { if (password == null) { throw new ArgumentNullException("password"); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentException("Value cannot be null or whitespace.", "password"); } if (hashToCheck.Length != 64) { throw new ArgumentException("Password is hashed using HMACSHA512, hash length should be of 64 bytes", "hashToCheck"); } if (hashSalt.Length != 128) { throw new ArgumentException("Password is hashed using HMACSHA512, salt length should be of 128 bytes", "hashToCheck"); } using (var hmac = new System.Security.Cryptography.HMACSHA512(hashSalt)) { var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); for (int i = 0; i < computedHash.Length; i++) { if (computedHash[i] != hashToCheck[i]) { return(false); } } } return(true); }
protected override void ProcessRequest(HttpWebRequest request, Dictionary <string, object> payload) { if (payload == null || !payload.ContainsKey("nonce")) { PostPayloadToRequest(request, payload); } else { string nonce = payload["nonce"].ToString(); payload.Remove("nonce"); string form = GetFormForPayload(payload); // nonce must be first on Kraken form = "nonce=" + nonce + (string.IsNullOrWhiteSpace(form) ? string.Empty : "&" + form); using (SHA256 sha256 = SHA256Managed.Create()) { string hashString = nonce + form; byte[] sha256Bytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(hashString)); byte[] pathBytes = Encoding.UTF8.GetBytes(request.RequestUri.AbsolutePath); byte[] sigBytes = new byte[sha256Bytes.Length + pathBytes.Length]; pathBytes.CopyTo(sigBytes, 0); sha256Bytes.CopyTo(sigBytes, pathBytes.Length); byte[] privateKey = Convert.FromBase64String(CryptoUtility.SecureStringToString(PrivateApiKey)); using (System.Security.Cryptography.HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(privateKey)) { string sign = Convert.ToBase64String(hmac.ComputeHash(sigBytes)); request.Headers.Add("API-Sign", sign); } } request.Headers.Add("API-Key", CryptoUtility.SecureStringToString(PublicApiKey)); PostFormToRequest(request, form); } }
public bool VerificaSenhaHash(dynamic usuario) { if (usuario.SenhaString != null && !string.IsNullOrWhiteSpace(usuario.Senha)) { if (usuario.Senha.Lenght == 64 && usuario.Chave.Length == 128) { using (var hmac = new System.Security.Cryptography.HMACSHA512(usuario.Chave)) { var ComputedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(usuario.SenhaString)); for (int i = 0; i < ComputedHash.Length; i++) { if (ComputedHash[i] != usuario.Senha[i]) { return(false); } } return(true); } } else { return(false); } } else { return(false); } }
public byte[] Hash(byte[] key, byte[] plainText) { using (var hmac = new HMACSHA512(key)) { return hmac.ComputeHash(plainText); } }
public static byte[] HMACSHA512(byte[] key, byte[] data) { using (var hmac = new HMACSHA512(key)) { return hmac.ComputeHash(data); } }
// Computes a keyed hash for a source file and creates a target file with the keyed hash // prepended to the contents of the source file. public static void SignFile(byte[] key, String sourceFile, String destFile) { // Initialize the keyed hash object. using (HMACSHA512 hmac = new HMACSHA512(key)) { using (FileStream inStream = new FileStream(sourceFile, FileMode.Open)) { using (FileStream outStream = new FileStream(destFile, FileMode.Create)) { // Compute the hash of the input file. byte[] hashValue = hmac.ComputeHash(inStream); // Reset inStream to the beginning of the file. inStream.Position = 0; // Write the computed hash value to the output file. outStream.Write(hashValue, 0, hashValue.Length); // Copy the contents of the sourceFile to the destFile. int bytesRead; // read 1K at a time byte[] buffer = new byte[1024]; do { // Read from the wrapping CryptoStream. bytesRead = inStream.Read(buffer, 0, 1024); outStream.Write(buffer, 0, bytesRead); } while (bytesRead > 0); } } } }
private bool VerifyPasswordHash(string password, byte[] passwordSalt, byte[] passwordHash) { using HMACSHA512 hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt); byte[] computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); return(!(computedHash.Where((t, i) => t != passwordHash[i]).Any())); }
private static bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt) { if (password == null) { throw new ArgumentNullException("password"); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentException("Password Required", "password"); } if (storedHash.Length != 64) { throw new ArgumentException("Invalid Hash Length", "passwordHash"); } if (storedSalt.Length != 128) { throw new ArgumentException("Invalid Salt Length", "passwordHash"); } using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt)) { var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); for (int i = 0; i < computedHash.Length; i++) { if (computedHash[i] != storedHash[i]) { return(false); } } } return(true); }
public void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt) { using (var hamc = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = hamc.Key; passwordHash = hamc.ComputeHash(Encoding.UTF8.GetBytes(password)); } }
public void CreatePasswordHash(string password, out byte[] passwordHash) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { hmac.Key = Encoding.UTF8.GetBytes("2020eID"); passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); } }
public static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)//out : değişen keyword değişen arraya aktarılacak { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = hmac.Key; passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); } }
private void CreateHashAndSalt(string password, out byte[] passwordHash, out byte[] passwordSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = hmac.Key; passwordHash = hmac.ComputeHash(Encoding.ASCII.GetBytes(password)); } }
public static string ComputeSHA(string str, string key) { byte[] passwordBytes = ASCIIEncoding.ASCII.GetBytes(str); byte[] saltBytes = ASCIIEncoding.ASCII.GetBytes(key); var crypt = new HMACSHA512(saltBytes); return BitConverter.ToString(crypt.ComputeHash(passwordBytes)).Replace("-", ""); }
public void CreatePasswordHash(string password, out string passwordHash, out string passwordSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = Convert.ToBase64String(hmac.Key); passwordHash = Convert.ToBase64String(hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password))); } }
public string GenerateSHA512Signature(FormUrlEncodedContent request) { HMAC digester = new HMACSHA512(this.PrivateKeyBytes); StringBuilder hex = new StringBuilder(); byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(request.ReadAsStringAsync().Result); return BitConverter.ToString(digester.ComputeHash(requestBytes)).Replace("-", "").ToLower(); }
public byte[] HashingAMessageWithASecretKey(byte[] iterationNumberByte, byte[] userIdByte) { using (var hmac = new HMACSHA512(userIdByte)) { byte[] hash = hmac.ComputeHash(iterationNumberByte); return hash; } }
private void CreatePasswordHash(string password, User user) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { user.PasswordSalt = hmac.Key; user.PasswordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); } }
public static void CriarSenhaHash(string senha, out byte[] senhaHash, out byte[] senhaSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { senhaSalt = hmac.Key; senhaHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(senha)); } }
private static byte[] getHash(byte[] keyByte, byte[] messageBytes) { using (var hmacsha512 = new HMACSHA512(keyByte)) { Byte[] result = hmacsha512.ComputeHash(messageBytes); return result; } }
private bool verifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt)) { passwordSalt = hmac.Key; var computerHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); return(computerHash.SequenceEqual(passwordHash)); } }
public string Generate(string password) { byte[] msgByte = ASCIIEncoding.ASCII.GetBytes(password); HMACSHA512 hmac = new HMACSHA512(); byte[] hashMsg = hmac.ComputeHash(msgByte); return HttpServerUtility.UrlTokenEncode(hashMsg); }
private bool VerifyPasswordHash(string password, byte[] userPasswordHash, byte[] userPasswordSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512(userPasswordSalt)) { var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); return(computedHash.SequenceEqual(userPasswordHash)); } }
public static String Sign(HttpRequestMessage request, String secretKey) { String message = BuildMessage(request); HMACSHA512 hmac = new HMACSHA512(Convert.FromBase64String(secretKey)); byte[] signature = hmac.ComputeHash(encoding.GetBytes(message)); return Convert.ToBase64String(signature); }
public byte[] Hash(byte[] clearBytes) { using (var hmac = new HMACSHA512(_key)) { hmac.Initialize(); byte[] hashBytes = hmac.ComputeHash(clearBytes); return hashBytes; } }
/// <summary> /// Computes the mac sha512. /// </summary> /// <param name="storageKey">The storage key.</param> /// <param name="canonicalizedString">The canonicalized string.</param> /// <returns>The computed hash.</returns> internal static string ComputeMacSha512(StorageKey storageKey, string canonicalizedString) { byte[] dataToMAC = Encoding.UTF8.GetBytes(canonicalizedString); using (HMACSHA512 hmacsha1 = new HMACSHA512(storageKey.Key)) { return System.Convert.ToBase64String(hmacsha1.ComputeHash(dataToMAC)); } }
public static string SignString512(string stringToSign, string secretKey) { byte[] secretkeyBytes = Convert.FromBase64String(secretKey); byte[] inputBytes = Encoding.UTF8.GetBytes(stringToSign); using (var hmac = new HMACSHA512(secretkeyBytes)) { byte[] hashValue = hmac.ComputeHash(inputBytes); return System.Convert.ToBase64String(hashValue); } }
public static void CreatePasswordhash(string password, out byte[] passwordHash, out byte[] passwordSalt) { using (var hamc = new System.Security.Cryptography.HMACSHA512()) { //password salt به صورت key passwordSalt = hamc.Key; //پسورد رو هشش کن در اصطلاح کامپیوتش کن passwordHash = hamc.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); } }
public void HasheiaSenha(dynamic usuario) { if (usuario.SenhaString != null && !string.IsNullOrWhiteSpace(usuario.SenhaString)) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { usuario.Chave = hmac.Key; usuario.Senha = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(usuario.SenhaString)); } } }
private static string CreateSharedAccessToken(string id, string key, DateTime expiry) { using (var encoder = new HMACSHA512(Encoding.UTF8.GetBytes(key))) { var dataToSign = id + "\n" + expiry.ToString("O", CultureInfo.InvariantCulture); var hash = encoder.ComputeHash(Encoding.UTF8.GetBytes(dataToSign)); var signature = Convert.ToBase64String(hash); var encodedToken = $"uid={id}&ex={expiry:o}&sn={signature}"; return encodedToken; } }
private static string CreatePasswordHash(string password, out string Salt) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { var passwordSalt = hmac.Key; var passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); string base64StringPassword = Convert.ToBase64String(passwordHash); Salt = Convert.ToBase64String(passwordSalt); return(base64StringPassword); } }
public async Task <Tuple <byte[], byte[]> > CrearPasswordHash(string password) { byte[] passwordSalt, passwordHash; using (var hmac = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = hmac.Key; passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); } return(new Tuple <byte[], byte[]>(passwordHash, passwordSalt)); }
/// <summary> /// Creates a Sha512 HMAC hash of an inputted string. /// </summary> /// <param name="input">The string to create the hash from.</param> internal static string ComputeHmacSha512Hash(string input, string secret) { var utf8Encoding = new UTF8Encoding(); var inputBytes = utf8Encoding.GetBytes(input); var secretBytes = utf8Encoding.GetBytes(secret); var hmacSha512 = new HMACSHA512(secretBytes); var hash = hmacSha512.ComputeHash(inputBytes); return BitConverter.ToString(hash).Replace("-", ""); }
public async Task HasheiaSenhaAsync(Usuario usuario, string senha) { if (!string.IsNullOrEmpty(senha) && !string.IsNullOrWhiteSpace(senha)) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { usuario.Chave = hmac.Key; usuario.Senha = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(senha)); } } }
private (byte[], byte[]) CreatePasswordHash(string password) { byte[] passwordHash, passwordSalt; // hmac implements Idisposible using (var hmac = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = hmac.Key; passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password)); } return(passwordHash, passwordSalt); }
public static byte[] CreateHmac(byte[] iv, byte[] encryptedBytes, string password) { var data = encryptedBytes.Concat(iv).ToArray(); byte[] result; using (var hmacsha512 = new HMACSHA512(data)) { result = hmacsha512.ComputeHash(CreateKey(password, SaltType.Hmac)); } return result; }
public static void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512()) { passwordSalt = hmac.Key; passwordHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); //test //test2 //local //bug fix } }
public static string HmacSha512(string plainText, string key) { byte[] text_bytes = System.Text.Encoding.ASCII.GetBytes(plainText); byte[] key_bytes = System.Text.Encoding.ASCII.GetBytes(key); HMACSHA512 sha = new System.Security.Cryptography.HMACSHA512(key_bytes); byte[] sha_bytes = sha.ComputeHash(text_bytes); string sha_text = System.BitConverter.ToString(sha_bytes); sha_text = sha_text.Replace("-", ""); sha_text = sha_text.ToLower(); return(sha_text); }
private static string Gethmacsha512(Encoding encoding, string apiSecret, string url) { // doing the encoding var keyByte = encoding.GetBytes(apiSecret); string result; using (var hmacsha512 = new HMACSHA512(keyByte)) { hmacsha512.ComputeHash(encoding.GetBytes(url)); result = ByteToString(hmacsha512.Hash); } return result; }
/// <summary> /// Computes Hash /// </summary> /// <param name="messageKey"></param> /// <param name="message"></param> /// <returns></returns> public static string ComputeHash(string messageKey, string message) { var key = Encoding.UTF8.GetBytes(messageKey.ToUpper()); string hashString; using (var hmac = new HMACSHA512(key)) { var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message)); hashString = Convert.ToBase64String(hash); } return hashString; }
public bool VerifyPasswordHash(string password, byte[] storedHash, byte[] storedSalt) { using (var hmac = new System.Security.Cryptography.HMACSHA512(storedSalt)) { var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password)); if (!computedHash.SequenceEqual(storedHash)) { return(false); } } return(true); }
public string Sign(string secret, string verb, string url, string body, string nonce, string timestamp) { var msg = JsonConvert.SerializeObject( new[] { verb, url, body, nonce, timestamp}); var noncedMsg = Encoding.UTF8.GetBytes(nonce + msg); var sha256 = new SHA256Managed(); var hashedNoncedMessage = sha256.ComputeHash(noncedMsg); var toSign = Encoding.UTF8.GetBytes(url).Concat(hashedNoncedMessage); var hmac = new HMACSHA512(Encoding.UTF8.GetBytes(secret)); var hmacDigest = hmac.ComputeHash(toSign.ToArray()); return Convert.ToBase64String(hmacDigest); }
public static string Generate() { var hash = string.Empty; var shaHash = new HMACSHA512(Guid.NewGuid().ToByteArray()); var byteArray = HashGenerator.ByteArrayToString(shaHash.ComputeHash(Guid.NewGuid().ToByteArray())); foreach (var hashChar in byteArray) { hash += HashGenerator.IntToString(Convert.ToInt32(hashChar), chars); } return hash.Remove(25); }
private static string CreatePasswordHash(string password, string challengeString) { var passwordBuffer = Encoding.UTF8.GetBytes(password); // same as MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha512).CreateKey(passwordBuffer) in Windows Runtime. var provider = new HMACSHA512(passwordBuffer); // Same as CryptographicBuffer.DecodeFromHexString in Windows Runtime. var challengeBuffer = DecodeFromHexString(challengeString); // same as CryptographicEngine.Sign(provider, challengeBuffer) in Windows Runtime. var hmacBytes = provider.ComputeHash(challengeBuffer); // Same as CryptographicBuffer.EncodeToHexString in Windows Runtime. return EncodeToHexString(hmacBytes); }
public byte[] ProtectData(byte[] data, string label, params string[] context) { // Validate arguments if (data == null) throw new ArgumentNullException("data"); if (data.Length == 0) throw new ArgumentException("Value cannot me empty.", "data"); if (label == null) throw new ArgumentNullException("label"); if (string.IsNullOrWhiteSpace(label)) throw new ArgumentException("Value cannot be empty or whitespace only string.", "label"); // Get derived keys byte[] derivedEncKey, derivedSigKey; this.GetDerivedKeys(label, context, out derivedEncKey, out derivedSigKey); // Prepare AES-256 in CBC mode byte[] iv, encryptedData, signatureData; using (var aes = new RijndaelManaged()) { aes.Key = derivedEncKey; aes.BlockSize = 128; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; // Generate 16-byte IV and put it at beginning of output aes.GenerateIV(); iv = aes.IV; // Encrypt payload and write it to output using (var enc = aes.CreateEncryptor()) { encryptedData = enc.TransformFinalBlock(data, 0, data.Length); } } // Sign IV + encrypted data using (var mac = new HMACSHA512(derivedSigKey)) { var dataToSign = new byte[iv.Length + encryptedData.Length]; iv.CopyTo(dataToSign, 0); encryptedData.CopyTo(dataToSign, iv.Length); signatureData = mac.ComputeHash(dataToSign); } // Return encrypted and signed data using (var ms = new MemoryStream()) { ms.Write(signatureData, 0, signatureData.Length); ms.Write(iv, 0, iv.Length); ms.Write(encryptedData, 0, encryptedData.Length); var outData = ms.ToArray(); return outData; } }
public byte[] Decrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0) { if (encryptedMessage == null || encryptedMessage.Length == 0) throw new ArgumentException(@"Encrypted Message Required!", nameof(encryptedMessage)); using (var hmac = new HMACSHA512(authKey)) { var sentTag = new byte[hmac.HashSize / 8]; //Calculate Tag var calcTag = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length); var ivLength = BlockSize; //if message length is to small just return null if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength) return null; //Grab Sent Tag Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length); //Compare Tag with constant time comparison var compare = 0; for (var i = 0; i < sentTag.Length; i++) compare |= sentTag[i] ^ calcTag[i]; //if message doesn't authenticate return null if (compare != 0) return null; using (var aes = new RijndaelManaged {KeySize = KeySize * 8, BlockSize = BlockSize * 8, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7}) { //Grab IV from message var iv = new byte[ivLength]; Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length); using (var decrypter = aes.CreateDecryptor(cryptKey, iv)) using (var plainTextStream = new MemoryStream()) { using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write)) using (var binaryWriter = new BinaryWriter(decrypterStream)) { //Decrypt Cipher Text from Message binaryWriter.Write(encryptedMessage,nonSecretPayloadLength + iv.Length,encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length); } //Return Plain Text return plainTextStream.ToArray(); } } } }
public string GenerateRequestSignature(string secret, string apiPath, NameValueCollection queryString) { string formattedQueryString = String.Join ("&", from name in queryString.AllKeys select String.Concat (name, "=", WebUtility.UrlEncode (queryString[name])) ); string message = String.Concat (apiPath, ((char)0).ToString(), formattedQueryString); byte[] rawMessage = Encoding.ASCII.GetBytes (message); byte[] decodedSecret = Convert.FromBase64String (secret); string encodedHash = null; using (var hmac = new HMACSHA512 (decodedSecret)) { byte[] hash = hmac.ComputeHash (rawMessage); encodedHash = Convert.ToBase64String (hash); } return encodedHash; }
public static new double sGetLucky(string server, string client, int nonce) { HMACSHA512 betgenerator = new HMACSHA512(); int charstouse = 5; List<byte> serverb = new List<byte>(); for (int i = 0; i < server.Length; i++) { serverb.Add(Convert.ToByte(server[i])); } betgenerator.Key = serverb.ToArray(); List<byte> buffer = new List<byte>(); string msg = client + "-" + nonce.ToString(); foreach (char c in msg) { buffer.Add(Convert.ToByte(c)); } byte[] hash = betgenerator.ComputeHash(buffer.ToArray()); StringBuilder hex = new StringBuilder(hash.Length * 2); foreach (byte b in hash) hex.AppendFormat("{0:x2}", b); for (int i = 0; i < hex.Length; i += charstouse) { string s = hex.ToString().Substring(i, charstouse); double lucky = int.Parse(s, System.Globalization.NumberStyles.HexNumber); if (lucky < 1000000) { lucky %= 10000; return lucky / 100; } } return 0; }
/// <summary> /// NetAESEncryption constructor /// </summary> public NetAESEncryption(string key, int bitsize) { if (!m_keysizes.Contains(bitsize)) throw new NetException(string.Format("Not a valid key size. (Valid values are: {0})", NetUtility.MakeCommaDelimitedList(m_keysizes))); byte[] entropy = Encoding.UTF32.GetBytes(key); // I know hardcoding salts is bad, but in this case I think it is acceptable. HMACSHA512 hmacsha512 = new HMACSHA512(Convert.FromBase64String("i88NEiez3c50bHqr3YGasDc4p8jRrxJAaiRiqixpvp4XNAStP5YNoC2fXnWkURtkha6M8yY901Gj07IRVIRyGL==")); hmacsha512.Initialize(); for (int i = 0; i < 1000; i++) { entropy = hmacsha512.ComputeHash(entropy); } int keylen = bitsize / 8; m_key = new byte[keylen]; Buffer.BlockCopy(entropy, 0, m_key, 0, keylen); m_iv = new byte[m_blocksizes[0] / 8]; Buffer.BlockCopy(entropy, entropy.Length - m_iv.Length - 1, m_iv, 0, m_iv.Length); m_bitSize = bitsize; }
// GET /api/Identity/id?requestId={requestId}&passwordHash={passwordHash} public UserInfo GetIsValid(string id, string requestId, string passwordHash) { byte[] challenge = null; if (requestId != null && ChallengeCache.Contains(requestId)) { // Retrieve the saved challenge bytes challenge = (byte[])ChallengeCache[requestId]; // Delete saved challenge (each challenge is used just one time). ChallengeCache.Remove(requestId); } lock (Identities) { // Check that credentials are valid. if (challenge != null && id != null && passwordHash != null && Identities.ContainsKey(id)) { // Compute hash for the previously issued challenge string using the password from the server's credentials store as the key. var serverPassword = Encoding.UTF8.GetBytes(Identities[id]); using (var provider = new HMACSHA512(serverPassword)) { var serverHashBytes = provider.ComputeHash(challenge); // Authentication succeeds only if client and server have computed the same hash for the challenge string. var clientHashBytes = DecodeFromHexString(passwordHash); if (!serverHashBytes.SequenceEqual(clientHashBytes)) throw new HttpResponseException(HttpStatusCode.Unauthorized); } if (HttpContext.Current != null) FormsAuthentication.SetAuthCookie(id, false); return new UserInfo { UserName = id }; } else { throw new HttpResponseException(HttpStatusCode.Unauthorized); } } }
private string getHash(byte[] keyByte, String message) { var hmacsha512 = new HMACSHA512(keyByte); var messageBytes = encoding.GetBytes(message); return Convert.ToBase64String(hmacsha512.ComputeHash(messageBytes)); }