// This function is defined as follow : // Func (S, i) = HMAC(S || i) | HMAC2(S || i) | ... | HMAC(iterations) (S || i) // where i is the block number. private byte[] Func() { byte[] INT_block = Utils.Int(m_block); m_hmacsha1.TransformBlock(m_salt, 0, m_salt.Length, null, 0); m_hmacsha1.TransformBlock(INT_block, 0, INT_block.Length, null, 0); m_hmacsha1.TransformFinalBlock(EmptyArray <Byte> .Value, 0, 0); byte[] temp = m_hmacsha1.HashValue; m_hmacsha1.Initialize(); byte[] ret = temp; for (int i = 2; i <= m_iterations; i++) { m_hmacsha1.TransformBlock(temp, 0, temp.Length, null, 0); m_hmacsha1.TransformFinalBlock(EmptyArray <Byte> .Value, 0, 0); temp = m_hmacsha1.HashValue; for (int j = 0; j < BlockSize; j++) { ret[j] ^= temp[j]; } m_hmacsha1.Initialize(); } // increment the block count. m_block++; return(ret); }
public static byte[] ComputeCombinedKey(byte[] requestorEntropy, byte[] issuerEntropy, int keySizeInBits) { if (requestorEntropy == null) { throw new ArgumentNullException("requestorEntropy"); } if (issuerEntropy == null) { throw new ArgumentNullException("issuerEntropy"); } int num = ValidateKeySizeInBytes(keySizeInBits); byte[] array = new byte[num]; using (KeyedHashAlgorithm algorithm = new HMACSHA1()) { algorithm.Key = requestorEntropy; byte[] buffer = issuerEntropy; byte[] buffer3 = new byte[(algorithm.HashSize / 8) + buffer.Length]; byte[] buffer4 = null; try { try { int num2 = 0; while (num2 < num) { algorithm.Initialize(); buffer = algorithm.ComputeHash(buffer); buffer.CopyTo(buffer3, 0); issuerEntropy.CopyTo(buffer3, buffer.Length); algorithm.Initialize(); buffer4 = algorithm.ComputeHash(buffer3); for (int i = 0; i < buffer4.Length; i++) { if (num2 >= num) { continue; } array[num2++] = buffer4[i]; } } } catch { Array.Clear(array, 0, array.Length); throw; } return array; } finally { if (buffer4 != null) { Array.Clear(buffer4, 0, buffer4.Length); } Array.Clear(buffer3, 0, buffer3.Length); algorithm.Clear(); } } }
public static string ToHMAC_SHA1_Encrypted(this string text, string key) { HMACSHA1 hmacSha = new HMACSHA1(Encoding.UTF8.GetBytes(key)); hmacSha.Initialize(); byte[] hmac = hmacSha.ComputeHash(Encoding.UTF8.GetBytes(text)); return System.Text.Encoding.UTF8.GetString(hmac); }
public static byte[] CalculateHMACSHA1(string data, string key) { var enc = System.Text.Encoding.UTF8; HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(key)); hmac.Initialize(); byte[] buffer = enc.GetBytes(data); return hmac.ComputeHash(buffer); }
private static string GetBase64Digest(string signatureString, string secretKey) { var enc = Encoding.UTF8; var hmac = new HMACSHA1(enc.GetBytes(secretKey)); hmac.Initialize(); var buffer = enc.GetBytes(signatureString); return Convert.ToBase64String(hmac.ComputeHash(buffer)); }
public static string HashHMAC(string PublicKey, string PrivateKey) { var enc = Encoding.UTF8; HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(PrivateKey)); hmac.Initialize(); byte[] buffer = enc.GetBytes(PublicKey); return Convert.ToBase64String(hmac.ComputeHash(buffer)); }
public string GetHmacHash(string stringToSign) { var enc = Encoding.ASCII; HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(_privateKey.ToString())); hmac.Initialize(); byte[] buffer = enc.GetBytes(stringToSign); return BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower(); }
public void Auth() { // setup connection to endpoint request = WebRequest.Create(baseUrl + "auth"); // compute HMAC var enc = Encoding.ASCII; HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(privateKey)); hmac.Initialize(); var timestamp = DateTime.Now.ToString(@"MM\/dd\/yyyy hh\:mm"); byte[] buffer = enc.GetBytes(publicKey + timestamp + salt); var hash = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower(); request.Headers ["X-Coursio-apikey"] = publicKey; request.Headers ["X-Coursio-time"] = timestamp; request.Headers ["X-Coursio-random"] = salt; request.Headers ["X-Coursio-hmac"] = hash; request.Method = "POST"; byte[] byteArray = Encoding.UTF8.GetBytes ("{\"method\":\"loginHmac\"}"); // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Write data to the Stream Stream dataStream = request.GetRequestStream (); dataStream.Write (byteArray, 0, byteArray.Length); dataStream.Close (); // Get the response. WebResponse response = request.GetResponse (); // Get the stream content and read it Stream dataStream2 = response.GetResponseStream (); StreamReader reader = new StreamReader (dataStream2); // Read the content. string responseFromServer = reader.ReadToEnd (); // Clean up reader.Close (); dataStream2.Close (); response.Close (); Regex regex = new Regex(@"""sessionId"":""(.*?)"""); Match match = regex.Match(responseFromServer); if (match.Success) { sessionId = match.Groups[1].Value; } else { throw new System.Exception ("Login failed"); } }
public byte[] digest() { byte[] keyBytes = new byte[secret.Length]; System.Buffer.BlockCopy(secret, 0, keyBytes, 0, secret.Length); System.Security.Cryptography.HMAC mac = new HMACSHA1(keyBytes); mac.Initialize(); byte[] challenge = BitConverter.GetBytes(currentInterval); Array.Reverse(challenge); //Java is using Big Endian so we have to convert it mac.ComputeHash(challenge); byte[] hash = mac.Hash; return hash; }
/// <summary> /// Verifies that a GitHub webhook payload is correctly signed. /// </summary> public bool VerifyWebhookPayloadSigned(byte[] content, string signature) { string secret = _webhookSecret.Value; using (var hmac = new HMACSHA1(Encoding.ASCII.GetBytes(secret))) { hmac.Initialize(); var hash = hmac.ComputeHash(content); var str = BitConverter.ToString(hash); var expectedSignature = $"sha1={str.Replace("-", "").ToLower()}"; return signature == expectedSignature; } }
public static string ComputeSignature(string baseString, string keyString) { byte[] keyBytes = UTF8Encoding.UTF8.GetBytes(keyString); HMACSHA1 sha1 = new HMACSHA1(keyBytes); sha1.Initialize(); byte[] baseBytes = UTF8Encoding.UTF8.GetBytes(baseString); byte[] text = sha1.ComputeHash(baseBytes); string signature = Convert.ToBase64String(text).Trim(); return signature; }
/// <summary> /// Generate signature /// </summary> /// <param name="apiUser"></param> /// <param name="apiKey"></param> /// <returns></returns> public string generateSignature(string apiUser, string apiKey) { string nonce = generateNonce(NONCE_LENGTH); DateTime time = DateTime.UtcNow; string data = apiUser + nonce + time; Encoding enc = Encoding.UTF8; HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(apiKey)); hmac.Initialize(); byte[] buffer = enc.GetBytes(data); string signature = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower(); JObject obj = new JObject( new JProperty("REB-APIUSER", apiUser), new JProperty("REB-NONCE", nonce), new JProperty("REB-TIMESTAMP", time.ToString()), new JProperty("REB-SIGNATURE", signature) ); return Convert.ToBase64String(enc.GetBytes(obj.ToString())); }
public TwitterCryptor(string consumerSecret, string oauthTokenSecret = null) { string signingKey = RFC3986.Encode(consumerSecret) + '&' + RFC3986.Encode(oauthTokenSecret); m_Crypto = new HMACSHA1(Encoding.ASCII.GetBytes(signingKey)); m_Crypto.Initialize(); }
protected void Prepare(string endpoint) { if (endpoint == null || endpoint.Length == 0) { throw new System.Exception ("No endpoint specified"); } // setup connection to endpoint request = WebRequest.Create(baseUrl + endpoint); // compute HMAC var enc = Encoding.ASCII; HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(privateKey)); hmac.Initialize(); var timestamp = DateTime.Now.ToString(@"MM\/dd\/yyyy h\:mm tt"); var signatureString = publicKey + timestamp + salt; byte[] buffer = enc.GetBytes(signatureString); var hash = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower(); request.Headers ["X-Coursio-apikey"] = publicKey; request.Headers ["X-Coursio-time"] = timestamp; request.Headers ["X-Coursio-random"] = salt; request.Headers ["X-Coursio-hmac"] = hash; }
// public methods /// <summary> /// /// </summary> /// <param name="requestorEntropy"></param> /// <param name="issuerEntropy"></param> /// <param name="keySize"></param> /// <returns></returns> public static byte[] ComputeCombinedKey(byte[] requestorEntropy, byte[] issuerEntropy, int keySize) { if (keySize < 64 || keySize > 4096) throw new ArgumentOutOfRangeException("keySize"); KeyedHashAlgorithm kha = new HMACSHA1(requestorEntropy, true); byte[] key = new byte[keySize / 8]; // Final key byte[] a = issuerEntropy; // A(0) byte[] b = new byte[kha.HashSize / 8 + a.Length]; // Buffer for A(i) + seed for (int i = 0; i < key.Length;) { // Calculate A(i+1). kha.Initialize(); a = kha.ComputeHash(a); // Calculate A(i) + seed a.CopyTo(b, 0); issuerEntropy.CopyTo(b, a.Length); kha.Initialize(); byte[] result = kha.ComputeHash(b); for (int j = 0; j < result.Length; j++) { if (i < key.Length) key[i++] = result[j]; else break; } } return key; }
/// <summary> /// Helper method to create the appropriate Authentication Hash that Distimo expects /// </summary> /// <returns>Distimo Authentication Hash</returns> private DistimoAuthToken CreateAuthToken(string queryString) { var time = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds; string data = String.Concat(queryString, time); HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(DistimoAuthService.DistimoPrivateKey)); hmac.Initialize(); byte[] buffer = Encoding.ASCII.GetBytes(data); string hash = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower(); string user = String.Concat(DistimoAuthService.DistimoUserName, ":", DistimoAuthService.DistimoPassword); string base64Login = Convert.ToBase64String(Encoding.Default.GetBytes(user)); return new DistimoAuthToken(hash, base64Login, time); }
private static string Base64EncodeHash(string url) { byte[] result; HMACSHA1 shaM = new HMACSHA1(); byte[] ms = new byte[url.Length]; for (int i = 0; i < url.Length; i++) { byte b = Convert.ToByte(url[i]); ms[i] = (b); } shaM.Initialize(); result = shaM.ComputeHash(ms, 0, ms.Length); return System.Convert.ToBase64String(result); ; }
/// <summary> /// Generates a PIN of desired length when given a challenge (counter) /// </summary> /// <param name="challenge">Counter to calculate hash</param> /// <returns>Desired length PIN</returns> private String generateResponseCode(long challenge, byte[] randomBytes) { HMACSHA1 myHmac = new HMACSHA1(randomBytes); myHmac.Initialize(); byte[] value = BitConverter.GetBytes(challenge); Array.Reverse(value); //reverses the challenge array due to differences in c# vs java myHmac.ComputeHash(value); byte[] hash = myHmac.Hash; int offset = hash[hash.Length - 1] & 0xF; byte[] SelectedFourBytes = new byte[4]; //selected bytes are actually reversed due to c# again, thus the weird stuff here SelectedFourBytes[0] = hash[offset]; SelectedFourBytes[1] = hash[offset + 1]; SelectedFourBytes[2] = hash[offset + 2]; SelectedFourBytes[3] = hash[offset + 3]; Array.Reverse(SelectedFourBytes); int finalInt = BitConverter.ToInt32(SelectedFourBytes, 0); int truncatedHash = finalInt & 0x7FFFFFFF; //remove the most significant bit for interoperability as per HMAC standards int pinValue = truncatedHash % pinModulo; //generate 10^d digits where d is the number of digits return padOutput(pinValue); }
byte[] ComputeToken(byte[] hash, byte[] ascii_text) { using (HMAC hmac = new HMACSHA1 (_hmac_key, true)) { hmac.Initialize (); hmac.TransformBlock (hash, 0, hash.Length, null, 0); hmac.TransformBlock (ascii_text, 0, ascii_text.Length, null, 0); hmac.TransformFinalBlock (_salt, 0, _salt.Length); return hmac.Hash; } }
/// <summary> /// Generates the encrypted password to append to the end of a request URI. /// </summary> /// <param name="url">request URI without "&pass="******"string"/> of the encrypted password.</returns> protected string GenerateQueryStringPassword(string url) { var uri = new Uri(url); var hmacshA1 = new HMACSHA1(Encoding.ASCII.GetBytes(Key.ToLowerInvariant())); hmacshA1.Initialize(); var str = Convert.ToBase64String(hmacshA1.ComputeHash(Encoding.ASCII.GetBytes(uri.PathAndQuery))); return Uri.EscapeDataString(string.Format("HMAC{{{0}}}", str.ToLowerInvariant())); }
public byte[] ComputeHash(byte[] data, int offset, int length) { _algorithm.Initialize(); return(_algorithm.ComputeHash(data, offset, length)); }
public string computeHmac(string sData) { HMACSHA1 TpeHmac = new HMACSHA1(_sUsableKey); TpeHmac.Initialize(); byte[] bytes = Encoding.ASCII.GetBytes(sData); byte[] ba = TpeHmac.ComputeHash(bytes); return this.byteArrayToHexString(ba); }
/// <summary> /// HMAC sha1 /// </summary> /// /// <param name="key">the key must be at least 8 bytes in length.</param> /// <param name="ins0">byte array to HMAC.</param> /// <returns>the hash</returns> /// @throws GeneralSecurityException public static byte[] HmacSha1(byte[] key, byte[] ins0) { if (key.Length < MIN_HMAC_KEY_LEN) { throw new Exception("HMAC key should be at least " + MIN_HMAC_KEY_LEN + " bytes."); } HMACSHA1 hmac = new HMACSHA1(key); hmac.Initialize(); return hmac.ComputeHash(ins0); }
public void GenerateSessionKey(byte[] clientSalt, byte[] serverSalt) { var hmac = new HMACSHA1(SecureRemotePassword.SessionKey); var wow = Encoding.ASCII.GetBytes("WoW\0"); var wowSessionKey = new byte[0x28]; hmac.TransformBlock(wow, 0, wow.Length, wow, 0); hmac.TransformBlock(clientSalt, 0, clientSalt.Length, clientSalt, 0); hmac.TransformFinalBlock(serverSalt, 0, serverSalt.Length); Buffer.BlockCopy(hmac.Hash, 0, wowSessionKey, 0, hmac.Hash.Length); hmac.Initialize(); hmac.TransformBlock(wow, 0, wow.Length, wow, 0); hmac.TransformBlock(serverSalt, 0, serverSalt.Length, serverSalt, 0); hmac.TransformFinalBlock(clientSalt, 0, clientSalt.Length); Buffer.BlockCopy(hmac.Hash, 0, wowSessionKey, hmac.Hash.Length, hmac.Hash.Length); GameAccount.SessionKey = wowSessionKey.ToHexString(); // Update SessionKey in database DB.Auth.Update(GameAccount); }
private dynamic auth_call(string resource, string method, string content) { string url = base_url + resource; // Create request HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; // Set method request.Method = method; WebHeaderCollection headers = (request as HttpWebRequest).Headers; string httpDate = DateTime.UtcNow.ToString("ddd, dd MMM yyyy HH:mm:ss ") + "GMT"; Encoding ae = new UTF8Encoding(); string content_type = "application/json"; string content_md5 = ""; if (!content.Equals("")) { // Need to verify MD5 MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] hash = md5.ComputeHash(ae.GetBytes(content)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } content_md5 = sb.ToString().ToLower(); } string canonicalString = method + "\n" + content_md5 + "\n" + content_type + "\n" + httpDate + "\n" + url; HMACSHA1 signature = new HMACSHA1(System.Text.Encoding.ASCII.GetBytes(secretId)); signature.Initialize(); // Get the actual signature byte[] moreBytes = signature.ComputeHash(ae.GetBytes(canonicalString)); string encodedCanonical = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(ByteToString(moreBytes).ToLower())); request.ContentType = content_type; request.Headers.Add("X-mailin-date", httpDate); request.Headers.Add("Authorization", accessId + ":" + encodedCanonical); if (method == "POST" || method == "PUT") { using (System.IO.Stream s = request.GetRequestStream()) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(s)) sw.Write(content); } } HttpWebResponse response; response = request.GetResponse() as HttpWebResponse; // read the response stream and put it into a byte array Stream stream = response.GetResponseStream() as Stream; byte[] buffer = new byte[32 * 1024]; int nRead = 0; MemoryStream ms = new MemoryStream(); do { nRead = stream.Read(buffer, 0, buffer.Length); ms.Write(buffer, 0, nRead); } while (nRead > 0); // convert read bytes into string ASCIIEncoding encoding = new ASCIIEncoding(); string responseString = encoding.GetString(ms.ToArray()); // Return a dynamic object return JObject.Parse(responseString); }