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)); }
/// <summary> /// Hash the signature using specified cipher strength. Default is HMACSHA1 /// </summary> /// <param name="plainText"></param> /// <param name="privateKey"></param> /// <returns></returns> public byte[] Hash(string plainText, byte[] privateKey) { int cipherStrength = Convert.ToInt32(Options.CipherStrength); try { HMAC Cipher = null; if (cipherStrength == 256) { Cipher = new HMACSHA256(privateKey); } else if (cipherStrength == 384) { Cipher = new HMACSHA384(privateKey); } else if (cipherStrength == 512) { Cipher = new HMACSHA512(privateKey); } else { //Default Cipher = new HMACSHA256(privateKey); } byte[] PlainBytes = Encoder.GetBytes(plainText); byte[] HashedBytes = Cipher.ComputeHash(PlainBytes); return(HashedBytes); } catch (Exception ex) { throw ex; } }
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); }
/// <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)))); } }
public string GetSignature(string plainText, byte[] privateKey) { int cipherStrength = 256; try { byte[] KeyBytes = privateKey; HMAC Cipher = null; if (cipherStrength == 256) { Cipher = new HMACSHA256(KeyBytes); } else if (cipherStrength == 384) { Cipher = new HMACSHA384(KeyBytes); } else if (cipherStrength == 512) { Cipher = new HMACSHA512(KeyBytes); } else { //Default Cipher = new HMACSHA256(KeyBytes); } byte[] PlainBytes = Encoder.GetBytes(plainText); byte[] HashedBytes = Cipher.ComputeHash(PlainBytes); return(WebEncoders.Base64UrlEncode(HashedBytes)); } catch (Exception ex) { throw ex; } }
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 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(); }
private static byte[] ComputeHash(JwtHashAlgorithm algorithm, byte[] key, byte[] value) { HashAlgorithm hashAlgorithm; switch (algorithm) { case JwtHashAlgorithm.HS256: hashAlgorithm = new HMACSHA256(key); break; case JwtHashAlgorithm.HS384: hashAlgorithm = new HMACSHA384(key); break; case JwtHashAlgorithm.HS512: hashAlgorithm = new HMACSHA512(key); break; default: throw new Exception($"Unsupported hash algorithm: '{algorithm}'."); } using (hashAlgorithm) { return(hashAlgorithm.ComputeHash(value)); } }
private byte[] ComputeHmac( int keySize, byte[] key, byte[] input) { HMAC hashMacAlg; switch (keySize) { case 256: hashMacAlg = new HMACSHA256(key); break; case 384: hashMacAlg = new HMACSHA384(key); break; case 512: hashMacAlg = new HMACSHA512(key); break; default: return(null); } return(hashMacAlg.ComputeHash(input)); }
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; } }
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)); } } } }; }
/// <summary> /// Open a properly configured <see cref="HMAC"/> conforming to the scheme /// identified by <paramref name="aeMac"/>. /// </summary> /// <param name="aeMac">The message authentication mode to open.</param> /// <param name="keyMac">The key data.</param> /// <returns> /// An HMAC object with the proper key, or <c>null</c> on unknown algorithms. /// </returns> private static HMAC GetMac(AeMac aeMac, byte[] keyMac) { HMAC hmac; switch (aeMac) { case AeMac.HMACSHA256: hmac = new HMACSHA256(); break; case AeMac.HMACSHA384: hmac = new HMACSHA384(); break; case AeMac.HMACSHA512: hmac = new HMACSHA512(); break; default: //An algorithm we don't understand throw new CryptographicException("Invalid Mac algorithm"); } hmac.Key = keyMac; return(hmac); }
/// <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))); } }
public JsonWebToken(SerializerType serializerType) { switch (serializerType) { case SerializerType.DefaultSerializer: JsonSerializer = new DefaultJsonSerializer(); break; case SerializerType.NewtonsoftJsonSerializer: JsonSerializer = new NewtonsoftJsonSerializer(); break; case SerializerType.ServiceStackJsonSerializer: JsonSerializer = new ServiceStackJsonSerializer(); break; default: JsonSerializer = new DefaultJsonSerializer(); break; } HashAlgorithms = new Dictionary <JwtHashAlgorithm, Func <byte[], byte[], byte[]> > { { JwtHashAlgorithm.HS256, (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 byte[] CalcularHmacSha384(byte[] passaASer, byte[] chave) { using (var hmac = new HMACSHA384(chave)) { return(hmac.ComputeHash(passaASer)); } }
/// <summary> 获取基于密钥的 Hash 加密方法 </summary> private static HMAC GetHmac(HmacFormat hmacFormat, byte[] key) { HMAC hmac; switch (hmacFormat) { case HmacFormat.HMACMD5: hmac = new HMACMD5(key); break; //case HmacFormat.HMACRIPEMD160: // hmac = new HMACRIPEMD160(key); // break; case HmacFormat.HMACSHA1: hmac = new HMACSHA1(key); break; case HmacFormat.HMACSHA256: hmac = new HMACSHA256(key); break; case HmacFormat.HMACSHA384: hmac = new HMACSHA384(key); break; case HmacFormat.HMACSHA512: hmac = new HMACSHA512(key); break; default: throw new ArgumentOutOfRangeException(nameof(hmacFormat), hmacFormat, null); } return(hmac); }
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 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()); }
public static byte[] ToHmacSHA384(this byte[] s, byte[] key) { using (var hmac = new HMACSHA384(key)) { return(hmac.ComputeHash(s)); } }
/// <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); }
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)); }
/// <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)); } }
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 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)); }
/// <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)); } }
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; }
private void HMACParameters() { /* Key size is selected based on NIST Special Publication 800-107 Revision 1 * Recommendation for Applications Using Approved Hash Algorithms * Section 5.3.4 Security Effect of the HMAC Key */ HMAC hmac; switch (Algorithm.Serialize()) { case "HS256": hmac = new HMACSHA256(CreateHMACKey(64)); break; case "HS384": hmac = new HMACSHA384(CreateHMACKey(128)); break; case "HS512": hmac = new HMACSHA512(CreateHMACKey(128)); break; default: throw new CryptographicException("Could not create HMAC key based on algorithm " + Algorithm.Serialize() + " (Could not parse expected SHA version)"); } var key = Base64urlEncode(hmac.Key); KeyParameters = new Dictionary <KeyParameter, string> { { OctKeyParameterK, key } }; }
/// <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()); }
/// <summary> /// Hash the signature using specified cipher strength. Default is HMACSHA1 /// </summary> /// <param name="plainText"></param> /// <param name="privateKey"></param> /// <returns></returns> public string Hash(string plainText, string privateKey) { int cipherStrength = Convert.ToInt32(Options.CipherStrength); try { byte[] KeyBytes = Encoder.GetBytes(privateKey); HMAC Cipher = null; if (cipherStrength == 256) { Cipher = new HMACSHA256(KeyBytes); } else if (cipherStrength == 384) { Cipher = new HMACSHA384(KeyBytes); } else if (cipherStrength == 512) { Cipher = new HMACSHA512(KeyBytes); } else { //Default Cipher = new HMACSHA256(KeyBytes); } byte[] PlainBytes = Encoder.GetBytes(plainText); byte[] HashedBytes = Cipher.ComputeHash(PlainBytes); return(WebEncoders.Base64UrlEncode(HashedBytes));//Convert.ToBase64String(HashedBytes); } catch (Exception ex) { throw ex; } }
/// <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)); } }
public void ProduceLegacyHmacValues() { using (var h = new HMACSHA384()) { Assert.False(h.ProduceLegacyHmacValues); h.ProduceLegacyHmacValues = false; // doesn't throw Assert.Throws<PlatformNotSupportedException>(() => h.ProduceLegacyHmacValues = true); } }
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; }