public static string GenerateUrlToken(string controllerName, string actionName, RouteValueDictionary argumentParams, string password) { //// The URL hash is dynamic by assign a dynamic key in each session. So //// eventhough your URL is stolen, it will not work in other session if (HttpContext.Current.Session["url_dynamickey"] == null) { HttpContext.Current.Session["url_dynamickey"] = RandomString(); } // The salt include the dynamic session key and valid for an hour. var salt = HttpContext.Current.Session["url_dynamickey"] + DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour; // generating the partial url var stringToToken = controllerName + "/" + actionName + "/"; stringToToken = argumentParams.Where(item => item.Key != "controller" && item.Key != "action" && item.Key != "urltoken").Aggregate(stringToToken, (current, item) => current + (item.Value)); // Converting the salt in to a byte array var saltValueBytes = System.Text.Encoding.ASCII.GetBytes(salt); // Encrypt the salt bytes with the password var key = new Rfc2898DeriveBytes(password, saltValueBytes); // get the key bytes from the above process var secretKey = key.GetBytes(16); // generate the hash var tokenHash = new HMACSHA1(secretKey); tokenHash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(stringToToken)); // convert the hash to a base64string var token = Convert.ToBase64String(tokenHash.Hash).Replace("/", "_"); return token; }
public static string hash_hmac(string signatureString, string secretKey) { HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(secretKey)); byte[] buffer = Encoding.UTF8.GetBytes(signatureString); string result = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower(); return Convert.ToBase64String(Encoding.UTF8.GetBytes(result)); }
private static string SignData(string to_sign) { using (var signature = new HMACSHA1(key: Encoding.UTF8.GetBytes("<<YOUR_AWS_SECRET_KEY>>"))) { var bytes = Encoding.UTF8.GetBytes(to_sign); var hash = signature.ComputeHash(bytes); return Convert.ToBase64String(hash); } }
public string GenerateHeader (string url, string method) { ResetNew(); // create a signature var parameters = (from p in params_ where !except_parameters.Contains(p.Key) orderby p.Key, p.Value select p); string param_string = ""; foreach (var item in parameters) { if (param_string.Length > 0) param_string += "&"; param_string += string.Format("{0}={1}", UrlEncode(item.Key), UrlEncode(item.Value)); } string base_string = string.Format("{0}&{1}&{2}", UrlEncode(method), UrlEncode(url), UrlEncode(param_string)); string key_string = string.Format("{0}&{1}", UrlEncode(params_[kOAuthConsumerSecret]), UrlEncode(params_[kOAuthTokenSecret])); HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(key_string)); byte[] bytes = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(base_string)); string signature = Convert.ToBase64String(bytes); // oauth string parameters = from p in params_ where oauth_parameters.Contains(p.Key) orderby p.Key, UrlEncode(p.Value) select p; string header = "OAuth "; foreach (var item in parameters) { if (item.Key == kOAuthVersion) header += string.Format("{0}=\"{1}\"", item.Key, item.Value); else header += string.Format("{0}=\"{1}\",", item.Key, item.Value); if (item.Key == kOAuthNonce) header += string.Format("{0}=\"{1}\",", kOAuthSignature, UrlEncode(signature)); } return header; }
private string getHMAC(string signatureString, string secretKey) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] keyByte = encoding.GetBytes(secretKey); HMACSHA1 hmac = new HMACSHA1(keyByte); byte[] messageBytes = encoding.GetBytes(signatureString); byte[] hashmessage = hmac.ComputeHash(messageBytes); return ByteArrayToHexString(hashmessage); }
public virtual void onButtonClick(object sender, EventArgs e) { // The HMAC secret as configured in the skin string hmacSecret = "TheHM4C$ecretF0rTheSk1n"; // Generate the signing string string signingString = paymentAmount.Text + currencyCode.Text + shipBeforeDate.Text + merchantReference.Text + skinCode.Text + merchantAccount.Text + sessionValidity.Text + shopperEmail.Text; // Values are always transferred using UTF-8 encoding System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding(); // Calculate the HMAC HMACSHA1 myhmacsha1 = new HMACSHA1(encoding.GetBytes(hmacSecret)); merchantSig.Text = System.Convert.ToBase64String(myhmacsha1.ComputeHash(encoding.GetBytes(signingString))); myhmacsha1.Clear(); // Ready to pay button1.Text = "Pay"; }
static Boolean Test() { Boolean bRes = true; Byte[] abKey1 = {0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b}; Byte[] abData1 = (new System.Text.ASCIIEncoding()).GetBytes("Hi There"); Byte[] abDigest1 = {0xb6, 0x17, 0x31, 0x86, 0x55, 0x05, 0x72, 0x64, 0xe2, 0x8b, 0xc0, 0xb6, 0xfb, 0x37, 0x8c, 0x8e, 0xf1, 0x46, 0xbe, 0x00}; Byte[] abKey2 = (new System.Text.ASCIIEncoding()).GetBytes("Jefe"); Byte[] abData2 = (new System.Text.ASCIIEncoding()).GetBytes("what do ya want for nothing?"); Byte[] abDigest2 = {0xef, 0xfc, 0xdf, 0x6a, 0xe5, 0xeb, 0x2f, 0xa2, 0xd2, 0x74, 0x16, 0xd5, 0xf1, 0x84, 0xdf, 0x9c, 0x25, 0x9a, 0x7c, 0x79}; Console.WriteLine("Testing rc21 hash..."); HMACSHA1 rc21 = new HMACSHA1(abKey1); HMACSHA1 rc22 = new HMACSHA1(abKey2); rc21.ComputeHash(abData1); rc22.ComputeHash(abData2); Console.WriteLine("The computed hash #1 is : "); PrintByteArray(rc21.Hash); Console.WriteLine("The correct hash #1 is : "); PrintByteArray(abDigest1); if(Compare(rc21.Hash, abDigest1)) { Console.WriteLine("CORRECT"); } else { Console.WriteLine("INCORRECT"); bRes = false; } Console.WriteLine("The computed hash #2 is : "); PrintByteArray(rc22.Hash); Console.WriteLine("The correct hash #2 is : "); PrintByteArray(abDigest2); if(Compare(rc22.Hash, abDigest2)) { Console.WriteLine("CORRECT"); } else { Console.WriteLine("INCORRECT"); bRes = false; } return bRes; }
public static string Hash(this Exception exc) { if (exc == null) { return(string.Empty); } var sb = new StringBuilder(); AddException(sb, exc); if (exc.InnerException != null) { AddException(sb, exc.InnerException); } // DNN-8845: using a FIPS compliant HashAlgorithm using (var hasher = new HMACSHA1()) { var byteArray = hasher.ComputeHash(Encoding.Unicode.GetBytes(sb.ToString().ToLower())); return(Convert.ToBase64String(byteArray)); } }
/// Computes RFC 2104-compliant HMAC signature for request parameters /// Implements AWS Signature, as per following spec: /// /// Sort all query parameters (including SignatureVersion and excluding Signature, /// the value of which is being created), ignoring case. Optional parameters not /// included in the request should not be canonicalized as "empty" parameters. /// That is, if no value for a ParameterA is specified in the request, there /// should not be a ParameterA entry in the canonicalized string. /// /// Iterate over the sorted list and append the parameter name (in original case) /// and then its value. Do not URL-encode the parameter values before constructing /// this string. There are no separators. public static string GetSignature(IDictionary <String, String> parameters, string secretKey) { var sorted = new SortedDictionary <string, string>(); foreach (var pair in parameters) { sorted.Add(pair.Key, pair.Value); } var sb = new StringBuilder(); foreach (var kvp in sorted) { sb.Append(kvp.Key); sb.Append(kvp.Value); } var data = sb.ToString(); Encoding ae = new UTF8Encoding(); var signature = new HMACSHA1(ae.GetBytes(secretKey)); return(Convert.ToBase64String(signature.ComputeHash(ae.GetBytes(data.ToCharArray())))); }
public static T FromJSON <T>(string url, string publicAuthKey, string privateAuthKey) where T : class { HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest; DateTime date = DateTime.Now.ToUniversalTime(); req.Date = date; string stringToSign = req.Method + "\n" + date.ToString("r") + "\n" + req.RequestUri.AbsolutePath + "\n"; byte[] buffer = Encoding.UTF8.GetBytes(stringToSign); HMACSHA1 hmac = new HMACSHA1(Encoding.UTF8.GetBytes(privateAuthKey)); string signature = Convert.ToBase64String(hmac.ComputeHash(buffer)); req.Headers[HttpRequestHeader.Authorization] = "BNET " + publicAuthKey + ":" + signature; return(FromJSON <T>(req)); }
public string GenerateSignature(string url) { var encoding = new ASCIIEncoding(); var uri = new Uri(url); // converting key to bytes will throw an exception, need to replace '-' and '_' characters first. string usablePrivateKey = SigningKey.Replace("-", "+").Replace("_", "/"); byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey); byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query); // compute the hash var algorithm = new HMACSHA1(privateKeyBytes); byte[] hash = algorithm.ComputeHash(encodedPathAndQueryBytes); // convert the bytes to string and make url-safe by replacing '+' and '/' characters string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_"); // Add the signature to the existing URI. return(uri.Scheme + "://" + uri.Host + uri.LocalPath + uri.Query + "&signature=" + signature); }
/// <summary> /// Generate an OAuth signature from OAuth header values /// </summary> internal string GenerateSignature(string url, Dictionary <string, string> data) { var sigString = string.Join( "&", data .Union(data) .Select(kvp => string.Format("{0}={1}", Uri.EscapeDataString(kvp.Key), Uri.EscapeDataString(kvp.Value))) .OrderBy(s => s) ); var fullSigData = string.Format("{0}&{1}&{2}", "POST", Uri.EscapeDataString(url), Uri.EscapeDataString(sigString.ToString() ) ); return(Convert.ToBase64String( sigHasher.ComputeHash( new ASCIIEncoding().GetBytes(fullSigData.ToString()) ) )); }
private string CreateOauthSignature(string resourceUrl, Method method, string oauthNonce, string oauthTimestamp, SortedDictionary requestParameters) { //firstly we need to add the standard oauth parameters to the sorted list requestParameters.Add("oauth_consumer_key", ConsumerKey); requestParameters.Add("oauth_nonce", oauthNonce); requestParameters.Add("oauth_signature_method", OauthSignatureMethod); requestParameters.Add("oauth_timestamp", oauthTimestamp); requestParameters.Add("oauth_token", AccessToken); requestParameters.Add("oauth_version", OauthVersion); var sigBaseString = requestParameters.ToWebString(); var signatureBaseString = string.Concat(method.ToString(), "&", Uri.EscapeDataString(resourceUrl), "&", Uri.EscapeDataString(sigBaseString.ToString())); //Using this base string, we then encrypt the data using a composite of the //secret keys and the HMAC-SHA1 algorithm. var compositeKey = string.Concat(Uri.EscapeDataString(ConsumerKeySecret), "&", Uri.EscapeDataString(AccessTokenSecret)); string oauthSignature; using (var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey))) { oauthSignature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString))); } return(oauthSignature); }
private void heshGen() { TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0); double curT_T0 = timeSpan.TotalSeconds; Random rd = new Random(); int x = 30; long t = (long)curT_T0 / x; String k = textBox1.Text; //String a = "1"; var enc = Encoding.ASCII; HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(k)); hmac.Initialize(); byte[] buffer = enc.GetBytes(t.ToString()); String key20 = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower(); byte[] barr = Encoding.ASCII.GetBytes(key20); String key4 = barr[2].ToString() + barr[4].ToString() + barr[1].ToString() + barr[0].ToString(); textBox2.Text = key4; }
// 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 = Int(m_block); m_hmacsha1.TransformBlock(m_salt, 0, m_salt.Length, m_salt, 0); m_hmacsha1.TransformFinalBlock(INT_block, 0, INT_block.Length); byte[] temp = m_hmacsha1.Hash; m_hmacsha1.Initialize(); byte[] ret = temp; for (int i = 2; i <= m_iterations; i++) { temp = m_hmacsha1.ComputeHash(temp); for (int j = 0; j < BlockSize; j++) { ret[j] ^= temp[j]; } } // increment the block count. m_block++; return(ret); }
private static byte[] hmac_sha(byte[] keyBytes, byte[] text, int crypto) { if (crypto == 1) { HMACSHA1 hmac = new HMACSHA1(keyBytes); byte[] bc = hmac.ComputeHash(text); return(bc); } else if (crypto == 256) { HMACSHA256 hmac = new HMACSHA256(keyBytes); byte[] bc = hmac.ComputeHash(text); return(bc); } else if (crypto == 512) { HMACSHA512 hmac = new HMACSHA512(keyBytes); byte[] bc = hmac.ComputeHash(text); return(bc); } else { return(null); } }
private static string GetHotp(string base32EncodedSecret, long counter) { byte[] message = BitConverter.GetBytes(counter).Reverse().ToArray(); // Assuming Intel machine (little endian) byte[] secret = base32EncodedSecret.ToByteArray(); string s = secret.ToBase32String(); bool b = base32EncodedSecret.Equals(s); HMACSHA1 hmac = new HMACSHA1(secret, true); byte[] hash = hmac.ComputeHash(message); int offset = hash[hash.Length - 1] & 0xf; int truncatedHash = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); int hotp = truncatedHash % 1000000; // 6 digits code and hence 10 power 6, that is a million return(hotp.ToString().PadLeft(6, '0')); }
private static string GenerateSignatureWithAccessToken(SortedDictionary <string, string> parameters, string requestMethod, string requestURL) { AddDefaultOauthParams(parameters, consumerKey); parameters.Add("oauth_token", accessToken); StringBuilder paramString = new StringBuilder(); foreach (KeyValuePair <string, string> param in parameters) { paramString.Append(Helper.UrlEncode(param.Key) + "=" + Helper.UrlEncode(param.Value) + "&"); } paramString.Length -= 1; // Remove "&" at the last of string string requestHeader = Helper.UrlEncode(requestMethod) + "&" + Helper.UrlEncode(requestURL); string signatureData = requestHeader + "&" + Helper.UrlEncode(paramString.ToString()); string signatureKey = Helper.UrlEncode(consumerSecret) + "&" + Helper.UrlEncode(accessTokenSecret); HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(signatureKey)); byte[] signatureBytes = hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(signatureData)); return(Convert.ToBase64String(signatureBytes)); }
private static string GeneratePayload(string serializedUserData) { byte[] userDataAsBytes = Encoding.UTF8.GetBytes(serializedUserData); // Base64 Encode the message string Message = Convert.ToBase64String(userDataAsBytes); // Get the proper timestamp TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0); string Timestamp = Convert.ToInt32(ts.TotalSeconds).ToString(); // Convert the message + timestamp to bytes byte[] messageAndTimestampBytes = Encoding.ASCII.GetBytes(Message + " " + Timestamp); // Convert Disqus API key to HMAC-SHA1 signature byte[] apiBytes = Encoding.ASCII.GetBytes(DisqusSecretAPIKey); HMACSHA1 hmac = new HMACSHA1(apiBytes); byte[] hashedMessage = hmac.ComputeHash(messageAndTimestampBytes); // Put it all together into the final payload return(Message + " " + ByteToString(hashedMessage) + " " + Timestamp); }
/// <summary> /// 署名を生成する /// </summary> /// <param name="paramsDict">署名生成用パラメータ</param> /// <param name="apiSecret">APIシークレット</param> /// <param name="tokenSecret">トークンシークレット</param> /// <param name="requestMethod">リクエストメソッド</param> /// <param name="requestUrl">リクエストURL</param> private string _GenerateSignature(Dictionary <string, string> paramsDict, string apiSecret, string tokenSecret, string requestMethod, string requestUrl) { List <KeyValuePair <string, string> > pairs = new List <KeyValuePair <string, string> >(paramsDict); pairs.Sort((x, y) => { return(string.Compare(x.Key, y.Key)); }); string requestParams = _HttpBuildQuery(pairs); requestParams = _URLEncode(requestParams); string encodedRequestMethod = _URLEncode(requestMethod); string encodedRequestUrl = _URLEncode(requestUrl); string signatureData = encodedRequestMethod + "&" + encodedRequestUrl + "&" + requestParams; string signitureKey = _URLEncode(apiSecret) + "&" + _URLEncode(tokenSecret); var hashMethod = new HMACSHA1(); hashMethod.Key = System.Text.Encoding.ASCII.GetBytes(signitureKey); var hash = hashMethod.ComputeHash(System.Text.Encoding.ASCII.GetBytes(signatureData)); string signature = Convert.ToBase64String(hash); signature = _URLEncode(signature); return(signature); }
private static string GetCode(string secretKey, long timeIndex) { var secretKeyBytes = Base32Encode(secretKey); //for (int i = secretKey.Length; i < secretKeyBytes.Length; i++) {secretKeyBytes[i] = 0;} var hmac = new HMACSHA1(secretKeyBytes); var challenge = BitConverter.GetBytes(timeIndex); if (BitConverter.IsLittleEndian) { Array.Reverse(challenge); } var hash = hmac.ComputeHash(challenge); var offset = hash[19] & 0xf; var truncatedHash = hash[offset] & 0x7f; for (var i = 1; i < 4; i++) { truncatedHash <<= 8; truncatedHash |= hash[offset + i] & 0xff; } truncatedHash %= 1000000; return(truncatedHash.ToString("D6")); }
public string GenerateTimeoutCode(string password) { byte[] key = Base32.FromBase32String(password); string keyStr = ToHex(key); HMACSHA1 Mac = new HMACSHA1(); Mac.Key = key; byte[] challenge = Reverse(BitConverter.GetBytes(CurrentInterval)); byte[] hash = Mac.ComputeHash(challenge); string hashStr = ToHex(hash); // Dynamically truncate the hash // OffsetBits are the low order bits of the last byte of the hash int offset = hash[hash.Length - 1] & 0xF; // Grab a positive integer value starting at the given offset. int result = HashToInt(hash, offset); int truncatedHash = result & 0x7FFFFFFF; int pinValue = truncatedHash % PinModulo; return(pinValue.ToString(new String('0', 6))); }
private string GetSignatureHMACSHA1() { // Construct Base String string baseString = GetBaseString(); Trace.WriteLine("Base string: " + baseString); // Create the key based on secrets string key = string.Format("{0}&{1}", HttpUtil.Esc(ConsumerSecret), HttpUtil.Esc(TokenSecret)); // Create our hash generator with key var hasher = new HMACSHA1(Encoding.ASCII.GetBytes(key)); // Generate hashes and create signature string byte[] hashes = hasher.ComputeHash(Encoding.ASCII.GetBytes(baseString)); string signature = Convert.ToBase64String(hashes); Trace.WriteLine("Signature string: " + signature); return(signature); }
public static string GenerateSteamGuardCodeForTime(string SharedSecret, long time) { string sharedSecretUnescaped = Regex.Unescape(SharedSecret); byte[] sharedSecretArray = Convert.FromBase64String(sharedSecretUnescaped); byte[] timeArray = new byte[8]; time /= 30L; for (int i = 8; i > 0; i--) { timeArray[i - 1] = (byte)time; time >>= 8; } HMACSHA1 hmacGenerator = new HMACSHA1(); hmacGenerator.Key = sharedSecretArray; byte[] hashedData = hmacGenerator.ComputeHash(timeArray); byte[] codeArray = new byte[5]; try { byte b = (byte)(hashedData[19] & 0xF); int codePoint = (hashedData[b] & 0x7F) << 24 | (hashedData[b + 1] & 0xFF) << 16 | (hashedData[b + 2] & 0xFF) << 8 | (hashedData[b + 3] & 0xFF); for (int i = 0; i < 5; ++i) { codeArray[i] = steamGuardCodeTranslations[codePoint % steamGuardCodeTranslations.Length]; codePoint /= steamGuardCodeTranslations.Length; } } catch (Exception) { return(null); //Change later, catch-alls are bad! } return(Encoding.UTF8.GetString(codeArray)); }
/// <summary> /// Verifies that the signature header matches that of the actual body. /// </summary> protected virtual async Task <bool> VerifySignature(HttpRequestMessage request, string id) { string secretKey = await GetReceiverConfig(request, Name, id, SecretMinLength, SecretMaxLength); // Get the expected hash from the signature header string signatureHeaderValue = GetRequestHeader(request, SignatureHeaderName); byte[] expectedHash; try { expectedHash = EncodingUtilities.FromBase64(signatureHeaderValue); } catch (Exception ex) { string msg = string.Format(CultureInfo.CurrentCulture, TrelloResources.Receiver_BadHeaderEncoding, SignatureHeaderName); request.GetConfiguration().DependencyResolver.GetLogger().Error(msg, ex); HttpResponseMessage invalidEncoding = request.CreateErrorResponse(HttpStatusCode.BadRequest, msg); throw new HttpResponseException(invalidEncoding); } // Get the actual hash of the request body concatenated with the request URI byte[] actualHash; byte[] secret = Encoding.UTF8.GetBytes(secretKey); using (var hasher = new HMACSHA1(secret)) { byte[] data = await request.Content.ReadAsByteArrayAsync(); byte[] requestUri = Encoding.UTF8.GetBytes(request.RequestUri.AbsoluteUri); byte[] combo = new byte[data.Length + requestUri.Length]; Buffer.BlockCopy(data, 0, combo, 0, data.Length); Buffer.BlockCopy(requestUri, 0, combo, data.Length, requestUri.Length); actualHash = hasher.ComputeHash(combo); } // Now verify that the provided hash matches the expected hash. return(WebHookReceiver.SecretEqual(expectedHash, actualHash)); }
private string CreateOauthSignature(string resourceUrl, string method, string oauthNonce, string oauthTimestamp, string msg) { var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}"; if (msg != "") { baseFormat += "&status=" + Uri.EscapeDataString(msg); } var baseString = string.Format(baseFormat, consumerKey, oauthNonce, oauthSignatureMethod, oauthTimestamp, accessToken, oauthVersion ); baseString = string.Concat(method + "&", Uri.EscapeDataString(resourceUrl), "&", Uri.EscapeDataString(baseString)); var compositeKey = string.Concat(Uri.EscapeDataString(consumerKeySecret), "&", Uri.EscapeDataString(accessTokenSecret)); string oauth_signature; using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))) { oauth_signature = Convert.ToBase64String( hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString))); } string autht = Uri.EscapeDataString(oauth_signature); return(autht); }
private string DecodeCookie() { var cookieBytes = SoapHexBinary.Parse(CookieValue).Value; var validationKeyBytes = SoapHexBinary.Parse(ValidationKey).Value; var decryptionKeyBytes = SoapHexBinary.Parse(DecryptionKey).Value; int signatureLength = 0; using (var validationAlgorithm = new HMACSHA1(validationKeyBytes)) { signatureLength = validationAlgorithm.HashSize >> 3; if (cookieBytes.Length - 1 < signatureLength) { return("The cookie cannot be validated. Validation signature hash size does not align with cookie length."); } var signature = validationAlgorithm.ComputeHash(cookieBytes, 0, cookieBytes.Length - signatureLength); for (int signatureIndex = 0; signatureIndex < signature.Length; signatureIndex++) { // If we break early, we'll be more vulnerable to timing attacks. if (signature[signatureIndex] != cookieBytes[cookieBytes.Length - signatureLength + signatureIndex]) { return("Cookie signature validation failed."); } } } int initializationVectorLength; var decryptedBytes = DecryptBytes(cookieBytes, decryptionKeyBytes, signatureLength, out initializationVectorLength); if (decryptedBytes.Length < 51 + initializationVectorLength) { return("Decrypted value is insufficient in length."); } return(DecodeCookieBytes(decryptedBytes, initializationVectorLength)); }
public static byte[] hmacSHA1(object data, object key) { byte[] rawKey = null; byte[] rawData = null; if (data is byte[] || data is string) { if (data is string) { rawData = System.Text.Encoding.UTF8.GetBytes(data as string); } else { rawData = data as byte[]; } } if (key is byte[] || key is string) { if (key is string) { rawKey = System.Text.Encoding.UTF8.GetBytes(key as string); } else { rawKey = key as byte[]; } } if (data != null && key != null) { HMACSHA1 hmac = new HMACSHA1(rawKey); return(hmac.ComputeHash(rawData)); } return(null); }
/// <summary> /// 给TOP请求签名。 /// </summary> /// <param name="parameters">所有字符型的TOP请求参数</param> /// <param name="secret">签名密钥</param> /// <returns>签名</returns> public static string SignTopRequest(string urlPath, IDictionary <string, string> parameters, string secret) { // 第一步:把字典按Key的字母顺序排序 IDictionary <string, string> sortedParams = new SortedDictionary <string, string>(parameters); IEnumerator <KeyValuePair <string, string> > dem = sortedParams.GetEnumerator(); // 第二步:把所有参数名和参数值串在一起 StringBuilder query = new StringBuilder(urlPath); while (dem.MoveNext()) { string key = dem.Current.Key; string value = dem.Current.Value; if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) { query.Append(key).Append(value); } } // 第三步:使用MD5加密 using (HMACSHA1 sha = new HMACSHA1(Encoding.UTF8.GetBytes(secret))) { byte[] bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(query.ToString())); // 第四步:把二进制转化为大写的十六进制 StringBuilder result = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { string hex = bytes[i].ToString("X"); if (hex.Length == 1) { result.Append("0"); } result.Append(hex); } return(result.ToString()); } }
public string Sign(SignatureContext context) { var hmac = new HMACSHA1(); var secret = context.Secret.UrlEncode(); if (secret == null) { secret = Guid.NewGuid().ToString(); } hmac.Key = context.Encoding.GetBytes(secret); var source = new StringBuilder(); if (context.SortedQuery != null) { // append path foreach (var key in context.SortedQuery.AllKeys) { source.Append(key); source.Append(context.SortedQuery[key]); } } var buffer = context.Encoding.GetBytes(source.ToString()); var signBytes = hmac.ComputeHash(buffer); var sb = new StringBuilder(); foreach (byte b in signBytes) { sb.Append(b.ToString("x2")); } return(sb.ToString()); }
public static byte[] WhatsappEncrypt(byte[] key, byte[] data, bool appendHash) { if (encryptionOutgoing == null) encryptionOutgoing = new RC4(key, 256); HMACSHA1 h = new HMACSHA1(key); byte[] buff = new byte[data.Length]; Buffer.BlockCopy(data, 0, buff, 0, data.Length); encryptionOutgoing.Cipher(buff); byte[] hashByte = h.ComputeHash(buff); byte[] response = new byte[4 + buff.Length]; if (appendHash) { Buffer.BlockCopy(buff, 0, response, 0, buff.Length); Buffer.BlockCopy(hashByte, 0, response, buff.Length, 4); } else { Buffer.BlockCopy(hashByte, 0, response, 0, 4); Buffer.BlockCopy(buff, 0, response, 4, buff.Length); } return response; }
public static string GenerateUrlToken(string controllerName, string actionName, RouteValueDictionary argumentParams, string password) { //// The URL hash is dynamic by assign a dynamic key in each session. So //// eventhough your URL is stolen, it will not work in other session if (HttpContext.Current.Session["url_dynamickey"] == null) { HttpContext.Current.Session["url_dynamickey"] = RandomString(); } // The salt include the dynamic session key and valid for an hour. var salt = HttpContext.Current.Session["url_dynamickey"] + DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour; // generating the partial url var stringToToken = controllerName + "/" + actionName + "/"; stringToToken = argumentParams.Where(item => item.Key != "controller" && item.Key != "action" && item.Key != "urltoken").Aggregate(stringToToken, (current, item) => current + (item.Value)); // Converting the salt in to a byte array var saltValueBytes = System.Text.Encoding.ASCII.GetBytes(salt); // Encrypt the salt bytes with the password var key = new Rfc2898DeriveBytes(password, saltValueBytes); // get the key bytes from the above process var secretKey = key.GetBytes(16); // generate the hash var tokenHash = new HMACSHA1(secretKey); tokenHash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(stringToToken)); // convert the hash to a base64string var token = Convert.ToBase64String(tokenHash.Hash).Replace("/", "_"); return(token); }
public void Initialize(byte[] sessionKey) { if (IsInitialized) { throw new InvalidOperationException("PacketCrypt already initialized!"); } SARC4Encrypt = new SARC4(); SARC4Decrypt = new SARC4(); DecryptSHA1 = new HMACSHA1(ServerDecryptionKey); EncryptSHA1 = new HMACSHA1(ServerEncryptionKey); SARC4Encrypt.PrepareKey(EncryptSHA1.ComputeHash(sessionKey)); SARC4Decrypt.PrepareKey(DecryptSHA1.ComputeHash(sessionKey)); byte[] PacketEncryptionDummy = new byte[0x400]; byte[] PacketDecryptionDummy = new byte[0x400]; SARC4Encrypt.ProcessBuffer(PacketEncryptionDummy, PacketEncryptionDummy.Length); SARC4Decrypt.ProcessBuffer(PacketDecryptionDummy, PacketDecryptionDummy.Length); IsInitialized = true; }
/// <summary> /// Performs an encryption using AES/CBC/PKCS7 with an input byte array and key, with a IV (comprised of random bytes and the HMAC-SHA1 of the random bytes and plaintext) prepended using AES/ECB/None /// </summary> public static byte[] SymmetricEncryptWithHMACIV(byte[] input, byte[] key, byte[] hmacSecret) { if (input == null) { throw new ArgumentNullException(nameof(input)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (hmacSecret == null) { throw new ArgumentNullException(nameof(hmacSecret)); } // IV is HMAC-SHA1(Random(3) + Plaintext) + Random(3). (Same random values for both) var iv = new byte[16]; var random = GenerateRandomBlock(3); Array.Copy(random, 0, iv, iv.Length - random.Length, random.Length); using (var hmac = new HMACSHA1(hmacSecret)) using (var ms = new MemoryStream()) { ms.Write(random, 0, random.Length); ms.Write(input, 0, input.Length); ms.Seek(0, SeekOrigin.Begin); var hash = hmac.ComputeHash(ms); Array.Copy(hash, iv, iv.Length - random.Length); } return(SymmetricEncryptWithIV(input, key, iv)); }
/// <summary> /// Verifies and performs a symmetricdecrypt on the input using the given password as a key /// </summary> public static byte[]? VerifyAndDecryptPassword(byte[] input, string password) { if (input == null) { throw new ArgumentNullException(nameof(input)); } if (password == null) { throw new ArgumentNullException(nameof(password)); } byte[] key, hash; using (var sha256 = SHA256.Create()) { byte[] password_bytes = Encoding.UTF8.GetBytes(password); key = sha256.ComputeHash(password_bytes); } using (HMACSHA1 hmac = new HMACSHA1(key)) { hash = hmac.ComputeHash(input, 0, 32); } for (int i = 32; i < input.Length; i++) { if (input[i] != hash[i % 32]) { return(null); } } byte[] encrypted = new byte[32]; Array.Copy(input, encrypted, encrypted.Length); return(CryptoHelper.SymmetricDecrypt(encrypted, key)); }
// https://dev.twitter.com/docs/auth/creating-signature private string GenerateSignature(SortedDictionary <string, string> paramDictionary, string reqestUrl, string oAuthConsumerSecret, string oAuthTokenSecret = null) { //パラメータディクショナリ内の要素を結合しシグネチャのベースとなる文字列を生成 string baseStrParams = String.Empty; foreach (var kvp in paramDictionary.OrderBy(kvp => kvp.Key)) { baseStrParams += (baseStrParams.Length > 0 ? "&" : String.Empty) + kvp.Key + "=" + kvp.Value; } string baseStr = "POST&" + reqestUrl.EscapeDataStringRFC3986() + "&" + baseStrParams.EscapeDataStringRFC3986(); //デジタル署名用キーを生成するためのキー文字列を生成 string stringKey = oAuthConsumerSecret.EscapeDataStringRFC3986() + "&"; if (!String.IsNullOrEmpty(oAuthTokenSecret)) { stringKey += oAuthTokenSecret.EscapeDataStringRFC3986(); } byte[] keyBytes = Encoding.UTF8.GetBytes(stringKey); HMACSHA1 hmacsha1 = new HMACSHA1(keyBytes); byte[] inDataBytes = Encoding.UTF8.GetBytes(baseStr); MemoryStream ms = new MemoryStream(inDataBytes); byte[] outDataBytes = hmacsha1.ComputeHash(inDataBytes); //Base64エンコードにてシグネチャを取得 string signature = Convert.ToBase64String(outDataBytes, 0, outDataBytes.Length); return(signature); }
public string GetPassword(int digits = 6) { TimeStamp ts = new TimeStamp(); long seconds = (long)ts.Seconds; long count = seconds / duration; byte[] buffer = BitConverter.GetBytes(count); if (BitConverter.IsLittleEndian) { Array.Reverse(buffer); } HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(key), true); byte[] hash = hmac.ComputeHash(buffer); int offset = hash[hash.Length - 1] & 0xf; int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); int password = binary % (int)Math.Pow(10, digits); // 6 digits return(password.ToString(new string('0', digits))); }
public static string generateUrlToken(string controllerName, string actionName, RouteValueDictionary argumentParams, string password) { //The URL hash is dynamic by assign a dynamic key in each session. So //eventhough your URL is stolen, it will not work in other session if (HttpContext.Current.Session["url_dynamickey"] == null) { HttpContext.Current.Session["url_dynamickey"] = RandomString(); } string token = ""; //The salt include the dynamic session key and valid for an hour. string salt = HttpContext.Current.Session["url_dynamickey"].ToString() + DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour;; //generating the partial url string stringToToken = controllerName + "/" + actionName + "/"; foreach (KeyValuePair <string, object> item in argumentParams) { if (item.Key != "controller" && item.Key != "action" && item.Key != "urltoken") { stringToToken += "/" + item.Value; } } //Converting the salt in to a byte array byte[] saltValueBytes = System.Text.Encoding.ASCII.GetBytes(salt); //Encrypt the salt bytes with the password Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, saltValueBytes); //get the key bytes from the above process byte[] secretKey = key.GetBytes(16); //generate the hash HMACSHA1 tokenHash = new HMACSHA1(secretKey); tokenHash.ComputeHash(System.Text.Encoding.ASCII.GetBytes(stringToToken)); //convert the hash to a base64string token = Convert.ToBase64String(tokenHash.Hash).Replace("/", "_"); return(token); }
string GetSignature(Uri uri) { byte[] encodedPathQuery = Encoding.ASCII.GetBytes(uri.LocalPath + uri.Query); var hashAlgorithm = new HMACSHA1(_privateKeyBytes); byte[] hashed = hashAlgorithm.ComputeHash(encodedPathQuery); return Convert.ToBase64String(hashed).Replace("+", "-").Replace("/", "_"); }
private static string Base64EncodeHash(Stream ms) { ms.Seek(0, SeekOrigin.Begin); byte[] result; HMACSHA1 shaM = new HMACSHA1(); shaM.Key = new byte[1]; shaM.Initialize(); result = shaM.ComputeHash(ms); string hash = System.Convert.ToBase64String(result); return hash; }
//------------------------------------------------------------------------------- #endregion JoinParameters //------------------------------------------------------------------------------- #region GenerateSignature //------------------------------------------------------------------------------- // private string GenerateSignature(string tokenSecret, string httpMethod, string url, SortedDictionary<string, string> parameters) { string signatureBase = GenerateSignatureBase(httpMethod, url, parameters); HMACSHA1 hmacsha1 = new HMACSHA1(); hmacsha1.Key = Encoding.ASCII.GetBytes(UrlEncode(ConsumerSecret) + '&' + UrlEncode(tokenSecret)); byte[] data = System.Text.Encoding.ASCII.GetBytes(signatureBase); byte[] hash = hmacsha1.ComputeHash(data); return Convert.ToBase64String(hash); }
public byte[] ComputeHash(byte[] source, byte[] key) { HMACSHA1 hma = new HMACSHA1(key); return hma.ComputeHash(source); }
private static string GenerateSignatureBySignatureBase(string httpMethod, string consumerSecret, string tokenSecret, string normalizedUrl, StringBuilder sbSignatureBase) { string normalizedRequestParameters = sbSignatureBase.ToString().TrimEnd('&'); StringBuilder signatureBase = new StringBuilder(); signatureBase.AppendFormat("{0}&", httpMethod.ToString()); signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl)); signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters)); HMACSHA1 hmacsha1 = new HMACSHA1(); hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), UrlEncode(tokenSecret))); byte[] hashBytes = hmacsha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(signatureBase.ToString())); return Convert.ToBase64String(hashBytes); }
/// <summary> /// Creates and returns an HMAC-SHA1 signature of a String. /// </summary> /// <param name="token">The String that will be used to create the signature.</param> /// <returns></returns> protected static string SignToken(string token) { byte[] hash; using (HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(api_key))) { hash = hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(token)); } return Convert.ToBase64String(hash); }
static string get_hm_hash(string secret_key, string input) { HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(secret_key)); MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(input)); byte[] hashData = hmacsha1.ComputeHash(stream); // Format as hexadecimal string. StringBuilder sb = new StringBuilder(); foreach (byte data in hashData) { sb.Append(data.ToString("x2")); } return sb.ToString(); }
/// <summary> /// Creates an authorization header. /// </summary> /// <param name="credentials">Lumos credentials object.</param> /// <param name="postData">The POST body.</param> /// <returns>A string suitable for the HTTP Authorization header.</returns> public static string GenerateAuthorizationHeader (LumosCredentials credentials, byte[] postData) { if (postData == null) { postData = new byte[] {}; } var secret = Encoding.ASCII.GetBytes(credentials.apiKey); var hmac = new HMACSHA1(secret); var hash = hmac.ComputeHash(postData); var auth = Convert.ToBase64String(hash); var header = "Lumos " + credentials.gameID + ":" + auth; return header; }
static string MakeOAuthSignature(string compositeSigningKey, string signatureBase) { using (HMACSHA1 crypto = new HMACSHA1()) { byte[] bkey = Encoding.ASCII.GetBytes(compositeSigningKey); // Keys longer than 60 characters aparently do not work with OpenNetCF... if (bkey.Length > 60) { bkey = (new System.Security.Cryptography.SHA1CryptoServiceProvider()).ComputeHash(bkey); } crypto.Key = bkey; string hash = Convert.ToBase64String(crypto.ComputeHash(Encoding.ASCII.GetBytes(signatureBase))); crypto.Clear(); return hash; } }
/// <summary> /// Runs an HMACSHA1 hash on specified data using specified key /// </summary> /// <param name="xKey"></param> /// <param name="xData"></param> /// <returns></returns> public static byte[] ComputeHash(byte[] xKey, byte[] xData) { HMACSHA1 xhs = new HMACSHA1(xKey); return xhs.ComputeHash(xData); }
private string HMAC_SHA1(string key, string message) { System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); byte[] keyByte = encoding.GetBytes(key); HMACMD5 hmacmd5 = new HMACMD5(keyByte); HMACSHA1 hmacsha1 = new HMACSHA1(keyByte); byte[] messageBytes = encoding.GetBytes(message); byte[] hashmessage = hmacsha1.ComputeHash(messageBytes); return ByteToString(hashmessage); }
public string getHmacSHA1(String data) { System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); byte[] keyByte = encoding.GetBytes(this.secure_pass); HMACSHA1 hmacsha1 = new HMACSHA1(keyByte); byte[] messageBytes = encoding.GetBytes(data); byte[] hashmessage = hmacsha1.ComputeHash(messageBytes); string encrypted = this.ByteToString(hashmessage); return encrypted; }
public void LoadTwitterPosts(string page_name) { string str = "%20from:" + page_name + "&result_type=mixed"; string url = "https://api.twitter.com/1.1/search/tweets.json?q=" + str; string oauthconsumerkey = System.Configuration.ConfigurationManager.AppSettings["consumerKey"]; string oauthtoken = System.Configuration.ConfigurationManager.AppSettings["oauth_token"]; string oauthconsumersecret = System.Configuration.ConfigurationManager.AppSettings["consumerSecret"]; string oauthtokensecret = System.Configuration.ConfigurationManager.AppSettings["oauth_token_secret"]; string oauthsignaturemethod = "HMAC-SHA1"; string oauthversion = "1.0"; string oauthnonce = Convert.ToBase64String( new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())); TimeSpan timeSpan = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); string oauthtimestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString(); SortedDictionary<string, string> basestringParameters = new SortedDictionary<string, string>(); basestringParameters.Add("q", str); basestringParameters.Add("oauth_version", oauthversion); basestringParameters.Add("oauth_consumer_key", oauthconsumerkey); basestringParameters.Add("oauth_nonce", oauthnonce); basestringParameters.Add("oauth_signature_method", oauthsignaturemethod); basestringParameters.Add("oauth_timestamp", oauthtimestamp); basestringParameters.Add("oauth_token", oauthtoken); //Build the signature string string baseString = String.Empty; baseString += "GET" + "&"; baseString += Uri.EscapeDataString(url.Split('?')[0]) + "&"; foreach (KeyValuePair<string, string> entry in basestringParameters) { baseString += Uri.EscapeDataString(entry.Key + "=" + entry.Value + "&"); } //Remove the trailing ambersand char last 3 chars - %26 baseString = baseString.Substring(0, baseString.Length - 3); //Build the signing key string signingKey = Uri.EscapeDataString(oauthconsumersecret) + "&" + Uri.EscapeDataString(oauthtokensecret); //Sign the request HMACSHA1 hasher = new HMACSHA1(new ASCIIEncoding().GetBytes(signingKey)); string oauthsignature = Convert.ToBase64String( hasher.ComputeHash(new ASCIIEncoding().GetBytes(baseString))); //Tell Twitter we don't do the 100 continue thing ServicePointManager.Expect100Continue = false; //authorization header HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@url); string authorizationHeaderParams = String.Empty; authorizationHeaderParams += "OAuth "; authorizationHeaderParams += "oauth_nonce=" + "\"" + Uri.EscapeDataString(oauthnonce) + "\","; authorizationHeaderParams += "oauth_signature_method=" + "\"" + Uri.EscapeDataString(oauthsignaturemethod) + "\","; authorizationHeaderParams += "oauth_timestamp=" + "\"" + Uri.EscapeDataString(oauthtimestamp) + "\","; authorizationHeaderParams += "oauth_consumer_key=" + "\"" + Uri.EscapeDataString(oauthconsumerkey) + "\","; authorizationHeaderParams += "oauth_token=" + "\"" + Uri.EscapeDataString(oauthtoken) + "\","; authorizationHeaderParams += "oauth_signature=" + "\"" + Uri.EscapeDataString(oauthsignature) + "\","; authorizationHeaderParams += "oauth_version=" + "\"" + Uri.EscapeDataString(oauthversion) + "\""; webRequest.Headers.Add("Authorization", authorizationHeaderParams); webRequest.Method = "GET"; webRequest.ContentType = "application/x-www-form-urlencoded"; //Allow us a reasonable timeout in case Twitter's busy webRequest.Timeout = 3 * 60 * 1000; try { //Proxy settings webRequest.Proxy = new WebProxy(); HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse; Stream dataStream = webResponse.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); CreatePostslist(responseFromServer, page_name); } catch (Exception ex) { Panel2_Clear(); lblPagePostsMsg2.Text = " Not a valid Page URL "; lblPagePostsMsg2.Visible = true; } }
public byte[] ComputeHash(string source, string key, Encoding encoding) { HMACSHA1 hma = new HMACSHA1(encoding.GetBytes(key)); return hma.ComputeHash(encoding.GetBytes(source)); }
/** * */ protected override string CreateSignature(string token_secret, string method, Uri uri, IDictionary<string, string> palams) { const string proxy_domain = string.Format( "{0}://{1}", uri.Scheme, __proxy_host ); const string real_proxy = string.Format( "{0}://{1}", uri.Scheme, __default_api_host ); // params をソート済みディクショナリに詰め替えます。 SortedDictionary sorted_params = new SortedDictionary<string, string>( palams ); // URL エンコード済みのクエリ形式文字列に変換します。 string param_string = CreateQueryString( sorted_params ); // アクセス先 URL の整形をおこないます。 string url = string.Format( "{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath ); // 本来のアクセス先 URL に再設定します。 if ( !string.IsNullOrEmpty( __proxy_host ) && url.StartsWith( proxy_domain ) ) { url = url.Replace( proxy_domain, real_domain ); } // 署名のベース文字列を生成します('&' 区切り)。クエリ形式文字列は再エンコードします。 string sigunature_base = string.Format( "{0}&{1}&{2}", method, UrlEncode( url ), UrlEncode( param_string ) ); // 署名鍵の文字列をコンシューマー秘密鍵とアクセストークン秘密鍵から生成します('&' 区切りです。 // アクセストークン秘密鍵が無くても '&' を残すようにしてください)。 StringBuilder key_builder = new StringBuilder( UrlEncode( this.consumer_secret_ ) ).Append( "&" ); if ( !string.Format( this.token_secret_ ) ) key_builder.Append( UrlEncode( this.token_secret_ ) ); // // 鍵と署名を生成します。 // using ( HMACSHA1 hmac = new HMACSHA1( Encoding.ASCII.GetBytes( key_builder.ToString() ) ) ) { byte[] hash = hmac.ComputeHash( Encoding.ASCII.GetBytes( sigunature_base ) ); return Convert.ToBase64String( hash ); } }
private static string CreateTimeHash(long time, string tag, string secret) { byte[] b64secret = Convert.FromBase64String(secret); int bufferSize = 8; if (string.IsNullOrEmpty(tag) == false) { bufferSize += Math.Min(32, tag.Length); } byte[] buffer = new byte[bufferSize]; byte[] timeArray = BitConverter.GetBytes(time); if (BitConverter.IsLittleEndian) { Array.Reverse(timeArray); } Array.Copy(timeArray, buffer, 8); if (string.IsNullOrEmpty(tag) == false) { Array.Copy(Encoding.UTF8.GetBytes(tag), 0, buffer, 8, bufferSize - 8); } HMACSHA1 hmac = new HMACSHA1(b64secret, true); byte[] hash = hmac.ComputeHash(buffer); return Convert.ToBase64String(hash, Base64FormattingOptions.None); }
public void UploadToS3Worker(FileInfo Info, string KeyId, string AccessKey, string BucketName, string FolderName ) { Log(" Uploading " + Info.Name); // force upload files even if the timestamps haven't changed. string TimeStamp = string.Format("{0:r}", DateTime.UtcNow); string ContentType = ""; if (MimeTypeMapping.ContainsKey(Info.Extension)) { ContentType = MimeTypeMapping[Info.Extension]; } else { // default ContentType = "application/octet-stream"; } // URL to put things. string URL = "http://" + BucketName + ".s3.amazonaws.com/" + FolderName + "/" + Info.Name; HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(URL); // Upload. Request.Method = "PUT"; Request.Headers["x-amz-date"] = TimeStamp; Request.Headers["x-amz-acl"] = "public-read"; // we probably want to make public read by default. // set correct content encoding for compressed javascript. if ( Info.Extension == ".gz") { Request.Headers["Content-Encoding"] = "gzip"; } Request.ContentType = ContentType; Request.ContentLength = Info.Length; //http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html // Find Base64Encoded data. UTF8Encoding EncodingMethod = new UTF8Encoding(); HMACSHA1 Signature = new HMACSHA1 { Key = EncodingMethod.GetBytes(AccessKey) }; // don't change this string. string RequestString = "PUT\n\n" + ContentType + "\n\nx-amz-acl:public-read\nx-amz-date:" + TimeStamp + "\n/"+ BucketName + "/" + FolderName + "/" + Info.Name; Byte[] ComputedHash = Signature.ComputeHash(EncodingMethod.GetBytes(RequestString)); var Base64Encoded = Convert.ToBase64String(ComputedHash); // final amz auth header. Request.Headers["Authorization"] = "AWS " + KeyId + ":" + Base64Encoded; try { // may fail for really big stuff. YMMV. May need Multi part approach, we will see. Byte[] FileData = File.ReadAllBytes(Info.FullName); var requestStream = Request.GetRequestStream(); requestStream.Write(FileData, 0, FileData.Length); requestStream.Close(); using (var response = Request.GetResponse() as HttpWebResponse) { var reader = new StreamReader(response.GetResponseStream()); reader.ReadToEnd(); } } catch (Exception ex) { Log("Could not connect to S3, incorrect S3 Keys? " + ex.ToString()); throw ex; } Log(Info.Name + " has been uploaded " ); }
public static string GetSHA1(string text, string key) { UTF8Encoding utf8 = new UTF8Encoding(); Encoding en = utf8; byte[] hashValue; byte[] message = en.GetBytes(text); byte[] k = en.GetBytes(key); HMACSHA1 hmac = new HMACSHA1(k, true); string hex = ""; hashValue = hmac.ComputeHash(message); foreach (byte x in hashValue) { hex += String.Format("{0:x2}", x); } return hex; }
private string EncodePassword(string password) { string encodedPassword = password; switch (PasswordFormat) { case MembershipPasswordFormat.Clear: break; case MembershipPasswordFormat.Encrypted: encodedPassword = Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password))); break; case MembershipPasswordFormat.Hashed: HMACSHA1 hash = new HMACSHA1(); hash.Key = HexToByte(machineKey.ValidationKey); encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); break; default: throw new ProviderException("Unsupported password format."); } return encodedPassword; }
/// <summary> /// Encode string in Hash format /// </summary> /// <param name="password">password</param> /// <returns>Encoded password</returns> public static string EncodePassword(string password) { HMACSHA1 hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); return encodedPassword; }