private static byte[] P_SHA384(byte[] secret, byte[] seed, int bytesToGenerate) { var BLOCKSIZE = 48; var iterations = bytesToGenerate / BLOCKSIZE + 1; var generatedBytes = new byte[iterations * BLOCKSIZE]; var hmac = new HMACSHA384(secret); var a = new byte[iterations][]; a[0] = seed; a[1] = hmac.ComputeHash(a[0]); var previousA = hmac.ComputeHash(seed); for (int i = 1; i <= iterations; i++) { var A = hmac.ComputeHash(previousA); var aAndSeed = new byte[BLOCKSIZE + seed.Length]; Buffer.BlockCopy(A, 0, aAndSeed, 0, A.Length); Buffer.BlockCopy(seed, 0, aAndSeed, A.Length, seed.Length); var part = hmac.ComputeHash(aAndSeed); Buffer.BlockCopy(part, 0, generatedBytes, (i - 1) * BLOCKSIZE, part.Length); previousA = A; } var result = new byte[bytesToGenerate]; Buffer.BlockCopy(generatedBytes, 0, result, 0, result.Length); return(result); }
private string Hash(string pass, string salt) { var key = /*_cfg.CryptographicKey;// */ "4e95f4b2ae1075e697695926a47c721d"; System.Security.Cryptography.HMACSHA384 crypto = new HMACSHA384(Encoding.ASCII.GetBytes(key)); return(Convert.ToBase64String(crypto.ComputeHash(Encoding.ASCII.GetBytes(salt + pass)))); }
private static string GetHexHashSignature(string payload, string secret) { HMACSHA384 hmac = new HMACSHA384(Encoding.UTF8.GetBytes(secret)); byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)); return(BitConverter.ToString(hash).Replace("-", "").ToLower()); }
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)); } } } }; }
private T Send <T>(BasicRequest request) { try { var jsonText = JsonConvert.SerializeObject(request); var payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonText)); var hmac = new HMACSHA384(Encoding.UTF8.GetBytes(_secret)); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)); var hexHash = BitConverter.ToString(hash).Replace("-", ""); using (var client = new WebClient()) { client.Headers.Add("X-GEMINI-APIKEY", _key); client.Headers.Add("X-GEMINI-PAYLOAD", payload); client.Headers.Add("X-GEMINI-SIGNATURE", hexHash); var response = client.UploadString($"{_baseUrl}{request.Request}", ""); return(JsonConvert.DeserializeObject <T>(response)); } } catch (Exception ex) { throw ex; } }
private async Task <string> SendRequestAsync(GenericRequest request, string httpMethod) { string json = JsonConvert.SerializeObject(request); string json64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); byte[] data = Encoding.UTF8.GetBytes(json64); byte[] hash = hashMaker.ComputeHash(data); string signature = GetHexString(hash); HttpWebRequest wr = WebRequest.Create("https://api.bitfinex.com" + request.request) as HttpWebRequest; wr.Headers.Add("X-BFX-APIKEY", Key); wr.Headers.Add("X-BFX-PAYLOAD", json64); wr.Headers.Add("X-BFX-SIGNATURE", signature); wr.Method = httpMethod; string response = null; try { HttpWebResponse resp = wr.GetResponse() as HttpWebResponse; StreamReader sr = new StreamReader(resp.GetResponseStream()); response = await sr.ReadToEndAsync(); sr.Close(); } catch (WebException ex) { StreamReader sr = new StreamReader(ex.Response.GetResponseStream()); response = sr.ReadToEnd(); sr.Close(); throw new BitfinexException(ex, response); } return(response); }
public static string CreateSign(string secretKey, string content) { var hmacSha = new HMACSHA384(Encoding.UTF8.GetBytes(secretKey)); var hash = hmacSha.ComputeHash(Encoding.UTF8.GetBytes(content)).ToArray(); return(Convert.ToBase64String(hash)); }
static JsonWebToken() { JsonWebToken.jsonSerializer = new JavaScriptSerializer(); Dictionary <JwtHashAlgorithm, Func <byte[], byte[], byte[]> > dictionary = new Dictionary <JwtHashAlgorithm, Func <byte[], byte[], byte[]> >(); dictionary.Add(JwtHashAlgorithm.HS256, delegate(byte[] key, byte[] value) { byte[] result; using (HMACSHA256 hMACSHA = new HMACSHA256(key)) { result = hMACSHA.ComputeHash(value); } return(result); }); dictionary.Add(JwtHashAlgorithm.HS384, delegate(byte[] key, byte[] value) { byte[] result; using (HMACSHA384 hMACSHA = new HMACSHA384(key)) { result = hMACSHA.ComputeHash(value); } return(result); }); dictionary.Add(JwtHashAlgorithm.HS512, delegate(byte[] key, byte[] value) { byte[] result; using (HMACSHA512 hMACSHA = new HMACSHA512(key)) { result = hMACSHA.ComputeHash(value); } return(result); }); JsonWebToken.HashAlgorithms = dictionary; }
/// <summary> /// 使用HMACSHA384进行加密。 /// </summary> /// <param name="text">当前字符串。</param> /// <param name="key">哈希算法密钥128位密钥,十六进制字符串。</param> /// <returns>返回加密后的16进制的字符串。</returns> // ReSharper disable once InconsistentNaming public static string HMACSHA384(string text, string key) { var sha = new HMACSHA384(GetBytes(key)); var hashed = sha.ComputeHash(Encoding.UTF8.GetBytes(text)); return(hashed.ToHexString()); }
private static bool IsRequestValid(string signature, string secret, string body) { // If there's no secret, we accept any request as valid if (string.IsNullOrEmpty(secret)) { return(true); } // We always expect a signature to prevent non-Mixer initiated requests if (string.IsNullOrEmpty(signature)) { return(false); } var secretBytes = Encoding.UTF8.GetBytes(secret); if (secretBytes != null) { var hmac = new HMACSHA384(secretBytes); var hash = BitConverter.ToString(hmac.ComputeHash(Encoding.UTF8.GetBytes(body))).Replace("-", string.Empty); return(signature.Equals($"sha384={hash}")); } return(false); }
private static async Task <string> DoHttpRequestAsync( string subUri, string publicKey, string secretKey, Action <string> callback, dynamic body = null) { DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan diff = DateTime.Now.ToUniversalTime() - origin; long nonce = (long)Math.Floor(diff.TotalMilliseconds); var rawBody = JsonConvert.SerializeObject(body == null ? new { } : body); string signature = $"/api/{subUri}{nonce}{rawBody}"; var hmac = new HMACSHA384(Encoding.UTF8.GetBytes(secretKey)); byte[] k = hmac.ComputeHash(Encoding.UTF8.GetBytes(signature)); string signatureString = string.Concat(k.Select(b => b.ToString("X2")).ToArray()).ToLower(); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.TryAddWithoutValidation("bfx-nonce", nonce.ToString()); client.DefaultRequestHeaders.TryAddWithoutValidation("bfx-apikey", publicKey); client.DefaultRequestHeaders.TryAddWithoutValidation("bfx-signature", signatureString); var response = await client.PostAsync($"https://api.bitfinex.com/{subUri}", new StringContent(rawBody, Encoding.UTF8, "application/json")); var responseString = await response.Content.ReadAsStringAsync(); if (callback != null) { callback(responseString); } return(responseString); }
private string GetHexHashSignature(string payload) { var hmac = new HMACSHA384(Encoding.UTF8.GetBytes(_apiSecret)); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)); return(BitConverter.ToString(hash).Replace("-", "").ToLower()); }
private void checkDetails(string username, string password) { byte[] pass = Encoding.ASCII.GetBytes(password); HMACSHA512 hmac1 = new HMACSHA512(new byte[] { 0xBA, 0x43, 0xB7, 0x3E, 0xCB }); StringBuilder sb = new StringBuilder(); byte[] passHash = hmac1.ComputeHash(pass); foreach (byte b in passHash) { sb.Append((char)b); } if (sb.ToString() == Properties.Settings.Default.Password) { sb.Clear(); HMACSHA384 hmac2 = new HMACSHA384(passHash); byte[] key = hmac2.ComputeHash(pass); for (int i = 0; i < username.Length; i++) { sb.Append((char)((byte)username[i] ^ key[i % key.Length])); } if (sb.ToString() == Properties.Settings.Default.Username) { Password = password; Paging.LoadPage(Pages.Welcome); lblBadInput.Visibility = Visibility.Hidden; return; } } lblBadInput.Visibility = Visibility.Visible; }
public static byte[] ComputeHMACSHA384HashFromFile(string filePath, byte[] authKey, int offset = 0) { if (!File.Exists(filePath)) { throw new FileNotFoundException($"File \"{filePath}\" not found.", filePath); } if (authKey == null || authKey.Length == 0) { throw new ArgumentException("Invalid auth key.", nameof(authKey)); } byte[] hash = null; using (var hmacSha384 = new HMACSHA384(authKey)) { using (FileStream fStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { fStream.Seek(offset, SeekOrigin.Begin); hash = hmacSha384.ComputeHash(fStream); fStream.Close(); } } return(hash); }
/// <summary> /// Calculates a SHA-384 hash signature. /// </summary> /// <param name="input">The message for which a signature will be generated</param> /// <param name="key">The secret key to use to sign the message</param> /// <returns>The HMAC signature.</returns> public static byte[] HMACSHA384(byte[] input, byte[] key) { using (HMACSHA384 hmac = new HMACSHA384(key)) { return(hmac.ComputeHash(input)); } }
private void add(string username, string password) { byte[] pass = Encoding.ASCII.GetBytes(password); HMACSHA512 hmac1 = new HMACSHA512(new byte[] { 0xBA, 0x43, 0xB7, 0x3E, 0xCB }); StringBuilder sb = new StringBuilder(); byte[] passHash = hmac1.ComputeHash(pass); foreach (byte b in passHash) { sb.Append((char)b); } Properties.Settings.Default.Password = sb.ToString(); sb.Clear(); HMACSHA384 hmac2 = new HMACSHA384(passHash); byte[] key = hmac2.ComputeHash(pass); for (int i = 0; i < username.Length; i++) { sb.Append((char)((byte)username[i] ^ key[i % key.Length])); } Properties.Settings.Default.Username = sb.ToString(); Properties.Settings.Default.Save(); ContentFile.Encrypt(password); MessageBox.Show("Registered your user!"); Paging.LoadPage(Pages.Login); }
public static string bitfinexQuery(string urlParams, bool bypass, string requestBody = "") { string key = ""; string secret = ""; HMACSHA384 hashMaker = new HMACSHA384(Encoding.UTF8.GetBytes(secret)); UInt64 unixTimestamp = (UInt64)DateTime.Now.Ticks; //request url parameters string data = @"{""request"":""/v1/" + urlParams + @""",""nonce"":""" + unixTimestamp.ToString() + @"""}"; if (bypass) { data = requestBody; } string payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(data)); byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(data); var request = WebRequest.Create(new Uri("https://api.bitfinex.com/v1/" + urlParams)) as HttpWebRequest; request.Method = "POST"; request.KeepAlive = true; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; byte[] hashed = hashMaker.ComputeHash(Encoding.UTF8.GetBytes(payload)); string sign = BitConverter.ToString(hashed).Replace("-", "").ToLower(); request.Headers.Add("X-BFX-APIKEY", key); request.Headers.Add("X-BFX-PAYLOAD", payload); request.Headers.Add("X-BFX-SIGNATURE", sign); var reqStream = request.GetRequestStream(); reqStream.Write(byteArray, 0, byteArray.Length); return(read(request)); }
public static byte[] CalcularHmacSha384(byte[] passaASer, byte[] chave) { using (var hmac = new HMACSHA384(chave)) { return(hmac.ComputeHash(passaASer)); } }
private async Task <string> SendRequestAsync(object request, string url) { string json = JsonConvert.SerializeObject(request); string json64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); byte[] data = Encoding.UTF8.GetBytes(json64); byte[] hash = _hashMaker.ComputeHash(data); string signature = GetHexString(hash); using (HttpClient client = new HttpClient()) { var headers = client.DefaultRequestHeaders; headers.Add("X-BFX-APIKEY", _key); headers.Add("X-BFX-PAYLOAD", json64); headers.Add("X-BFX-SIGNATURE", signature); var response = await client.PostAsync(_endpointAddress + url, null); var body = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Response Body Raw:"); Console.WriteLine($"{body}"); if (!response.IsSuccessStatusCode) { throw new BitfinexException(response.ReasonPhrase, body); } return(body); } }
/// <summary> /// Computes a HMAC-SHA384 hash for the input data, using the specified key. /// </summary> /// <param name="input">The raw input data to hash</param> /// <param name="key">The raw key to use</param> /// <returns>Unix format hex string of the hash</returns> public static HashResult HmacSha384(this byte[] input, byte[] key) { using (var hash = new HMACSHA384(key)) { return(new HashResult(hash.ComputeHash(input))); } }
/// <summary> /// Signs the provided byte array with the provided key. /// </summary> /// <param name="key">The key used to sign the data.</param> /// <param name="bytesToSign">The data to sign.</param> public byte[] Sign(byte[] key, byte[] bytesToSign) { using (var sha = new HMACSHA384(key)) { return(sha.ComputeHash(bytesToSign)); } }
/// <summary> /// Hash a token signature /// </summary> /// <param name="algorithm"><see cref="JWTAlgorithm"/> to encrypt</param> /// <param name="keyBytes">Key</param> /// <param name="payloadBytes">Payload</param> /// <returns>Hashed Signature</returns> public static byte[] HashSignature(JWTAlgorithm algorithm, byte[] keyBytes, byte[] payloadBytes) { byte[] hashedBytes = null; switch (algorithm) { case JWTAlgorithm.HS256: HMACSHA256 encHMAC256 = new HMACSHA256(keyBytes); hashedBytes = encHMAC256.ComputeHash(payloadBytes); break; case JWTAlgorithm.HS384: HMACSHA384 encHMAC384 = new HMACSHA384(keyBytes); hashedBytes = encHMAC384.ComputeHash(payloadBytes); break; case JWTAlgorithm.HS512: HMACSHA512 encHMAC512 = new HMACSHA512(keyBytes); hashedBytes = encHMAC512.ComputeHash(payloadBytes); break; default: // temporary impementation of a default encryption goto case JWTAlgorithm.HS256; } return(hashedBytes); }
/// <summary> /// Creates an auth token for ws auth endppoints /// https://docs.bitfinex.com/docs/ws-auth /// </summary> /// <param name="payload">the body of the request</param> /// <returns>a token representing the request params</returns> private string AuthenticationToken(string payload) { using (HMACSHA384 hmac = new HMACSHA384(Encoding.UTF8.GetBytes(ApiSecret))) { return(ByteArrayToString(hmac.ComputeHash(Encoding.UTF8.GetBytes(payload)))); } }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <param name="secret"></param> /// <param name="compareToHashString"></param> /// <returns></returns> public static bool IsHMACSHA384Valid(string message, string secret, string compareToHashString) { try { secret = secret ?? ""; var encoding = new System.Text.ASCIIEncoding(); byte[] keyBytes = encoding.GetBytes(secret); byte[] messageBytes = encoding.GetBytes(message); using (var hmacsha384 = new HMACSHA384(keyBytes)) { byte[] hashMessage = hmacsha384.ComputeHash(messageBytes); string hashString = Convert.ToBase64String(hashMessage).ToLower(); bool isValid = hashString == compareToHashString.ToLower(); return(isValid); } } catch (Exception ex) { Debug.WriteLine("IsHMACSHA384Valid : " + ex.Message); throw; } }
/// <summary> /// Computes an HMAC SHA 384 hash /// with text and key /// </summary> /// <param name="text"></param> /// <param name="key"></param> /// <returns></returns> public static byte[] ComputeHmachSHA384(byte[] text, byte[] key) { using (var hmac = new HMACSHA384(key)) { return(hmac.ComputeHash(text)); } }
public byte[] Sign(byte[] input) { var keyBytes = CryptoHelper.Base64.UrlDecode(Key); switch (Algorithm) { case "HS256": { using var hmac = new HMACSHA256(keyBytes); return(hmac.ComputeHash(input)); } case "HS384": { using var hmac = new HMACSHA384(keyBytes); return(hmac.ComputeHash(input)); } case "HS512": { using var hmac = new HMACSHA512(keyBytes); return(hmac.ComputeHash(input)); } } throw new InvalidOperationException(); }
public static void SignFile(byte[] key, String sourceFile, String destFile) { // Initialize the keyed hash object. using (HMACSHA384 hmac = new HMACSHA384(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); } } } return; } // end SignFile
public static byte[] ToHmacSHA384(this string s, byte[] key, Encoding encoding) { using (var hmac = new HMACSHA384(key)) { return(hmac.ComputeHash(s.GetBytes(encoding))); } }
public static async Task <T> InvokeHttpCall <T>( string path, BaseInfo args, string apiKey, string secretKey) { var req = new HttpRequestMessage(HttpMethod.Get, endpointBase + path); if (args != null) { req.Method = HttpMethod.Post; string json = JsonConvert.SerializeObject(args); string payload = Convert.ToBase64String(Encoding.UTF8.GetBytes(json)); var crypto = new HMACSHA384(Encoding.UTF8.GetBytes(secretKey)); var hash = crypto.ComputeHash(Encoding.UTF8.GetBytes(payload)); string signature = BitConverter.ToString(hash).Replace("-", "").ToLower(); req.Headers.Add("X-BFX-APIKEY", apiKey); req.Headers.Add("X-BFX-PAYLOAD", payload); req.Headers.Add("X-BFX-SIGNATURE", signature); } var res = await _httpClient.SendAsync(req); string data = await res.Content.ReadAsStringAsync(); if (!res.IsSuccessStatusCode) { throw new HttpRequestException(data); } return(JsonConvert.DeserializeObject <T>(data)); }
public static byte[] ToHmacSHA384(this byte[] s, byte[] key) { using (var hmac = new HMACSHA384(key)) { return(hmac.ComputeHash(s)); } }
public static int Main() { byte[] key = ParseHexBytes(KeyStr); byte[] data = ParseHexBytes(DataStr); byte[] hash384Correct = ParseHexBytes(Hash384CorrectStr); byte[] hash384Legacy = ParseHexBytes(Hash384LegacyStr); byte[] hash512Correct = ParseHexBytes(Hash512CorrectStr); byte[] hash512Legacy = ParseHexBytes(Hash512LegacyStr); // HMAC-SHA-384 with legacy property set -> legacy result // HMACSHA384 hm384Legacy = new HMACSHA384(key); hm384Legacy.ProduceLegacyHmacValues = true; byte[] result384Legacy = hm384Legacy.ComputeHash(data); if (!CompareBytes(result384Legacy, hash384Legacy)) { Console.WriteLine("HMACSHA384 - ProductLegacyHmacValues=true failed"); return FailCode; } // HMAC-SHA-384 with legacy property not set -> correct result // HMACSHA384 hm384Correct = new HMACSHA384(key); hm384Correct.ProduceLegacyHmacValues = false; byte[] result384Correct = hm384Correct.ComputeHash(data); if (!CompareBytes(result384Correct, hash384Correct)) { Console.WriteLine("HMACSHA384 - ProduceLegacyHmacValues=false failed"); return FailCode; } // HMAC-SHA-384 with legacy property not set -> default result (correct) // HMACSHA384 hm384Default = new HMACSHA384(key); byte[] result384Default = hm384Default.ComputeHash(data); if (!CompareBytes(result384Default, hash384Correct)) { Console.WriteLine("HMACSHA384 - ProduceLegacyHmacValues=default failed"); return FailCode; } // HMAC-SHA-512 with legacy property set -> legacy result // HMACSHA512 hm512Legacy = new HMACSHA512(key); hm512Legacy.ProduceLegacyHmacValues = true; byte[] result512Legacy = hm512Legacy.ComputeHash(data); if (!CompareBytes(result512Legacy, hash512Legacy)) { Console.WriteLine("HMACSHA512 - ProduceLegacyHmacValues=true failed"); return FailCode; } // HMAC-SHA-512 with legacy property not set -> correct result // HMACSHA512 hm512Correct = new HMACSHA512(key); hm512Correct.ProduceLegacyHmacValues = false; byte[] result512Correct = hm512Correct.ComputeHash(data); if (!CompareBytes(result512Correct, hash512Correct)) { Console.WriteLine("HMACSHA512 - ProduceLegacyHmacValues=false failed"); return FailCode; } // HMAC-SHA-512 with legacy property not set -> default result (correct) // HMACSHA512 hm512Default = new HMACSHA512(key); byte[] result512Default = hm512Default.ComputeHash(data); if (!CompareBytes(result512Default, hash512Correct)) { Console.WriteLine("HMACSHA512 - ProduceLegacyHmacValues=default failed"); return FailCode; } Console.WriteLine("Test passed"); return PassCode; }