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)); }
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; }
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"; }
public void HmacSha1_Byte_Constructors() { byte[] key = (byte[])s_testKeys2202[1].Clone(); string digest = "b617318655057264e28bc0b6fb378c8ef146be00"; using (HMACSHA1 h1 = new HMACSHA1(key)) { VerifyHmac_KeyAlreadySet(h1, 1, digest); #if netstandard17 using (HMACSHA1 h2 = new HMACSHA1(key, true)) { VerifyHmac_KeyAlreadySet(h2, 1, digest); Assert.Equal(h1.Key, h2.Key); } using (HMACSHA1 h2 = new HMACSHA1(key, false)) { VerifyHmac_KeyAlreadySet(h1, 1, digest); Assert.Equal(h1.Key, h2.Key); } #endif } }
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 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 bool ValidateCode(SecurityToken securityToken, int code, string modifier = null) { if (securityToken == null) { throw new ArgumentNullException("securityToken"); } // Allow a variance of no greater than 90 seconds in either direction var currentTimeStep = GetCurrentTimeStepNumber(); using (var hashAlgorithm = new HMACSHA1(securityToken.GetDataNoClone())) { for (var i = -2; i <= 2; i++) { var computedTotp = ComputeTotp(hashAlgorithm, (ulong)((long)currentTimeStep + i), modifier); if (computedTotp == code) { return(true); } } } // No match return(false); }
static private bool IsGithubPushAllowed(string payload, string eventName, string signatureWithPrefix) { if (string.IsNullOrWhiteSpace(payload)) { throw new ArgumentNullException(nameof(payload)); } if (string.IsNullOrWhiteSpace(eventName)) { throw new ArgumentNullException(nameof(eventName)); } if (string.IsNullOrWhiteSpace(signatureWithPrefix)) { throw new ArgumentNullException(nameof(signatureWithPrefix)); } if (signatureWithPrefix.StartsWith(Sha1Prefix, StringComparison.OrdinalIgnoreCase)) { var signature = signatureWithPrefix.Substring(Sha1Prefix.Length); var secret = Encoding.ASCII.GetBytes(ServiceSecret); var payloadBytes = Encoding.UTF8.GetBytes(payload); using (var hmSha1 = new HMACSHA1(secret)) { var hash = hmSha1.ComputeHash(payloadBytes); var hashString = ToHexString(hash); if (hashString.Equals(signature)) { return(true); } } } return(false); }
/// <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)); }
/// <summary> /// Checks whether the specified pairwise transit key is valid for the EAPoL key /// </summary> /// <param name="eapolKey">The EAPoL key to check against</param> /// <param name="ptk">The pairwise transit key to check</param> /// <returns>True if the key is valid, false if it is not</returns> public static bool PtkIsValid(IEEE802_1x <EapolKey> eapolKey, byte[] ptk) { var tkip = (eapolKey.Payload.KeyInformation & 7) == 1; bool isValid; var MIC = eapolKey.Payload.MIC; eapolKey.Payload.MIC = new byte[MIC.Length]; try { HMAC hmac; var key = ptk.Take(16).ToArray(); if (tkip) { #if DOTNET5_4 throw new System.Exception("The current version of System.Security.Cryptography.Algorithms is missing HMACMD5."); #else hmac = new HMACMD5(key); #endif } else { hmac = new HMACSHA1(key); } var computedHash = hmac.ComputeHash(eapolKey.ToArray()); isValid = computedHash.Take(16).SequenceEqual(MIC.Take(16)); } finally { eapolKey.Payload.MIC = MIC; } return(isValid); }
/* * 计算 HMAC-SHA1 */ public static String HMACSha1(String data, String key) { String result = ""; //使用CodePagesEncodingProvider去注册扩展编码。 Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //注册GBK编码 Encoding encodingGbk = Encoding.GetEncoding("GBK"); byte[] dataByte = encodingGbk.GetBytes(data); byte[] keyByte = encodingGbk.GetBytes(key); using (HMACSHA1 hmac = new HMACSHA1(keyByte)) { using (MemoryStream stream = new MemoryStream(dataByte)) { byte[] hashValue = hmac.ComputeHash(stream); result = Convert.ToBase64String(hashValue); } } return(result); }
/// <summary> /// OAuth認証ヘッダの署名作成 /// </summary> /// <param name="tokenSecret">アクセストークン秘密鍵</param> /// <param name="method">HTTPメソッド文字列</param> /// <param name="uri">アクセス先Uri</param> /// <param name="parameter">クエリ、もしくはPOSTデータ</param> /// <returns>署名文字列</returns> public static string CreateSignature(string consumerSecret, string tokenSecret, string method, Uri uri, Dictionary <string, string> parameter) { // パラメタをソート済みディクショナリに詰替(OAuthの仕様) SortedDictionary <string, string> sorted = new SortedDictionary <string, string>(parameter); // URLエンコード済みのクエリ形式文字列に変換 string paramString = MyCommon.BuildQueryString(sorted); // アクセス先URLの整形 string url = string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath); // 署名のベース文字列生成(&区切り)。クエリ形式文字列は再エンコードする string signatureBase = string.Format("{0}&{1}&{2}", method, MyCommon.UrlEncode(url), MyCommon.UrlEncode(paramString)); // 署名鍵の文字列をコンシューマー秘密鍵とアクセストークン秘密鍵から生成(&区切り。アクセストークン秘密鍵なくても&残すこと) string key = MyCommon.UrlEncode(consumerSecret) + "&"; if (!string.IsNullOrEmpty(tokenSecret)) { key += MyCommon.UrlEncode(tokenSecret); } // 鍵生成&署名生成 using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(key))) { byte[] hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase)); return(Convert.ToBase64String(hash)); } }
public void GenerateSessionKey(byte[] clientSalt, byte[] serverSalt) { var hmac = new HMACSHA1(SecureRemotePassword.SessionKey); var wow = Encoding.ASCII.GetBytes("WoW\0"); var wowSessionKey = new byte[0x28]; hmac.TransformBlock(wow, 0, wow.Length, wow, 0); hmac.TransformBlock(clientSalt, 0, clientSalt.Length, clientSalt, 0); hmac.TransformFinalBlock(serverSalt, 0, serverSalt.Length); Buffer.BlockCopy(hmac.Hash, 0, wowSessionKey, 0, hmac.Hash.Length); hmac.Initialize(); hmac.TransformBlock(wow, 0, wow.Length, wow, 0); hmac.TransformBlock(serverSalt, 0, serverSalt.Length, serverSalt, 0); hmac.TransformFinalBlock(clientSalt, 0, clientSalt.Length); Buffer.BlockCopy(hmac.Hash, 0, wowSessionKey, hmac.Hash.Length, hmac.Hash.Length); GameAccount.SessionKey = wowSessionKey.ToHexString(); // Update SessionKey in database DB.Auth.Update(GameAccount, "SessionKey"); }
public void Can_Persist_New_User_With_Hashed_Password() { // Arrange var userService = ServiceContext.UserService; // Act // NOTE: Normally the hash'ing would be handled in the membership provider, so the service just saves the password var password = "******"; var hash = new HMACSHA1(); hash.Key = Encoding.Unicode.GetBytes(password); var encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password))); var membershipUser = new User("JohnDoe", "*****@*****.**", encodedPassword, encodedPassword); userService.Save(membershipUser); // Assert Assert.That(membershipUser.HasIdentity, Is.True); Assert.That(membershipUser.RawPasswordValue, Is.Not.EqualTo(password)); Assert.That(membershipUser.RawPasswordValue, Is.EqualTo(encodedPassword)); IUser user = membershipUser as User; Assert.That(user, Is.Not.Null); }
private string GenerateTokenForTime(long time) { if (time == 0) { Logging.LogNullError(nameof(time), Bot.BotName); return(null); } byte[] sharedSecretArray = Convert.FromBase64String(SharedSecret); byte[] timeArray = new byte[8]; time /= 30L; for (int i = 8; i > 0; i--) { timeArray[i - 1] = (byte)time; time >>= 8; } byte[] hashedData; using (HMACSHA1 hmacGenerator = new HMACSHA1(sharedSecretArray, true)) { hashedData = hmacGenerator.ComputeHash(timeArray); } 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); byte[] codeArray = new byte[5]; for (int i = 0; i < 5; ++i) { codeArray[i] = TokenCharacters[codePoint % TokenCharacters.Length]; codePoint /= TokenCharacters.Length; } return(Encoding.UTF8.GetString(codeArray)); }
public string GenerateOtp(int input) { // Since .net uses little endian numbers, we need to reverse the byte order to get big endian. var data = BitConverter.GetBytes((long)input); Array.Reverse(data); HMAC hmac = null; switch (this.digest) { case Digest.Sha256: hmac = new HMACSHA256(); break; case Digest.Sha512: hmac = new HMACSHA512(); break; default: //case Digest.Sha1: hmac = new HMACSHA1(); break; } hmac.Key = Base32.Decode(this.secret); byte[] hashedValue = hmac.ComputeHash(data); int offset = hashedValue[hashedValue.Length - 1] & 0x0F; long result = (hashedValue[offset] & 0x7f) << 24 | (hashedValue[offset + 1] & 0xff) << 16 | (hashedValue[offset + 2] & 0xff) << 8 | (hashedValue[offset + 3] & 0xff) % 1000000; var truncatedValue = ((int)result % (int)Math.Pow(10, this.digits)); return(truncatedValue.ToString().PadLeft(this.digits, '0')); }
public static void Main(String[] args) { try { // Generate a signing key. HMACSHA1 Key = new HMACSHA1(); // Create an XML file to sign. CreateSomeXml("Example.xml"); Console.WriteLine("New XML file created."); // Sign the XML that was just created and save it in a // new file. SignXmlFile("Example.xml", "SignedExample.xml", Key); Console.WriteLine("XML file signed."); // Verify the signature of the signed XML. Console.WriteLine("Verifying Signature..."); bool result = VerifyXmlFile("SignedExample.xml", Key); // Display the results of the signature verification to \ // the console. if (result) { Console.WriteLine("The XML signature is valid."); } else { Console.WriteLine("The XML signature is not valid."); } } catch (CryptographicException e) { Console.WriteLine(e.Message); } }
public static string HashHMAC_SHA1(string input, string key, bool raw = false) { byte[] datBytes = Encoding.UTF8.GetBytes(input); byte[] keyBytes = Encoding.Default.GetBytes(key); using (HMACSHA1 hMac = new HMACSHA1(keyBytes)) { byte[] output = hMac.ComputeHash(datBytes); if (raw) { return(Encoding.Default.GetString(output)); } else { StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < output.Length; i++) { sBuilder.Append(output[i].ToString("x2")); } return(sBuilder.ToString()); } } }
// // EncodePassword // Encrypts, Hashes, or leaves the password clear based on the PasswordFormat. // 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; }
private string Sign(string url) { // add Google Client Id to query url += "&client=" + GoogleClientId; var encoding = new ASCIIEncoding(); // converting key to bytes will throw an exception, need to replace '-' and '_' characters first. var usablePrivateKey = GoogleCryptoKey.Replace("-", "+").Replace("_", "/"); var privateKeyBytes = Convert.FromBase64String(usablePrivateKey); var uri = new Uri(url); var encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query); // compute the hash var algorithm = new HMACSHA1(privateKeyBytes); var hash = algorithm.ComputeHash(encodedPathAndQueryBytes); // convert the bytes to string and make url-safe by replacing '+' and '/' characters var signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_"); // Add the signature to the existing URI. return(uri.Scheme + "://" + uri.Host + uri.LocalPath + uri.Query + "&signature=" + signature); }
public KeyedHashAlgorithm CreateAlgorithm(string name) { KeyedHashAlgorithm algorithm; switch (name) { case "HMACSHA1": algorithm = new HMACSHA1(); break; case "HMACSHA256": algorithm = new HMACSHA256(); break; case "HMACMD5": algorithm = new HMACMD5(); break; default: algorithm = KeyedHashAlgorithm.Create(name); break; } return(algorithm); }
internal Uri Sign(Uri _uri) { // Based on the C# sample from: https://developers.google.com/maps/documentation/business/webservices if (_uri == null) { throw new ArgumentNullException("_uri"); } if (this.ClientId == null) { throw new NullReferenceException("ClientID"); } if (string.IsNullOrWhiteSpace(this.SigningKey)) { throw new ArgumentException("Invalid signing key."); } 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(SigningKey); 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))); }
/// <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')); }
static bool Verify(string uri, dict plivoHttpParams, string xPlivoSignature, string authToken) { var isMatch = false; foreach (KeyValuePair <string, string> kvp in plivoHttpParams.OrderBy(key => key.Key)) { uri += kvp.Key + kvp.Value; } var enc = Encoding.ASCII; HMACSHA1 myhmacsha1 = new HMACSHA1(enc.GetBytes(authToken)); byte[] byteArray = Encoding.ASCII.GetBytes(uri); MemoryStream stream = new MemoryStream(byteArray); byte[] hashValue = myhmacsha1.ComputeHash(stream); string generatedSignature = Convert.ToBase64String(hashValue); if (xPlivoSignature.Equals(generatedSignature)) { isMatch = true; } return(isMatch); }
private static byte[] ComputeHmac(this HashAlgorithmEnum algorithm, byte[] key, byte[] input) { KeyedHashAlgorithm hmacAlgo = new HMACMD5(); switch (algorithm) { case HashAlgorithmEnum.Md5: hmacAlgo = new HMACMD5(key); break; case HashAlgorithmEnum.Sha1: hmacAlgo = new HMACSHA1(key); break; case HashAlgorithmEnum.Sha2256: hmacAlgo = new HMACSHA256(key); break; case HashAlgorithmEnum.Sha2384: hmacAlgo = new HMACSHA384(key); break; case HashAlgorithmEnum.Sha2512: hmacAlgo = new HMACSHA512(key); break; } return(hmacAlgo.ComputeHash(input)); }
// Esse método é igual ao exemplo fornecido pelo Google. // https://developers.google.com/maps/documentation/business/webservices/auth?hl=en-us private string IncludeSignature(string url, string keyString) { ASCIIEncoding encoding = new ASCIIEncoding(); // converting key to bytes will throw an exception, need to replace '-' and '_' characters first. string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/"); byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey); Uri uri = new Uri(url); byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query); // compute the hash HMACSHA1 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> /// Generates a signature using the specified signatureType /// </summary> /// <param name="url">The full url that needs to be signed including its non OAuth url parameters</param> /// <param name="consumerKey">The consumer key</param> /// <param name="consumerSecret">The consumer seceret</param> /// <param name="token">The token, if available. If not available pass null or an empty string</param> /// <param name="tokenSecret">The token secret, if available. If not available pass null or an empty string</param> /// <param name="httpMethod">The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)</param> /// <param name="signatureType">The type of signature to use</param> /// <returns>A base64 string of the hash value</returns> public string GenerateSignature(Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, string callback, SignatureTypes signatureType, out string normalizedUrl, out string normalizedRequestParameters) { normalizedUrl = null; normalizedRequestParameters = null; switch (signatureType) { case SignatureTypes.PLAINTEXT: return(HttpUtility.UrlEncode(string.Format("{0}&{1}", consumerSecret, tokenSecret))); case SignatureTypes.HMACSHA1: string signatureBase = GenerateSignatureBase(url, consumerKey, token, tokenSecret, httpMethod, timeStamp, nonce, callback, HMACSHA1SignatureType, out normalizedUrl, out normalizedRequestParameters); HMACSHA1 hmacsha1 = new HMACSHA1(); hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret))); return(GenerateSignatureUsingHash(signatureBase, hmacsha1)); case SignatureTypes.RSASHA1: throw new NotImplementedException(); default: throw new ArgumentException("Unknown signature type", "signatureType"); } }
public static string Generate(byte[] pbSecret, ulong uFactor, uint uCodeDigits, bool bAddChecksum, int iTruncationOffset) { byte[] pbText = MemUtil.UInt64ToBytes(uFactor); Array.Reverse(pbText); // Big-Endian #if KeePass2PCL var hsha1 = WinRTCrypto.MacAlgorithmProvider.OpenAlgorithm(MacAlgorithm.HmacSha1).CreateHash(pbSecret); hsha1.Append(pbText); var pbHash = hsha1.GetValueAndReset(); #else HMACSHA1 hsha1 = new HMACSHA1(pbSecret); byte[] pbHash = hsha1.ComputeHash(pbText); #endif uint uOffset = (uint)(pbHash[pbHash.Length - 1] & 0xF); if ((iTruncationOffset >= 0) && (iTruncationOffset < (pbHash.Length - 4))) { uOffset = (uint)iTruncationOffset; } uint uBinary = (uint)(((pbHash[uOffset] & 0x7F) << 24) | ((pbHash[uOffset + 1] & 0xFF) << 16) | ((pbHash[uOffset + 2] & 0xFF) << 8) | (pbHash[uOffset + 3] & 0xFF)); uint uOtp = (uBinary % vDigitsPower[uCodeDigits]); if (bAddChecksum) { uOtp = ((uOtp * 10) + CalculateChecksum(uOtp, uCodeDigits)); } uint uDigits = (bAddChecksum ? (uCodeDigits + 1) : uCodeDigits); return(uOtp.ToString(NumberFormatInfo.InvariantInfo).PadLeft( (int)uDigits, '0')); }
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; }
public static string Generate(byte[] pbSecret, ulong uFactor, uint uCodeDigits, bool bAddChecksum, int iTruncationOffset) { byte[] pbText = MemUtil.UInt64ToBytes(uFactor); Array.Reverse(pbText); // To big-endian byte[] pbHash; using (HMACSHA1 h = new HMACSHA1(pbSecret)) { pbHash = h.ComputeHash(pbText); } uint uOffset = (uint)(pbHash[pbHash.Length - 1] & 0xF); if ((iTruncationOffset >= 0) && (iTruncationOffset < (pbHash.Length - 4))) { uOffset = (uint)iTruncationOffset; } uint uBinary = (uint)(((pbHash[uOffset] & 0x7F) << 24) | ((pbHash[uOffset + 1] & 0xFF) << 16) | ((pbHash[uOffset + 2] & 0xFF) << 8) | (pbHash[uOffset + 3] & 0xFF)); uint uOtp = (uBinary % g_vDigitsPower[uCodeDigits]); if (bAddChecksum) { uOtp = ((uOtp * 10) + CalculateChecksum(uOtp, uCodeDigits)); } uint uDigits = (bAddChecksum ? (uCodeDigits + 1) : uCodeDigits); return(uOtp.ToString(NumberFormatInfo.InvariantInfo).PadLeft( (int)uDigits, '0')); }
/// <summary> /// Вычисление цифровой подписи /// </summary> /// <param name="requestParams">Входные параметры</param> /// <param name="secretWord">Секретное слово</param> /// <param name="action">Используемый метод</param> /// <returns></returns> public static string Compute(Dictionary <string, string> requestParams, string secretWord, string action) { var normalizedParams = requestParams .ToDictionary(k => k.Key.ToLower(), v => v.Value); var cmdFields = Mapping[action]; var builder = new StringBuilder(); foreach (var cmdField in cmdFields) { if (normalizedParams.ContainsKey(cmdField)) { builder.Append(normalizedParams[cmdField]); } } HMACSHA1 hmac; if (string.IsNullOrWhiteSpace(secretWord)) { // В алгоритме всегда должно быть задан ключ шифрования. Если используется конструктор по умолчанию, то ключ генерируется автоматически, // что нам не подходит hmac = new HMACSHA1(HashEncoding.GetBytes(string.Empty)); } else { hmac = new HMACSHA1(HashEncoding.GetBytes(secretWord)); } var hash = hmac.ComputeHash( HashEncoding.GetBytes(builder.ToString())); var result = new StringBuilder(); foreach (var item in hash) { result.Append(item.ToString("X2")); } return(result.ToString()); }
/// <summary> /// /// </summary> /// <param name="purpose"></param> /// <param name="token"></param> /// <param name="manager"></param> /// <param name="user"></param> /// <returns></returns> public virtual async Task <bool> ValidateAsync(string purpose, string token, UserManager <TUser> manager, TUser user) { var key = await manager.GetAuthenticatorKeyAsync(user); if (!int.TryParse(token, out int code)) { return(false); } var hash = new HMACSHA1(Base32.FromBase32(key)); var unixTimestamp = Convert.ToInt64(Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds)); var timestep = Convert.ToInt64(unixTimestamp / 30); // 允许代码从90年代在每个方向(我们可以使这可配置?) for (int i = -2; i <= 2; i++) { var expectedCode = Rfc6238AuthenticationService.ComputeTotp(hash, (ulong)(timestep + i), modifier: null); if (expectedCode == code) { return(true); } } return(false); }
public static JodelHttpClient Create(DateTime timestamp, string stringifiedPayload = "", string accesstoken = "", HttpMethod method = null) { var httpClient = new JodelHttpClient(); var keyByte = Encoding.UTF8.GetBytes(Constants.HMAC_SECRET); var hmacsha1 = new HMACSHA1(keyByte); hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(stringifiedPayload)); httpClient.AddRequestHeader("X-Timestamp", $"{timestamp:s}Z"); httpClient.AddRequestHeader("X-Authorization", "HMAC " + hmacsha1.Hash.Aggregate(string.Empty, (current, t) => current + t.ToString("X2"))); if (!string.IsNullOrEmpty(accesstoken)) { httpClient.AddRequestHeader("Authorization", "Bearer " + accesstoken); } if (method != HttpMethod.Get) { httpClient.AddPostsHeaders(); } return(httpClient); }
protected string serviceSignature(Dictionary <string, string> headers, Dictionary <string, string> parameters, string secretKey) { Dictionary <string, string> calcParams = checkNotExcluded(headers); if (null != parameters) { foreach (var param in parameters) { calcParams.Add(param.Key, param.Value); } } SignatureBytes sb = new SignatureBytes(); foreach (var param in calcParams) { sb.AddField(param.Key, param.Value); } HMACSHA1 mac = new HMACSHA1(); mac.Key = Encoding.UTF8.GetBytes(secretKey); byte[] hashBytes = mac.ComputeHash(sb.GetData()); return(Convert.ToBase64String(hashBytes)); }
public static string Hash(string plainText, string privateKey, int cipherStrength) { try { byte[] KeyBytes = Encoder.GetBytes(privateKey); HMAC Cipher = null; if (cipherStrength == 1) { Cipher = new HMACSHA1(KeyBytes); } else if (cipherStrength == 256) { Cipher = new HMACSHA256(KeyBytes); } else if (cipherStrength == 384) { Cipher = new HMACSHA384(KeyBytes); } else if (cipherStrength == 512) { Cipher = new HMACSHA512(KeyBytes); } else { throw new Exception("Enter a valid cipher strength."); } byte[] PlainBytes = Encoder.GetBytes(plainText); byte[] HashedBytes = Cipher.ComputeHash(PlainBytes); return(Convert.ToBase64String(HashedBytes)); } catch (Exception ex) { //Don't log here. Logging should be down in calling method. throw ex; } }
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; }
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; }
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); }
/// <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); }
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); }
/** * */ 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 ); } }
public byte[] ComputeHash(byte[] source, byte[] key) { HMACSHA1 hma = new HMACSHA1(key); return hma.ComputeHash(source); }
public byte[] ComputeHash(string source, string key, Encoding encoding) { HMACSHA1 hma = new HMACSHA1(encoding.GetBytes(key)); return hma.ComputeHash(encoding.GetBytes(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); }
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("/", "_"); }
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; } }
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(); }
static void Symmetric (string filename, byte[] key) { string shortName = Path.GetFileName (filename); XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; XmlTextReader xtr = new XmlTextReader (GetReader (filename)); XmlValidatingReader xvr = new XmlValidatingReader (xtr); xtr.Normalization = true; doc.Load (xvr); try { XmlNodeList nodeList = doc.GetElementsByTagName ("Signature", SignedXml.XmlDsigNamespaceUrl); XmlElement signature = (XmlElement) nodeList [0]; SignedXml s = new SignedXml (); s.LoadXml (signature); HMACSHA1 mac = new HMACSHA1 (key); if (s.CheckSignature (mac)) { Console.WriteLine ("valid {0}", shortName); valid++; } else { Console.WriteLine ("INVALID {0}", shortName); invalid++; } } catch (Exception ex) { Console.WriteLine ("EXCEPTION " + shortName + " " + ex); error++; } }
/// <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); }
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; }
//------------------------------------------------------------------------------- #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); }
/// <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; }
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; } }
/// <summary> /// Creates a signature value given a signature base and the consumer secret and a known token secret. /// </summary> /// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.2"/> /// <param name="signatureMethod">The hashing method</param> /// <param name="signatureTreatment">The treatment to use on a signature value</param> /// <param name="signatureBase">The signature base</param> /// <param name="consumerSecret">The consumer secret</param> /// <param name="tokenSecret">The token secret</param> /// <returns></returns> public static string GetSignature(OAuthSignatureMethod signatureMethod, OAuthSignatureTreatment signatureTreatment, string signatureBase, string consumerSecret, string tokenSecret) { if (tokenSecret.IsNullOrBlank()) { tokenSecret = String.Empty; } consumerSecret = UrlEncodeRelaxed(consumerSecret); tokenSecret = UrlEncodeRelaxed(tokenSecret); string signature; switch (signatureMethod) { case OAuthSignatureMethod.HmacSha1: { var crypto = new HMACSHA1(); var key = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); crypto.Key = _encoding.GetBytes(key); signature = signatureBase.HashWith(crypto); break; } default: throw new NotImplementedException("Only HMAC-SHA1 is currently supported."); } var result = signatureTreatment == OAuthSignatureTreatment.Escaped ? UrlEncodeRelaxed(signature) : signature; return result; }
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 " ); }
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; }