本文整理汇总了C#中System.Security.Cryptography.HMACSHA1类的典型用法代码示例。如果您正苦于以下问题:C# HMACSHA1类的具体用法?C# HMACSHA1怎么用?C# HMACSHA1使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HMACSHA1类属于System.Security.Cryptography命名空间,在下文中一共展示了HMACSHA1类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: WithS3Authentication
//--- Extension Methods ---
/// <summary>
/// Add a Plug Pre-Handler to attach the appropriate auth header.
/// </summary>
/// <param name="plug">Plug instance to base operation on.</param>
/// <param name="privateKey">Amazon S3 private key.</param>
/// <param name="publicKey">Amazon S3 public key.</param>
/// <returns>New Plug instance with pre-handler.</returns>
public static Plug WithS3Authentication(this Plug plug, string privateKey, string publicKey)
{
return plug.WithPreHandler((verb, uri, normalizedUri, message) => {
// add amazon date header (NOTE: this must be the real wall-time)
var date = DateTime.UtcNow.ToString("r");
message.Headers[AWS_DATE] = date;
// add authorization header
var authString = new StringBuilder()
.Append(verb)
.Append("\n")
.Append(message.Headers[DreamHeaders.CONTENT_MD5])
.Append("\n")
.Append(message.ContentType.ToString())
.Append("\n")
.Append("\n");
foreach(var header in message.Headers.OrderBy(x => x.Key.ToLowerInvariant(), StringComparer.Ordinal)) {
if(!header.Key.StartsWithInvariantIgnoreCase("x-amz-")) {
continue;
}
authString.AppendFormat("{0}:{1}\n", header.Key.ToLowerInvariant(), header.Value);
}
authString.Append(normalizedUri.Path);
var hmac = new HMACSHA1(Encoding.UTF8.GetBytes(privateKey));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(authString.ToString())));
message.Headers.Authorization = string.Format("AWS {0}:{1}", publicKey, signature);
message.Headers.ContentType = message.ContentType;
return message;
});
}
开发者ID:nataren,项目名称:DReAM,代码行数:39,代码来源:S3PlugEx.cs
示例2: Sign
private static string Sign(string url, string appSid, string appKey)
{
// Add AppSid parameter.
UriBuilder uriBuilder = new UriBuilder(url);
if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
uriBuilder.Query = uriBuilder.Query.Substring(1) + "&appSID=" + appSid;
else
uriBuilder.Query = "appSID=" + appSid;
// Remove final slash here as it can be added automatically.
uriBuilder.Path = uriBuilder.Path.TrimEnd('/');
// Compute the hash.
byte[] privateKey = Encoding.UTF8.GetBytes(appKey);
HMACSHA1 algorithm = new HMACSHA1(privateKey);
byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri);
byte[] hash = algorithm.ComputeHash(sequence);
string signature = Convert.ToBase64String(hash);
// Remove invalid symbols.
signature = signature.TrimEnd('=');
signature = HttpUtility.UrlEncode(signature);
// Convert codes to upper case as they can be updated automatically.
signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
// Add the signature to query string.
return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature);
}
开发者ID:mrtaunus,项目名称:Aspose_Cloud_SDK_For_.NET,代码行数:31,代码来源:ServiceController.cs
示例3: GetOAuthHeader
internal static string GetOAuthHeader(Dictionary<string, string> parameters, string url, string comsumeSercret, string tokenSecret)
{
parameters = parameters.OrderBy(x => x.Key).ToDictionary(v => v.Key, v => v.Value);
string concat = string.Empty;
string OAuthHeader = "OAuth ";
foreach (var key in parameters.Keys)
{
concat += key + "=" + parameters[key] + "&";
OAuthHeader += key + "=" + "\"" + parameters[key] + "\",";
}
concat = concat.Remove(concat.Length - 1, 1);
concat = EncodeToUpper(concat);
concat = "POST&" + EncodeToUpper(url) + "&" + concat;
byte[] content = Encoding.UTF8.GetBytes(concat);
HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(comsumeSercret + "&" + tokenSecret));
hmac.ComputeHash(content);
string hash = Convert.ToBase64String(hmac.Hash);
hash = hash.Replace("-", "");
OAuthHeader += "oauth_signature=\"" + EncodeToUpper(hash) + "\"";
return OAuthHeader;
}
开发者ID:kamaelyoung,项目名称:social_share,代码行数:31,代码来源:TwitterOauthClient.cs
示例4: GetSimInfo
public async Task<bool> GetSimInfo()
{
Tools.Tools.SetProgressIndicator(true);
try
{
Tools.Tools.SetProgressIndicator(true);
SystemTray.ProgressIndicator.Text = "loading sims";
var client = new VikingsApi();
OAuthUtility.ComputeHash = (key, buffer) =>
{
using (var hmac = new HMACSHA1(key))
{
return hmac.ComputeHash(buffer);
}
};
string json = await client.GetInfo(new AccessToken((string) IsolatedStorageSettings.ApplicationSettings["tokenKey"], (string) IsolatedStorageSettings.ApplicationSettings["tokenSecret"]), client.Sim, new KeyValuePair {content = "1", name = "alias"});
Sims = JsonConvert.DeserializeObject<Sim[]>(json);
Tools.Tools.SetProgressIndicator(false);
return true;
}
catch (Exception)
{
Message.ShowToast("Could not load sim information, please try again later");
return false;
}
}
开发者ID:JanJoris,项目名称:VikingApp,代码行数:26,代码来源:MainPivotViewmodel.cs
示例5: Sign
protected internal Uri Sign(Uri _uri)
{
if (_uri == null)
throw new ArgumentNullException("_uri");
if (string.IsNullOrWhiteSpace(this.Key))
throw new ArgumentException("Invalid signing key.");
if (this.ClientId == null)
throw new NullReferenceException("ClientID");
if (!this.ClientId.StartsWith("gme-"))
throw new ArgumentException("A user ID must start with 'gme-'.");
var _urlSegmentToSign = _uri.LocalPath + _uri.Query + "&client=" + this.ClientId;
var _privateKey = SignableRequest.FromBase64UrlString(this.Key);
byte[] _signature;
using (var _algorithm = new HMACSHA1(_privateKey))
{
_signature = _algorithm.ComputeHash(Encoding.ASCII.GetBytes(_urlSegmentToSign));
}
return new Uri(_uri.Scheme + "://" + _uri.Host + _urlSegmentToSign + "&signature=" + SignableRequest.ToBase64UrlString(_signature));
}
开发者ID:JasonBSteele,项目名称:GoogleApi,代码行数:25,代码来源:SignableRequest.cs
示例6: GenerateSignature
/// <summary>
/// Generates a signature using the specified signatureType
/// </summary>
/// <param name="httpMethod">The http method used</param>
/// <param name="url">The full url to be signed</param>
/// <param name="parametersIn">The collection of parameters to sign</param>
/// <param name="consumerSecret">The OAuth consumer secret used to generate the signature</param>
/// <returns>A base64 string of the hash value</returns>
public static string GenerateSignature(string httpMethod, Uri url, NameValueCollection parametersIn, string consumerSecret)
{
// Work with a copy of the parameters so the caller's data is not changed
var parameters = new NameValueCollection(parametersIn);
// https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
// The query component is parsed into a list of name/value pairs by treating it as an
// "application/x-www-form-urlencoded" string, separating the names and values and
// decoding them as defined by [W3C.REC - html40 - 19980424], Section 17.13.4.
//
// Unescape the query so that it is not doubly escaped by UrlEncodingParser.
var querystring = new UrlEncodingParser(Uri.UnescapeDataString(url.Query));
parameters.Add(querystring);
var signatureBase = GenerateSignatureBase(httpMethod, url, parameters);
// Note that in LTI, the TokenSecret (second part of the key) is blank
var hmacsha1 = new HMACSHA1
{
Key = Encoding.ASCII.GetBytes($"{consumerSecret.ToRfc3986EncodedString()}&")
};
var dataBuffer = Encoding.ASCII.GetBytes(signatureBase);
var hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
开发者ID:andyfmiller,项目名称:LtiLibrary,代码行数:35,代码来源:OAuthUtility.cs
示例7: HMAC
protected static byte[] HMAC(byte[] data, string key)
{
using (var hmac = new HMACSHA1(data, true))
{
return hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
}
}
开发者ID:rob-blackbourn,项目名称:JetBlack.Authentication,代码行数:7,代码来源:ScramSha1.cs
示例8: IsValidRequest
private static bool IsValidRequest(HttpActionContext context, string authToken, string urlOverride = null)
{
var value = new StringBuilder();
// Take the host URL from the request, or use the URL override if there is one
var fullUrl = string.IsNullOrEmpty(urlOverride) ? context.Request.RequestUri.ToString() : urlOverride;
value.Append(fullUrl);
var request = HttpContext.Current.Request;
// If POST request, concatenate the key-value pairs in the request
if (context.Request.Method == HttpMethod.Post)
{
var sortedKeys = request.Form.AllKeys.OrderBy(k => k, StringComparer.Ordinal).ToList();
foreach (var key in sortedKeys)
{
value.Append(key);
value.Append(request.Form[key]);
}
}
// Create signature using AuthToken as key
var sha1 = new HMACSHA1(Encoding.UTF8.GetBytes(authToken));
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(value.ToString()));
var encoded = Convert.ToBase64String(hash);
var sig = request.Headers["X-Twilio-Signature"];
// Compare our signatures
return sig == encoded;
}
开发者ID:jonasrafael,项目名称:Samples,代码行数:32,代码来源:ValidateTwilioRequestAttribute.cs
示例9: AuthorizationHeader
private string AuthorizationHeader(string status) {
var oauth_token = UserToken;
var oauth_token_secret = UserSecret;
var oauth_consumer_key = AppToken;
var oauth_consumer_secret = AppSecret;
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(
DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0,
DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
var resource_url = "https://api.twitter.com/1.1/statuses/update.json";
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&status={6}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
Uri.EscapeDataString(status)
);
baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url),
"&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
return authHeader;
}
开发者ID:hpneo,项目名称:CheckinApp,代码行数:60,代码来源:Twitter.cs
示例10: EncodePassword
//EncodePassword:Encrypts, Hashes, or leaves the password clear based on the PasswordFormat.
public string EncodePassword(string password)
{
var encodedPassword = password;
var hash = new HMACSHA1 { Key = HexToByte(_machineKey.ValidationKey) };
encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
return encodedPassword;
}
开发者ID:Aaronontheweb,项目名称:PeerLearningSite,代码行数:8,代码来源:PasswordHelper.cs
示例11: ComputeCombinedKey
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();
}
}
}
开发者ID:bencoveney,项目名称:Thinktecture.IdentityModel.40,代码行数:60,代码来源:KeyGenerator.cs
示例12: GetSignature
public string GetSignature()
{
var policy64 = GetPolicyInBase64();
byte[] b64Key = Encoding.ASCII.GetBytes(CManager.Settings.AWSSecretAccessKey);
var hmacSha1 = new HMACSHA1(b64Key);
return Convert.ToBase64String(hmacSha1.ComputeHash(Encoding.ASCII.GetBytes(policy64)));
}
开发者ID:AbbTek,项目名称:6weeks-challenge,代码行数:7,代码来源:AWSS3upload.cs
示例13: EncodePassword
private static string EncodePassword(string password)
{
HMACSHA1 hash = new HMACSHA1 {Key = HexToByte(key)};
string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
return encodedPassword;
}
开发者ID:divayht,项目名称:YouFood,代码行数:7,代码来源:PasswordManager.cs
示例14: GenerateValidationKey
public string GenerateValidationKey()
{
using (var validObj = new HMACSHA1())
{
return BinaryToHex(validObj.Key);
}
}
开发者ID:mdavid626,项目名称:triton,代码行数:7,代码来源:MachineKeyGenerator.cs
示例15: GeneratePin
/// <summary>
/// Generates a pin by hashing a key and counter.
/// </summary>
private static string GeneratePin(byte[] key, long counter)
{
//Get counter bytes (in big endian order)
var counterBytes = BitConverter.GetBytes(counter);
if (BitConverter.IsLittleEndian)
Array.Reverse(counterBytes);
byte[] hash;
using (var hmac = new HMACSHA1(key))
hash = hmac.ComputeHash(counterBytes);
var offset = hash[hash.Length - 1] & 0xF;
var selectedBytes = new byte[sizeof(int)];
Buffer.BlockCopy(hash, offset, selectedBytes, 0, sizeof(int));
//spec interprets bytes in big-endian order
if (BitConverter.IsLittleEndian)
Array.Reverse(selectedBytes);
var selectedInteger = BitConverter.ToInt32(selectedBytes, 0);
//remove the most significant bit for interoperability per spec
var truncatedHash = selectedInteger & 0x7FFFFFFF;
//generate number of digits for given pin length
var pin = truncatedHash % _pinModulo;
return pin.ToString(CultureInfo.InvariantCulture).PadLeft(PIN_LENGTH, '0');
}
开发者ID:WildGenie,项目名称:Bastet-Legacy,代码行数:33,代码来源:GoogleAuthenticator.cs
示例16: GenerateOTP
/**
* Generate a one-time password
*
* @param integer $input : number used to seed the hmac hash function.
* This number is usually a counter (HOTP) or calculated based on the current
* timestamp (see TOTP class).
* @return integer the one-time password
*/
public int GenerateOTP(Int64 input)
{
Byte[] secretBytes = Guid.Parse(this.secret).ToByteArray();
HMAC hashgenerator = new HMACSHA1(secretBytes);
hashgenerator.ComputeHash(IntToByteString(input));
string hash = "";
foreach (byte b in hashgenerator.Hash)
{
hash += b.ToString("x2");
}
List<int> hmac = new List<int>();
foreach (string s in hash.Split(2))
{
hmac.Add(Int32.Parse(s, System.Globalization.NumberStyles.HexNumber));
}
// The offset is the last nibble of the hash
int offset = hmac[19] & 0xf;
// Code is 4 bytes starting at the offset
int code = (hmac[offset + 0] & 0x7F) << 24 |
(hmac[offset + 1] & 0xFF) << 16 |
(hmac[offset + 2] & 0xFF) << 8 |
(hmac[offset + 3] & 0xFF);
return code % (int)Math.Pow((double)10, (double)this.digits);
}
开发者ID:nrag,项目名称:yapper,代码行数:38,代码来源:OTP.cs
示例17: Application_Start
protected void Application_Start()
{
OAuthUtility.ComputeHash = (key, buffer) => { using (var hmac = new HMACSHA1(key)) { return hmac.ComputeHash(buffer); } };
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
开发者ID:lobrien,项目名称:Fitbit.NET,代码行数:7,代码来源:Global.asax.cs
示例18: GetAuthorizationHeader
public static string GetAuthorizationHeader(string macKeyIdentifier, string macKey, string macAlgorithm, string method, Uri uri)
{
TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
string timestamp = ((int)t.TotalSeconds).ToString();
string nonce = new Random().Next().ToString();
string normalizedString = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n\n", timestamp, nonce, method, uri.PathAndQuery, uri.Host, uri.Port);
HashAlgorithm hashGenerator = null;
if (macAlgorithm == "hmac-sha-256")
{
hashGenerator = new HMACSHA256(Encoding.ASCII.GetBytes(macKey));
}
else if (macAlgorithm == "hmac-sha-1")
{
hashGenerator = new HMACSHA1(Encoding.ASCII.GetBytes(macKey));
}
else
{
throw new InvalidOperationException("Unsupported MAC algorithm");
}
string hash = System.Convert.ToBase64String(hashGenerator.ComputeHash(Encoding.ASCII.GetBytes(normalizedString)));
StringBuilder authorizationHeader = new StringBuilder();
authorizationHeader.AppendFormat(@"id=""{0}"",ts=""{1}"",nonce=""{2}"",mac=""{3}""", macKeyIdentifier, timestamp, nonce, hash);
return authorizationHeader.ToString();
}
开发者ID:tomasmcguinness,项目名称:tent.io-csharp,代码行数:31,代码来源:Helper.cs
示例19: SetAuth
public override void SetAuth(HttpWebRequest request, Stream body)
{
byte[] secretKey = Encoding.ASCII.GetBytes(Config.SECRET_KEY);
using (HMACSHA1 hmac = new HMACSHA1(secretKey))
{
string pathAndQuery = request.Address.PathAndQuery;
byte[] pathAndQueryBytes = Encoding.ASCII.GetBytes(pathAndQuery);
using (MemoryStream buffer = new MemoryStream())
{
buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length);
buffer.WriteByte((byte)'\n');
if (request.ContentType == "application/x-www-form-urlencoded" && body != null)
{
if (!body.CanSeek)
{
throw new Exception("stream can not seek");
}
StreamUtil.Copy(body, buffer);
body.Seek(0, SeekOrigin.Begin);
}
byte[] digest = hmac.ComputeHash(buffer.ToArray());
string digestBase64 = Base64UrlSafe.Encode(digest);
string authHead = "QBox " + Config.ACCESS_KEY + ":" + digestBase64;
request.Headers.Add("Authorization", authHead);
}
}
}
开发者ID:89sos98,项目名称:csharp-sdk,代码行数:28,代码来源:DigestAuthClient.cs
示例20: ComputeHash
public static string ComputeHash(string qs)
{
byte[] textBytes = Encoding.UTF8.GetBytes(qs);
HMACSHA1 hashAlgorithm = new HMACSHA1(Security.HexToByteArray(_hashKey));
byte[] hash = hashAlgorithm.ComputeHash(textBytes);
return Security.ByteArrayToHex(hash);
}
开发者ID:garcus,项目名称:QueryTampering,代码行数:7,代码来源:Security.cs
注:本文中的System.Security.Cryptography.HMACSHA1类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论