本文整理汇总了C#中System.Security.Cryptography.HMACSHA256.ComputeHash方法的典型用法代码示例。如果您正苦于以下问题:C# HMACSHA256.ComputeHash方法的具体用法?C# HMACSHA256.ComputeHash怎么用?C# HMACSHA256.ComputeHash使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.HMACSHA256
的用法示例。
在下文中一共展示了HMACSHA256.ComputeHash方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PHash
private static byte[] PHash(byte[] secret, byte[] seed, int iterations)
{
using (HMACSHA256 hmac = new HMACSHA256(secret))
{
byte[][] a = new byte[iterations + 1][];
a[0] = seed;
for (int i = 0; i < iterations; i++)
{
a[i + 1] = hmac.ComputeHash(a[i]);
}
byte[] prf = new byte[iterations * 32];
byte[] buffer = new byte[32 + seed.Length];
Buffer.BlockCopy(seed, 0, buffer, 32, seed.Length);
for (int i = 0; i < iterations; i++)
{
Buffer.BlockCopy(a[i + 1], 0, buffer, 0, 32);
byte[] hash = hmac.ComputeHash(buffer);
Buffer.BlockCopy(hash, 0, prf, 32 * i, 32);
}
return prf;
}
}
示例2: Generate
public static byte[] Generate(byte[] password, byte[] salt, int iterationCount, int byteCount)
{
if (iterationCount <= 0)
throw new ArgumentOutOfRangeException("iterationCount", "Iteration count should be positive");
if (byteCount < 0)
throw new ArgumentOutOfRangeException("byteCount", "Byte count should be nonnegative");
using (var hmac = new HMACSHA256())
{
hmac.Key = password;
// Prepare hash input (salt + block index)
var hashInputSize = salt.Length + 4;
var hashInput = new byte[hashInputSize];
salt.CopyTo(hashInput, 0);
hashInput[hashInputSize - 4] = 0;
hashInput[hashInputSize - 3] = 0;
hashInput[hashInputSize - 2] = 0;
hashInput[hashInputSize - 1] = 0;
var bytes = new byte[byteCount];
var hashSize = hmac.HashSize / 8;
var blockCount = (byteCount + hashSize - 1) / hashSize;
for (var i = 0; i < blockCount; ++i)
{
// Increase 32-bit big-endian block index at the end of the hash input buffer
if (++hashInput[hashInputSize - 1] == 0)
if (++hashInput[hashInputSize - 2] == 0)
if (++hashInput[hashInputSize - 3] == 0)
++hashInput[hashInputSize - 4];
var hashed = hmac.ComputeHash(hashInput);
var block = hashed;
for (var j = 1; j < iterationCount; ++j)
{
hashed = hmac.ComputeHash(hashed);
for (var k = 0; k < hashed.Length; ++k)
{
block[k] ^= hashed[k];
}
}
var offset = i * hashSize;
var size = Math.Min(hashSize, byteCount - offset);
Array.Copy(block, 0, bytes, offset, size);
}
return bytes;
}
}
示例3: ToString
public override string ToString()
{
StringBuilder content = new StringBuilder();
content.Append("Issuer=").Append(this.Issuer);
for (int i = 0; i < this.claims.Count; i++)
{
var claim = claims[i];
if (i == 0)
content.Append('&').Append("Claims").Append('=');
content.AppendFormat("{0}:{1}:{2}", claim.ClaimType, claim.Resource, claim.Right);
if (i < this.claims.Count - 1)
content.Append(',');
}
content.Append("&ExpiresOn=").Append(this.ExpiresOn);
if (!string.IsNullOrWhiteSpace(this.Audience))
{
content.Append("&Audience=").Append(this.Audience);
}
using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
{
byte[] signatureBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(content.ToString()));
string signature = System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(signatureBytes));
content.Append("&HMACSHA256=").Append(signature);
}
return content.ToString();
}
示例4: HMAC_ASCII_SHA256_Base64Url
public static string HMAC_ASCII_SHA256_Base64Url(string input, byte[] key)
{
HMACSHA256 hmacsha256 = new HMACSHA256(key);
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
byte[] hashBytes = hmacsha256.ComputeHash(inputBytes);
return Base64Utility.UrlEncode(hashBytes);
}
示例5: SendAsync
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
string requestContentBase64String = string.Empty;
string requestUri = System.Web.HttpUtility.UrlEncode(request.RequestUri.AbsoluteUri.ToLower());
//Checking if the request contains body, usually will be null wiht HTTP GET
if (request.Content != null)
{
using (var md5 = MD5.Create())
{
var content = await request.Content.ReadAsByteArrayAsync();
//Hashing the request body, any change in request body will result in different hash, we'll incure message integrity
var requestContentHash = md5.ComputeHash(content);
requestContentBase64String = Convert.ToBase64String(requestContentHash);
}
}
//create random nonce for each request
var nonce = Guid.NewGuid().ToString("N");
//Creating the raw signature string
var signatureRawData = string.Concat(_apiKey, "POST", requestUri, nonce, requestContentBase64String);
var secretKeyByteArray = Convert.FromBase64String(_apiSecret);
var signature = Encoding.UTF8.GetBytes(signatureRawData);
using (var hmac = new HMACSHA256(secretKeyByteArray))
{
var signatureBytes = hmac.ComputeHash(signature);
var requestSignatureBase64String = Convert.ToBase64String(signatureBytes);
//Setting the values in the Authorization header using custom scheme (amx)
request.Headers.Authorization = new AuthenticationHeaderValue("amx", string.Format("{0}:{1}:{2}", _apiKey, requestSignatureBase64String, nonce));
}
return await base.SendAsync(request, cancellationToken);
}
示例6: HDKFSHA256ExpandWithInfo
/// <summary>
/// C# version of the Objective-C algorithm found in Firefox Home.
/// </summary>
/// <param name="key"></param>
/// <param name="info"></param>
/// <param name="length"></param>
/// <returns></returns>
public static byte[] HDKFSHA256ExpandWithInfo(this byte[] key, byte[] info, int length)
{
int iterations = (length + SHA256_DIGEST_LENGTH - 1) / SHA256_DIGEST_LENGTH;
byte[] tr = new byte[iterations * SHA256_DIGEST_LENGTH];
byte[] tn = new byte[0];
byte[] tnSha = new byte[0];
int lengthCopied = 0;
using (HMACSHA256 hmacSha256 = new HMACSHA256(key))
{
for (int i = 0; i < iterations; i++)
{
tn = new byte[tnSha.Length + info.Length + 1];
Array.Copy(tnSha, 0, tn, 0, tnSha.Length);
Array.Copy(info, 0, tn, tnSha.Length, info.Length);
tn[tnSha.Length + info.Length] = (byte) (i + 1);
tnSha = hmacSha256.ComputeHash(tn);
Array.Copy(tnSha, 0, tr, lengthCopied, tnSha.Length);
lengthCopied += tnSha.Length;
}
}
byte[] result = new byte[length];
Array.Copy(tr, result, length);
return result;
}
示例7: GenerateHMACSHA256AuthorisationToken
public static string GenerateHMACSHA256AuthorisationToken(string sessionToken, string sharedSecret, out string dateString)
{
if (String.IsNullOrWhiteSpace(sharedSecret))
{
throw new ArgumentNullException("sharedSecret");
}
if (String.IsNullOrWhiteSpace(sessionToken))
{
throw new ArgumentNullException("sessionToken");
}
// Generate UTC ISO 8601 date string.
dateString = DateTime.UtcNow.ToString("o");
// 1. Combine the Token and current date time in UTC using ISO 8601 format.
byte[] messageBytes = Encoding.ASCII.GetBytes(sessionToken + ":" + dateString);
// 2. Calculate the HMAC SHA 256 using the Consumer Secret and then Base64 encode.
byte[] keyBytes = Encoding.ASCII.GetBytes(sharedSecret);
string hmacsha256EncodedString;
using (HMACSHA256 hmacsha256 = new HMACSHA256(keyBytes))
{
byte[] hashMessage = hmacsha256.ComputeHash(messageBytes);
hmacsha256EncodedString = Convert.ToBase64String(hashMessage);
}
// 3. Combine the Token with the resulting string from above separated by a colon.
string combinedMessage = sessionToken + ":" + hmacsha256EncodedString;
// 4. Base64 encode this string.
string base64EncodedString = Convert.ToBase64String(Encoding.ASCII.GetBytes(combinedMessage));
// 5. Prefix this string with the Authentication Method and a space.
return AuthorisationMethod.HMACSHA256.ToString() + " " + base64EncodedString;
}
示例8: DecodeFile
// Decrypt the encoded file and compare to original file.
public static bool DecodeFile(byte[] key, String sourceFile)
{
// Initialize the keyed hash object.
HMACSHA256 hmacsha256 = new HMACSHA256(key);
// Create an array to hold the keyed hash value read from the file.
byte[] storedHash = new byte[hmacsha256.HashSize / 8];
// Create a FileStream for the source file.
FileStream inStream = new FileStream(sourceFile, FileMode.Open);
// Read in the storedHash.
inStream.Read(storedHash, 0, storedHash.Length);
// Compute the hash of the remaining contents of the file.
// The stream is properly positioned at the beginning of the content,
// immediately after the stored hash value.
byte[] computedHash = hmacsha256.ComputeHash(inStream);
// compare the computed hash with the stored value
for (int i = 0; i < storedHash.Length; i++)
{
if (computedHash[i] != storedHash[i])
{
Console.WriteLine("Hash values differ! Encoded file has been tampered with!");
return false;
}
}
Console.WriteLine("Hash values agree -- no tampering occurred.");
return true;
}
示例9: hmacSHA256
static byte[] hmacSHA256(String data, String key)
{
using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key)))
{
return hmac.ComputeHash(Encoding.ASCII.GetBytes(data));
}
}
示例10: CreateToken
public static string CreateToken(string message, string key)
{
var myhmacsha1 = new HMACSHA256(Encoding.ASCII.GetBytes(key));
var byteArray = Encoding.ASCII.GetBytes(message);
var stream = new MemoryStream(byteArray);
return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + $"{e:x2}", s => s);
}
示例11: ComputeHmac
public byte[] ComputeHmac(byte[] sessionKey, byte[] encrpytedData)
{
using (var hmac = new HMACSHA256(sessionKey))
{
return hmac.ComputeHash(encrpytedData);
}
}
示例12: Main
public static void Main (string[] args)
{
var host = "https://api.coinbase.com/";
var apiKey = "yourApiKey";
var apiSecret = "youApiSecret";
var unixTimestamp = (Int32)(DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1))).TotalSeconds;
var currency = "USD";
var message = string.Format ("{0}GET/v2/prices/spot?currency={1}", unixTimestamp.ToString (), currency);
byte[] secretKey = Encoding.UTF8.GetBytes (apiSecret);
HMACSHA256 hmac = new HMACSHA256 (secretKey);
hmac.Initialize ();
byte[] bytes = Encoding.UTF8.GetBytes (message);
byte[] rawHmac = hmac.ComputeHash (bytes);
var signature = rawHmac.ByteArrayToHexString ();
var price = host
.AppendPathSegment ("v2/prices/spot")
.SetQueryParam ("currency", currency)
.WithHeader ("CB-ACCESS-SIGN", signature)
.WithHeader ("CB-ACCESS-TIMESTAMP", unixTimestamp)
.WithHeader ("CB-ACCESS-KEY", apiKey)
.GetJsonAsync<dynamic> ()
.Result;
Console.WriteLine (price.ToString (Formatting.None));
Console.ReadLine ();
}
示例13: sign
bool m_isCheckAmazonAwsInstancesEmailWasSent = false; // to avoid sending the same warning email many times; send only once
//# Key derivation functions. See:
//# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
internal byte[] sign(byte[] key, string msg)
{
HMACSHA256 hmac = new HMACSHA256(key);
var computedDigest = hmac.ComputeHash(Encoding.UTF8.GetBytes(msg));
return computedDigest;
//return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest();
}
示例14: Verify
public static bool Verify(string apikey, string token, string timestamp, string signature)
{
var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(apikey));
var sigBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(timestamp + token));
string sigString = BitConverter.ToString(sigBytes).Replace("-", "");
return signature.Equals(sigString, StringComparison.OrdinalIgnoreCase);
}
示例15: DropboxWebHookReceiverTests
public DropboxWebHookReceiverTests()
{
_settings = new SettingsDictionary();
_settings["MS_WebHookReceiverSecret_Dropbox"] = TestSecret;
_config = HttpConfigurationMock.Create(new Dictionary<Type, object> { { typeof(SettingsDictionary), _settings } });
_context = new HttpRequestContext { Configuration = _config };
_receiverMock = new Mock<DropboxWebHookReceiver> { CallBase = true };
_getRequest = new HttpRequestMessage();
_getRequest.SetRequestContext(_context);
_postRequest = new HttpRequestMessage() { Method = HttpMethod.Post };
_postRequest.SetRequestContext(_context);
_postRequest.Content = new StringContent(TestContent, Encoding.UTF8, "application/json");
byte[] secret = Encoding.UTF8.GetBytes(TestSecret);
using (var hasher = new HMACSHA256(secret))
{
byte[] data = Encoding.UTF8.GetBytes(TestContent);
byte[] testHash = hasher.ComputeHash(data);
_testSignature = EncodingUtilities.ToHex(testHash);
}
}