public void AuthenticateRequest(WebRequest request, string base64Secret)
 {
     var secret = Convert.FromBase64String(base64Secret);
     //var url = Encoding.Default.GetBytes(request.RequestUri.ToString());
     var hashingAlg = new System.Security.Cryptography.HMACSHA1(secret);
     Convert.ToBase64String(hashingAlg.ComputeHash(Encoding.UTF8.GetBytes(request.RequestUri.ToString())));
 }
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            string qry = @"
            SELECT
             L.[Id]
            ,L.[Password]
            ,L.[Guid]
            FROM
            [UserLogin] L
            INNER JOIN [EntityType] ET ON ET.[Id] = L.[entityTypeId] AND ET.[Guid] = '4E9B798F-BB68-4C0E-9707-0928D15AB020'
            ";
            var rdr = Rock.Data.DbService.GetDataReader( qry, System.Data.CommandType.Text, null );
            while ( rdr.Read() )
            {
                var hash = new System.Security.Cryptography.HMACSHA1();
                hash.Key = HexToByte( rdr["Guid"].ToString().Replace( "-", "" ) );

                string oldPassword = rdr["Password"].ToString();
                string newPassword = Convert.ToBase64String( hash.ComputeHash( Convert.FromBase64String( oldPassword ) ) );

                string updateQry = string.Format( @"
            UPDATE
            [UserLogin]
            SET
            [Password] = '{0}'
            WHERE
            [Id] = {1}
            ", newPassword, rdr["Id"].ToString() );

                Rock.Data.DbService.ExecuteCommand( updateQry, System.Data.CommandType.Text );
            }

            rdr.Close();
        }
        public void AuthenticateRequest(WebRequest request, string base64Secret)
        {
            var secret = Convert.FromBase64String(base64Secret);
            var hashingAlg = new System.Security.Cryptography.HMACSHA1(secret);

            var canonHeaders = request.Headers.AllKeys
                .Where(h => h.StartsWith("x-emc", StringComparison.InvariantCultureIgnoreCase))
                .OrderBy(h => h.ToLowerInvariant())
                .Select(h => h + ":" + request.Headers[h].Trim())
                .Aggregate(string.Empty, (current, header) => current + header + "\n")
                .TrimEnd('\n');

            var contentType = request.ContentType ?? string.Empty;
            var range = request.Headers["range"] ?? string.Empty;
            var date = request.Headers["date"] ?? string.Empty;
            var requestRelativeUri = Uri.UnescapeDataString(request.RequestUri.Segments.Aggregate(string.Empty, (current, segment) => current + segment) + request.RequestUri.Query);

            var hashString = request.Method + "\n" +
                             contentType + "\n" +
                             range + "\n" +
                             date + "\n" +
                             requestRelativeUri + "\n" +
                             canonHeaders;

            var signature = Convert.ToBase64String(hashingAlg.ComputeHash(Encoding.Default.GetBytes(hashString)));
            request.Headers.Add("x-emc-signature", signature);
        }
        /// <summary>
        /// Calculates the signature for an OAuth call.
        /// </summary>
        /// <param name="method">POST or GET method.</param>
        /// <param name="url">The URL the request will be sent to.</param>
        /// <param name="parameters">Parameters to be added to the signature.</param>
        /// <param name="tokenSecret">The token secret (either request or access) for generating the SHA-1 key.</param>
        /// <returns>Base64 encoded SHA-1 hash.</returns>
        public string OAuthCalculateSignature(string method, string url, Dictionary<string, string> parameters, string oAuthAccessTokenSecret)
        {
            string baseString = "";
            string key = ApiSecret + "&" + oAuthAccessTokenSecret;
            byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(key);

            SortedList<string, string> sorted = parameters.ToSortedList();

            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, string> pair in sorted)
            {
                sb.Append(pair.Key);
                sb.Append("=");
                sb.Append(pair.Value.ToEscapeOAuth());
                sb.Append("&");
            }

            //remove last &
            sb.Remove(sb.Length - 1, 1);

            baseString = method + "&" + url.ToEscapeOAuth() + "&" + sb.ToString().ToEscapeOAuth();

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(keyBytes);

            byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(baseString));

            string hash = Convert.ToBase64String(hashBytes);

            //Debug.WriteLine("key  = " + key);
            //Debug.WriteLine("base = " + baseString);
            //Debug.WriteLine("sig  = " + hash);

            return hash;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Method to Sign your app key
        /// This should be called with each URI resource
        /// before sending any HTTP command to the remote server
        /// </summary>
        /// <param name="url"></param>
        /// <param name="app"></param>
        /// <returns></returns>
        public static string Sign(string url)
        {
            try
            {
                // Add appSID parameter.
                UriBuilder builder = new UriBuilder(url);
                if (builder.Query != null && builder.Query.Length > 1)
                    builder.Query = builder.Query.Substring(1) + "&appSID=" + AsposeApp.AppSID;
                else
                    builder.Query = "appSID=" + AsposeApp.AppSID;
                // Remove final slash here as it can be added automatically.
                builder.Path = builder.Path.TrimEnd('/');
                // Compute the hash.

                byte[] privateKey = System.Text.Encoding.UTF8.GetBytes(AsposeApp.AppKey);

                System.Security.Cryptography.HMACSHA1 algorithm = new System.Security.Cryptography.HMACSHA1(privateKey);
                //System.Text.ASCIIEncoding
                byte[] sequence = System.Text.ASCIIEncoding.ASCII.GetBytes(builder.Uri.AbsoluteUri);
                byte[] hash = algorithm.ComputeHash(sequence);
                string signature = Convert.ToBase64String(hash);
                // Remove invalid symbols.
                signature = signature.TrimEnd('=');
                signature = System.Web.HttpUtility.UrlEncode(signature);
                // Convert codes to upper case as they can be updated automatically.
                signature = System.Text.RegularExpressions.Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());
                //signature = System.Text.RegularExpressions.Regex.Replace(signature, "%[0-9a-f]{2}", delegate(string e){ e.Value.ToUpper()});
                // Add the signature to query string.
                return string.Format("{0}&signature={1}", builder.Uri.AbsoluteUri, signature);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 6
0
 public static string sign(String data, String appSecret)
 {
     System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1();
     hmacsha1.Key = Encoding.UTF8.GetBytes(appSecret);
     byte[] dataBuffer = Encoding.UTF8.GetBytes(data);
     byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
     return byteToHexStr(hashBytes);
 }
Ejemplo n.º 7
0
 public static string GetSig(string policyStr, string secretKey)
 {
     policyStr = GetBase64_string(policyStr);
     var signature = new System.Security.Cryptography.HMACSHA1(GetBase64(secretKey));
     var bytes = GetBase64(policyStr);
     var moreBytes = signature.ComputeHash(bytes);
     var encodedCanonical = Convert.ToBase64String(moreBytes);
     return encodedCanonical;
 }
        public string AuthenticateRequest(string queryString, string base64Secret)
        {
            var queryBytes = Encoding.UTF8.GetBytes(queryString.ToLower());
            var secret = Encoding.UTF8.GetBytes(base64Secret);
            var hashingAlg = new System.Security.Cryptography.HMACSHA1(secret);
            var hashedQuery = hashingAlg.ComputeHash(queryBytes);
            var base64Hash = Convert.ToBase64String(hashedQuery);
            var signature = Uri.EscapeDataString(base64Hash);

            return signature;
        }
        internal static byte[] ComputeHmacSha1Hash(byte[] data, byte[] key)
        {
            Contract.Requires(data != null);
            Contract.Requires(key != null);
            Contract.Ensures(Contract.Result<byte[]>() != null);

            using (var crypto = new System.Security.Cryptography.HMACSHA1(key))
            {
                return crypto.ComputeHash(data);
            }
        }
Ejemplo n.º 10
0
        public void Configuration(IAppBuilder app)
        {
            AsyncOAuth.OAuthUtility.ComputeHash = (key, buffer) =>
            {
                using (var hmac = new System.Security.Cryptography.HMACSHA1(key))
                {
                    return hmac.ComputeHash(buffer);
                }
            };

            ConfigureAuth(app);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Gets a HMAC-SHA1 hash for an OAuth request.
        /// </summary>
        /// <param name="consumerSecret">
        /// The consumer secret.
        /// </param>
        /// <param name="oauthSecret">
        /// The OAuth secret.
        /// </param>
        /// <param name="signatureBaseString">
        /// The signature base string for which to compute the hash.
        /// </param>
        /// <returns>
        /// A HMAC-SHA1 hash of <paramref name="signatureBaseString"/>.
        /// </returns>
        public string ComputeHash(string consumerSecret, string oauthSecret, string signatureBaseString)
        {
            if (signatureBaseString == null)
                return null;

            byte[] key = Encoding.UTF8.GetBytes(String.Format("{0}&{1}", consumerSecret, oauthSecret));
            using (System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(key))
            {
                byte[] signatureBaseStringHash = sha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString));
                return Convert.ToBase64String(signatureBaseStringHash);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates an HMAC-SHA1 hash from an array of parameters and a security token.
        /// </summary>
        /// <param name="paramList">The parameters to be hashed</param>
        /// <param name="signingKey">The Subscriber's unique signing key.</param>
        /// <returns>The BASE64-encoded HMAC</returns>
        public static string CalculateHMAC(string signingKey, params object[] paramList)
        {
            byte[] key = Encoding.UTF8.GetBytes(signingKey);
            string stringToSign = Canonicalize(paramList);
            byte[] bytesToSign = Encoding.UTF8.GetBytes(stringToSign);
            byte[] signature;

            using (var hmac = new System.Security.Cryptography.HMACSHA1(key))
            {
                signature = hmac.ComputeHash(bytesToSign);
            }

            return System.Convert.ToBase64String(signature);
        }
Ejemplo n.º 13
0
        public void Initialize(byte[] sessionKey)
        {
            // create RC4-drop[1024] stream
            using(HMACSHA1 outputHMAC = new HMACSHA1(encryptionKey))
                encryptionStream = new ARC4(outputHMAC.ComputeHash(sessionKey));
            encryptionStream.Process(new byte[1024], 0, 1024);

            // create RC4-drop[1024] stream
            using(HMACSHA1 inputHMAC = new HMACSHA1(decryptionKey))
                decryptionStream = new ARC4(inputHMAC.ComputeHash(sessionKey));
            decryptionStream.Process(new byte[1024], 0, 1024);

            Status = AuthStatus.Ready;
        }
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            // Update the Admin's password to be encoded using the current passwordKey setting in web.config
            string encryptionKey = System.Configuration.ConfigurationManager.AppSettings["PasswordKey"];
            if ( !String.IsNullOrWhiteSpace( encryptionKey ) )
            {
                var hash = new System.Security.Cryptography.HMACSHA1();
                hash.Key = Encryption.HexToByte( encryptionKey );
                string newPassword = Convert.ToBase64String( hash.ComputeHash( System.Text.Encoding.Unicode.GetBytes( "admin" ) ) );

                Sql( string.Format( "Update [UserLogin] SET [Password] = '{0}' WHERE [UserName] = 'Admin'", newPassword ) );
            }

            AddColumn("dbo.GroupLocation", "GroupMemberPersonId", c => c.Int());
            CreateIndex("dbo.GroupLocation", "GroupMemberPersonId");
            AddForeignKey("dbo.GroupLocation", "GroupMemberPersonId", "dbo.Person", "Id", cascadeDelete: true);
        }
Ejemplo n.º 15
0
        private static string Sign(string content, string signKey)
        {
#if NETFX_CORE
            Windows.Security.Cryptography.Core.MacAlgorithmProvider HmacSha1Provider = Windows.Security.Cryptography.Core.MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
            var keyMaterial      = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(signKey, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
            var hmacSha1Provider = Windows.Security.Cryptography.Core.MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
            var macKey           = HmacSha1Provider.CreateKey(keyMaterial);
            var dataToBeSigned   = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(content, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
            var signatureBuffer  = Windows.Security.Cryptography.Core.CryptographicEngine.Sign(macKey, dataToBeSigned);
            var result           = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(signatureBuffer);
#else
            var data         = Encoding.UTF8.GetBytes(content);
            var signKeyBytes = Encoding.UTF8.GetBytes(signKey);
            var algorithm    = new System.Security.Cryptography.HMACSHA1(signKeyBytes);
            var result       = Convert.ToBase64String(algorithm.ComputeHash(data));
#endif
            return(result);
        }
Ejemplo n.º 16
0
        public static string GetSignature(string method, Uri uri, IDictionary <string, string> parameters, string clientSecret, string tokenSecret)
        {
            var stringBuilder = new StringBuilder($"{method.ToUpper()}&{Uri.EscapeDataString(uri.AbsoluteUri)}&");

            foreach (var keyValuePair in parameters)
            {
                stringBuilder.Append(Uri.EscapeDataString($"{keyValuePair.Key}={keyValuePair.Value}&"));
            }
            string signatureBaseString = stringBuilder.ToString().Substring(0, stringBuilder.Length - 3);

            string signatureKey = $"{Uri.EscapeDataString(clientSecret)}&{Uri.EscapeDataString(tokenSecret)}";
            var    hmacsha1     = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(signatureKey));


            string signatureString = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString)));

            return(signatureString);
        }
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            // Update the Admin's password to be encoded using the current passwordKey setting in web.config
            string encryptionKey = System.Configuration.ConfigurationManager.AppSettings["PasswordKey"];

            if (!String.IsNullOrWhiteSpace(encryptionKey))
            {
                var hash = new System.Security.Cryptography.HMACSHA1();
                hash.Key = Encryption.HexToByte(encryptionKey);
                string newPassword = Convert.ToBase64String(hash.ComputeHash(System.Text.Encoding.Unicode.GetBytes("admin")));

                Sql(string.Format("Update [UserLogin] SET [Password] = '{0}' WHERE [UserName] = 'Admin'", newPassword));
            }

            AddColumn("dbo.GroupLocation", "GroupMemberPersonId", c => c.Int());
            CreateIndex("dbo.GroupLocation", "GroupMemberPersonId");
            AddForeignKey("dbo.GroupLocation", "GroupMemberPersonId", "dbo.Person", "Id", cascadeDelete: true);
        }
Ejemplo n.º 18
0
        public string Sign(string URIRequest, string AppSIDValue, string AppKeyValue)
        {
            try
            {
                // Add appSID parameter.
                UriBuilder builder = new UriBuilder(URIRequest);
                if (builder.Query != null && builder.Query.Length > 1)
                {
                    builder.Query = builder.Query.Substring(1) + "&appSID=" + AppSIDValue;
                }
                else
                {
                    builder.Query = "appSID=" + AppSIDValue;
                }

                // Remove final slash here as it can be added automatically.
                builder.Path = builder.Path.TrimEnd('/');

                byte[] privateKey = System.Text.Encoding.UTF8.GetBytes(AppKeyValue);

                System.Security.Cryptography.HMACSHA1 algorithm = new System.Security.Cryptography.HMACSHA1(privateKey);

                byte[] sequence  = System.Text.ASCIIEncoding.ASCII.GetBytes(builder.Uri.AbsoluteUri);
                byte[] hash      = algorithm.ComputeHash(sequence);
                string signature = Convert.ToBase64String(hash);

                // Remove invalid symbols.
                signature = signature.TrimEnd('=');

                //signature = System.Web.HttpUtility.UrlEncode(signature);
                signature = System.Uri.EscapeDataString(signature);

                // Convert codes to upper case as they can be updated automatically.
                signature = System.Text.RegularExpressions.Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper());

                // Add the signature to query string.
                return(string.Format("{0}&signature={1}", builder.Uri.AbsoluteUri, signature));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Ejemplo n.º 19
0
        protected void decode(int stanzaSize, bool useDecrypt)
        {
            int size = stanzaSize;

            byte[] data     = new byte[size];
            byte[] dataReal = null;
            Buffer.BlockCopy(this.buffer.ToArray(), 0, data, 0, size);

            byte[] packet = new byte[size - 4];

            byte[] hashServerByte = new byte[4];
            Buffer.BlockCopy(data, 0, hashServerByte, 0, 4);
            Buffer.BlockCopy(data, 4, packet, 0, size - 4);

            System.Security.Cryptography.HMACSHA1 h = new System.Security.Cryptography.HMACSHA1(this.Encryptionkey);
            byte[] hashByte = new byte[4];
            Buffer.BlockCopy(h.ComputeHash(packet, 0, packet.Length), 0, hashByte, 0, 4);

            if (hashServerByte.SequenceEqual(hashByte))
            {
                this.buffer.RemoveRange(0, 4);
                if (useDecrypt)
                {
                    dataReal = Encryption.WhatsappDecrypt(this.Encryptionkey, packet);
                }
                else
                {
                    dataReal = Encryption.WhatsappEncrypt(this.Encryptionkey, packet, true);
                    //dataReal = new byte[foo.Length - 4];
                    //Buffer.BlockCopy(foo, 0, dataReal, 0, dataReal.Length);
                }

                for (int i = 0; i < size - 4; i++)
                {
                    this.buffer[i] = dataReal[i];
                }
            }
            else
            {
                throw new Exception("Hash doesnt match");
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Calculates the signature for an OAuth call.
        /// </summary>
        /// <param name="method">POST or GET method.</param>
        /// <param name="url">The URL the request will be sent to.</param>
        /// <param name="parameters">Parameters to be added to the signature.</param>
        /// <param name="tokenSecret">The token secret (either request or access) for generating the SHA-1 key.</param>
        /// <returns>Base64 encoded SHA-1 hash.</returns>
        public string OAuthCalculateSignature(string method, string url, Dictionary <string, string> parameters, string tokenSecret)
        {
            string baseString = "";
            string key        = ApiSecret + "&" + tokenSecret;

            byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(key);

#if !SILVERLIGHT
            SortedList <string, string> sorted = new SortedList <string, string>();
            foreach (KeyValuePair <string, string> pair in parameters)
            {
                sorted.Add(pair.Key, pair.Value);
            }
#else
            var sorted = parameters.OrderBy(p => p.Key);
#endif

            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair <string, string> pair in sorted)
            {
                sb.Append(pair.Key);
                sb.Append("=");
                sb.Append(UtilityMethods.EscapeOAuthString(pair.Value));
                sb.Append("&");
            }

            sb.Remove(sb.Length - 1, 1);

            baseString = method + "&" + UtilityMethods.EscapeOAuthString(url) + "&" + UtilityMethods.EscapeOAuthString(sb.ToString());

#if WindowsCE
            FlickrNet.Security.Cryptography.HMACSHA1 sha1 = new FlickrNet.Security.Cryptography.HMACSHA1(keyBytes);
#else
            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(keyBytes);
#endif

            byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(baseString));

            string hash = Convert.ToBase64String(hashBytes);

            return(hash);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <param name="container"></param>
        /// <param name="path"></param>
        /// <param name="expire"></param>
        /// <returns></returns>
        public static async Task <Uri> GetPreSignUriAsync(this SelectelClient client, string container, string path, TimeSpan expire)
        {
            var containerInfo = await client.ExecuteAsync(new GetContainerInfoRequest(container));

            var customHeaders = containerInfo.CustomHeaders;

            if (customHeaders == null)
            {
                customHeaders = new Dictionary <String, String>();
            }

            var customHeader = "X-Container-Meta-Temp-Url-Key";

            String secretKey = String.Empty;

            if (customHeaders.ContainsKey(customHeader))
            {
                secretKey = customHeaders[customHeader];
            }
            else
            {
                secretKey = CreateRandomString(64);
                customHeaders.Add(customHeader, secretKey);
                await client.SetContainerMetaAsync(container, containerInfo.Type, customHeaders.ToDictionary(k => k.Key, v => (object)v.Value));
            }

            var expires = Helpers.DateToUnixTimestamp(DateTime.UtcNow.Add(expire));

            String sig;

            using (var hasher = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(secretKey)))
            {
                var method  = "GET";
                var relPath = String.Format("/{0}/{1}", container, path);

                var hmac_body = String.Format("{0}\n{1}\n{2}", method, expires, relPath);

                sig = BitConverter.ToString(hasher.ComputeHash(Encoding.UTF8.GetBytes(hmac_body))).Replace("-", "").ToLower();
            }

            return(new Uri(String.Format("{0}{1}/{2}?temp_url_sig={3}&temp_url_expires={4}", client.StorageUrl, container, path, sig, expires)));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Calculates the signature for an OAuth call.
        /// </summary>
        /// <param name="method">POST or GET method.</param>
        /// <param name="url">The URL the request will be sent to.</param>
        /// <param name="parameters">Parameters to be added to the signature.</param>
        /// <param name="tokenSecret">The token secret (either request or access) for generating the SHA-1 key.</param>
        /// <returns>Base64 encoded SHA-1 hash.</returns>
        public string OAuthCalculateSignature(string method, string url, Dictionary<string, string> parameters, string tokenSecret)
        {
            string baseString = "";
            string key = ApiSecret + "&" + tokenSecret;
            byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(key);

            #if !SILVERLIGHT
            SortedList<string, string> sorted = new SortedList<string, string>();
            foreach (KeyValuePair<string, string> pair in parameters) { sorted.Add(pair.Key, pair.Value); }
            #else
                var sorted = parameters.OrderBy(p => p.Key);
            #endif

            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, string> pair in sorted)
            {
                sb.Append(pair.Key);
                sb.Append("=");
                sb.Append(UtilityMethods.EscapeOAuthString(pair.Value));
                sb.Append("&");
            }

            sb.Remove(sb.Length - 1, 1);

            baseString = method + "&" + UtilityMethods.EscapeOAuthString(url) + "&" + UtilityMethods.EscapeOAuthString(sb.ToString());

            #if WindowsCE
            FlickrNet.Security.Cryptography.HMACSHA1 sha1 = new FlickrNet.Security.Cryptography.HMACSHA1(keyBytes);
            #else
            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(keyBytes);
            #endif

            byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(baseString));

            string hash = Convert.ToBase64String(hashBytes);

            Debug.WriteLine("key  = " + key);
            Debug.WriteLine("base = " + baseString);
            Debug.WriteLine("sig  = " + hash);

            return hash;
        }
Ejemplo n.º 23
0
		//-------------------------------------------------

		public static string AesDecrypt(string password, string base64)
		{
			// Turn input string into a byte array.
			var input = System.Convert.FromBase64String(base64);
			// Create an instance of the Rijndael class.
			var cipher = new System.Security.Cryptography.AesCryptoServiceProvider();
			// Calculate salt to make it harder to guess key by using a dictionary attack.
			var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);
			var hmac = new System.Security.Cryptography.HMACSHA1(passwordBytes);
			var salt = hmac.ComputeHash(passwordBytes);
			// Generate Secret Key from the password and salt.
			// Note: Set number of iterations to 10 in order for JavaScript example to work faster.
			var secretKey = new System.Security.Cryptography.Rfc2898DeriveBytes(passwordBytes, salt, 10);
			// Create a encryptor from the existing SecretKey bytes by using
			// 32 bytes (256 bits) for the secret key and
			// 16 bytes (128 bits) for the initialization vector (IV).
			var key = secretKey.GetBytes(32);
			var iv = secretKey.GetBytes(16);
			// Get cryptor as System.Security.Cryptography.ICryptoTransform class.
			var cryptor = cipher.CreateDecryptor(key, iv);
			// Create new Input.
			var inputBuffer = new System.Byte[input.Length];
			// Copy data bytes to input buffer.
			System.Buffer.BlockCopy(input, 0, inputBuffer, 0, inputBuffer.Length);
			// Create a MemoryStream to hold the output bytes.
			var stream = new System.IO.MemoryStream();
			// Create a CryptoStream through which we are going to be processing our data.
			var mode = System.Security.Cryptography.CryptoStreamMode.Write;
			var cryptoStream = new System.Security.Cryptography.CryptoStream(stream, cryptor, mode);
			// Start the decrypting process.
			cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
			// Finish decrypting.
			cryptoStream.FlushFinalBlock();
			// Convert data from a memoryStream into a byte array.
			var outputBuffer = stream.ToArray();
			// Close both streams.
			stream.Close();
			//cryptoStream.Close();
			// Convert encrypted data into a base64-encoded string.
			var s = System.Text.Encoding.UTF8.GetString(outputBuffer);
			return s;
		}
Ejemplo n.º 24
0
        /// <summary>
        /// 本方法生成http请求的csb签名值。
        /// 调用csb服务时,需要在httpheader中增加以下几个头信息:
        /// _api_name: csb服务名
        /// _api_version: csb服务版本号
        /// _api_access_key: csb上的凭证ak
        /// _api_timestamp: 时间戳
        /// _api_signature: 本方法返回的签名串
        /// </summary>
        /// <param name="apiName">csb服务名</param>
        /// <param name="apiVersion">csb服务版本号</param>
        /// <param name="timeStamp">时间戳</param>
        /// <param name="accessKey">csb上的凭证ak</param>
        /// <param name="secretKey">csb上凭证的sk</param>
        /// <param name="formParamDict">form表单提交的参数列表(各参数值是还未urlEncoding编码的原始业务参数值)。如果是form提交,请使用 Content-Type= application/x-www-form-urlencoded </param>
        /// <param name="body">非form表单方式提交的请求内容,目前没有参与签名计算</param>
        /// <returns>签名串。</returns>
        public static string sign(string apiName, string apiVersion, long timeStamp, string accessKey, string secretKey, Dictionary <string, object[]> formParamDict, object body)
        {
            Dictionary <string, object[]> newDict = new Dictionary <string, object[]>();

            if (formParamDict != null)
            {
                foreach (KeyValuePair <string, object[]> pair in formParamDict)
                {
                    newDict.Add(pair.Key, pair.Value);
                }
            }

            //设置csb要求的头参数
            newDict.Add("_api_name", new String[] { apiName });
            newDict.Add("_api_version", new String[] { apiVersion });
            newDict.Add("_api_access_key", new String[] { accessKey });
            newDict.Add("_api_timestamp", new object[] { timeStamp });

            //对所有参数进行排序
            var           sortedDict = from pair in newDict orderby pair.Key select pair;
            StringBuilder builder    = new StringBuilder();

            foreach (KeyValuePair <string, object[]> pair in sortedDict)
            {
                foreach (object obj in pair.Value)
                {
                    builder.Append(string.Format("{0}={1}&", pair.Key, obj));
                }
            }
            string str = builder.ToString();

            if (str.EndsWith("&"))
            {
                str = str.Substring(0, str.Length - 1); //去掉最后一个多余的 & 符号
            }
            System.Security.Cryptography.HMACSHA1 hmacsha = new System.Security.Cryptography.HMACSHA1
            {
                Key = Encoding.UTF8.GetBytes(secretKey)
            };
            byte[] bytes = Encoding.UTF8.GetBytes(str);
            return(Convert.ToBase64String(hmacsha.ComputeHash(bytes)));
        }
Ejemplo n.º 25
0
        public static string GetSignature(string method, Uri uri, IDictionary <string, string> parameters, string clientSecret, string tokenSecret)
        {
            var url = uri.AbsoluteUri;

            if (!string.IsNullOrWhiteSpace(uri.Query))
            {
                url = url.Replace(uri.Query, "");
            }
            var urlString        = $"{method.ToUpper()}&{Uri.EscapeDataString(url)}";
            var parametersString = string.Join("&", parameters.Select(x => $"{Uri.EscapeDataString(x.Key)}={Uri.EscapeDataString(x.Value)}"));

            string signatureBaseString = $"{urlString}&{Uri.EscapeDataString(parametersString)}";
            string signatureKey        = $"{Uri.EscapeDataString(clientSecret)}&{Uri.EscapeDataString(tokenSecret)}";
            var    hmacsha1            = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(signatureKey));


            string signatureString = Convert.ToBase64String(hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString)));

            return(signatureString);
        }
        private static string GetPassword(IDictionary <string, string> values)
        {
            if (!values.TryGetValue(nameof(IConnectionSettingValues.Password), out var password) || string.IsNullOrEmpty(password))
            {
                return(null);
            }

            var client = GetClient(values);

            if (string.IsNullOrEmpty(client))
            {
                return(null);
            }

            using (var encipher = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(password)))
            {
                var data = Encoding.UTF8.GetBytes(client);
                return(Convert.ToBase64String(encipher.ComputeHash(data)));
            }
        }
Ejemplo n.º 27
0
        private static string GetSha1Hash(string text)
        {
            var sha1 = new System.Security.Cryptography.HMACSHA1();

            string result = null;

            var arrayData   = Encoding.ASCII.GetBytes(text);
            var arrayResult = sha1.ComputeHash(arrayData);

            foreach (var t in arrayResult)
            {
                var temp = Convert.ToString(t, 16);
                if (temp.Length == 1)
                {
                    temp = string.Format("0{0}", temp);
                }
                result += temp;
            }
            return(result);
        }
Ejemplo n.º 28
0
        private string GenerateSignature(string key, string content)
        {
            Ensure.That(key).IsNotNullOrEmpty();
            Ensure.That(content).IsNotNullOrEmpty();

            var hmac = new System.Security.Cryptography.HMACSHA1
            {
                Key = Encoding.UTF8.GetBytes(key)
            };

            try
            {
                var signature = hmac.ComputeHash(Encoding.UTF8.GetBytes(content));

                return(Convert.ToBase64String(signature));
            }
            catch (Exception ex)             //TODO: Catch Specific Exception
            {
                throw ex;
            }
        }
Ejemplo n.º 29
0
        private string Encrypt(string passwordSalt, string clearPassword)
        {
            try
            {
                string returnValue = string.Empty;

                passwordSalt  = GetHexString(passwordSalt);
                clearPassword = GetHexString(clearPassword);

                System.Security.Cryptography.HMACSHA1 hash = new System.Security.Cryptography.HMACSHA1();

                byte[] returnBytes = new byte[passwordSalt.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                {
                    returnBytes[i] = Convert.ToByte(passwordSalt.Substring(i * 2, 2), 16);
                }
                hash.Key = returnBytes;

                string encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(clearPassword)));

                string        newPassword = string.Format("{0}{1}", passwordSalt, encodedPassword);
                byte[]        bytes       = Encoding.UTF8.GetBytes(newPassword);
                StringBuilder sb          = new StringBuilder();
                foreach (byte bt in bytes)
                {
                    sb.AppendFormat("{0:x2}", bt);
                }
                returnValue = sb.ToString();
                return(returnValue);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    throw e.InnerException;
                }

                throw e;
            }
        }
Ejemplo n.º 30
0
        public string GetResult(String accessKeySecret, string httpMethod, IDictionary <string, string> allQuerys)
        {
            var querys = new List <string>();
            var sb     = new StringBuilder();

            sb.Append(System.Web.HttpUtility.UrlEncode("/").ToUpper());
            sb.Append("&");
            sb.Append(UrlEncode(String.Join("&", allQuerys.OrderBy(q => q.Key, StringComparer.Ordinal).Select(q => String.Format("{0}={1}", q.Key, UrlEncode(q.Value))))));

            var encodeQuerys = sb.ToString();

            sb = new StringBuilder();
            sb.Append(httpMethod.ToUpper());
            sb.Append("&");
            sb.Append(encodeQuerys);

            using (var sh1 = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(accessKeySecret + "&")))
            {
                var result = Convert.ToBase64String(sh1.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString())));
                return(result);
            }
        }
Ejemplo n.º 31
0
        private string CreateSignature(string consumerSecret, string tokenSecret, string method, Uri uri, IDictionary <string, string> oauthParams)
        {
            //パラメタをソート済みディクショナリに詰替(OAuthの仕様)
            SortedDictionary <string, string> sorted = new SortedDictionary <string, string>(oauthParams);
            //URLエンコード済みのクエリ形式文字列に変換
            string paramString = CreateQueryString(sorted);
            //アクセス先URLの整形
            string url = string.Format("{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath);
            //署名のベース文字列生成(&区切り)。クエリ形式文字列は再エンコードする
            string signatureBase = string.Format("{0}&{1}&{2}", method, UrlEncode(url), UrlEncode(paramString));
            //署名鍵の文字列をコンシューマー秘密鍵とアクセストークン秘密鍵から生成(&区切り。アクセストークン秘密鍵なくても&残すこと)
            string key = UrlEncode(consumerSecret) + "&";

            if (!string.IsNullOrEmpty(tokenSecret))
            {
                key += UrlEncode(tokenSecret);
            }
            //鍵生成&署名生成
            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(Encoding.ASCII.GetBytes(key));
            byte[] hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));
            return(Convert.ToBase64String(hash));
        }
Ejemplo n.º 32
0
        public App()
        {
            UnhandledException += Application_UnhandledException;

            InitializeComponent();

            InitializePhoneApplication();

            InitializeLanguage();


            // initialize computehash function
            OAuthUtility.ComputeHash = (key, buffer) => { using (var hmac = new System.Security.Cryptography.HMACSHA1(key)) { return hmac.ComputeHash(buffer); } };

            if (Debugger.IsAttached)
            {
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

        }
        /// <summary>
        /// Calculates the signature for an OAuth call.
        /// </summary>
        /// <param name="method">POST or GET method.</param>
        /// <param name="url">The URL the request will be sent to.</param>
        /// <param name="parameters">Parameters to be added to the signature.</param>
        /// <param name="tokenSecret">The token secret (either request or access) for generating the SHA-1 key.</param>
        /// <returns>Base64 encoded SHA-1 hash.</returns>
        public string OAuthCalculateSignature(string method, string url, Dictionary <string, string> parameters, string oAuthAccessTokenSecret)
        {
            string baseString = "";
            string key        = ApiSecret + "&" + oAuthAccessTokenSecret;

            byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(key);

            SortedList <string, string> sorted = parameters.ToSortedList();

            StringBuilder sb = new StringBuilder();

            foreach (KeyValuePair <string, string> pair in sorted)
            {
                sb.Append(pair.Key);
                sb.Append("=");
                sb.Append(pair.Value.ToEscapeOAuth());
                sb.Append("&");
            }

            //remove last &
            sb.Remove(sb.Length - 1, 1);

            baseString = method + "&" + url.ToEscapeOAuth() + "&" + sb.ToString().ToEscapeOAuth();

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(keyBytes);

            byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.UTF8.GetBytes(baseString));

            string hash = Convert.ToBase64String(hashBytes);

            //Debug.WriteLine("key  = " + key);
            //Debug.WriteLine("base = " + baseString);
            //Debug.WriteLine("sig  = " + hash);

            return(hash);
        }
Ejemplo n.º 34
0
        /// <summary>
        /// OAuth認証ヘッダの署名作成
        /// </summary>
        /// <param name="tokenSecret">アクセストークン秘密鍵</param>
        /// <param name="method">HTTPメソッド文字列</param>
        /// <param name="uri">アクセス先Uri</param>
        /// <param name="parameter">クエリ、もしくはPOSTデータ</param>
        /// <returns>署名文字列</returns>
        protected virtual string CreateSignature(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, this.UrlEncode(url), this.UrlEncode(paramString));
            // 署名鍵の文字列をコンシューマー秘密鍵とアクセストークン秘密鍵から生成(&区切り。アクセストークン秘密鍵なくても&残すこと)
            string key = this.UrlEncode(this.consumerSecret) + "&";

            if (!string.IsNullOrEmpty(tokenSecret))
            {
                key += this.UrlEncode(tokenSecret);
            }
            // 鍵生成&署名生成
            using (HMACSHA1 hmac = new HMACSHA1(Encoding.ASCII.GetBytes(key)))
            {
                byte[] hash = hmac.ComputeHash(Encoding.ASCII.GetBytes(signatureBase));
                return(Convert.ToBase64String(hash));
            }
        }
Ejemplo n.º 35
0
        //public int Api调用次数 { get; private set; }
        #endregion 公共属性
        #region 私有方法
        /// <summary>
        /// 获得授权签名
        /// </summary>
        /// <param name="urlPath">基础url部分,格式为protocol/apiVersion/namespace/apiName/appKey,如 json/1/system/currentTime/1;如果为客户端授权时此参数置为空串""</param>
        /// <param name="paramDic">请求参数,即queryString + request body 中的所有参数</param>
        /// <param name="isAppKey">是否需要传入AppKey</param>
        /// <returns></returns>
        private string Sign(string urlPath, Dictionary <string, object> paramDic, bool isAppKey = false)
        {
            if (isAppKey)
            {
                urlPath += "/" + this.AppKey;
            }
            byte[]        signatureKey = Encoding.UTF8.GetBytes(this.AppSecret);//此处用自己的签名密钥
            List <string> list         = new List <string>();

            foreach (KeyValuePair <string, object> kv in paramDic)
            {
                list.Add(kv.Key + System.Web.HttpUtility.UrlDecode(Convert.ToString(kv.Value)));
                //list.Add(kv.Key + HttpUtility.UrlDecode(kv.Value));
            }
            list.Sort();
            string tmp = urlPath;

            foreach (string kvstr in list)
            {
                tmp = tmp + kvstr;
            }
            //HMAC-SHA1
            System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(signatureKey);
            hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(tmp));

            /*
             * hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(urlPath));
             * foreach (string kvstr in list)
             * {
             *  hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(kvstr));
             * }
             */
            byte[] hash = hmacsha1.Hash;
            //TO HEX
            return(BitConverter.ToString(hash).Replace("-", string.Empty).ToUpper());
        }
Ejemplo n.º 36
0
        /// <summary>
        /// 计算签名
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        private void ComputeSignature(Context ctx)
        {
            var keys   = ctx.Parameters.Keys.ToList();
            var values = new System.Text.StringBuilder();

            keys.Sort(delegate(String small, String big) { return(string.Compare(small, big, StringComparison.Ordinal)); });
            foreach (var key in keys)
            {
                if (!string.IsNullOrEmpty(ctx.Parameters[key]))
                {
                    if (values.Length > 0)
                    {
                        values.Append("&");
                    }
                    values.Append(key + "=" + strUtil.UrlEncode(ctx.Parameters[key]));
                }
            }
            var text      = ctx.Method.ToString() + "&%2F&" + strUtil.UrlEncode(values.ToString());
            var hmac      = new System.Security.Cryptography.HMACSHA1(System.Text.Encoding.ASCII.GetBytes(ctx.KeySecret + "&"));
            var hashValue = hmac.ComputeHash(System.Text.Encoding.ASCII.GetBytes(text));
            var signature = System.Convert.ToBase64String(hashValue);

            ctx.Parameters.Add("Signature", signature);
        }
Ejemplo n.º 37
0
        public static string SignRequestUrl(string url)
        {
            if (!url.Contains('?'))
            {
                url += '?';
            }
            else
            {
                url += '&';
            }

            url += "appSID=" + APP_SID;

            byte[] key = System.Text.Encoding.UTF8.GetBytes(APP_KEY);
            System.Security.Cryptography.HMACSHA1 algorithm = new System.Security.Cryptography.HMACSHA1(key);
            byte[] sequence  = System.Text.ASCIIEncoding.ASCII.GetBytes(url);
            byte[] hash      = algorithm.ComputeHash(sequence);
            string signature = System.Convert.ToBase64String(hash);

            signature = signature.TrimEnd('=');
            url      += "&signature=" + signature;

            return(url);
        }
Ejemplo n.º 38
0
        public void DecodeURL()
        {
            //Setup required variables - ENTER YOUR OWN HERE
            string baseUrl   = "https://us-api.mimecast.com";
            string uri       = "/api/ttp/url/decode-url";
            string accessKey = "";
            string secretKey = "";
            string appId     = "";
            string appKey    = "";

            //Code borrowed from Mimecast's API Documentation with modifications to work with this application
            //Generate request header values
            string hdrDate   = System.DateTime.Now.ToUniversalTime().ToString("R");
            string requestId = System.Guid.NewGuid().ToString();

            //Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
            System.Security.Cryptography.HMAC h = new System.Security.Cryptography.HMACSHA1(System.Convert.FromBase64String(secretKey));

            //Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
            byte[] hash = h.ComputeHash(System.Text.Encoding.Default.GetBytes(hdrDate + ":" + requestId + ":" + uri + ":" + appKey));

            //Build the signature to be included in the Authorization header in your request
            string signature = "MC " + accessKey + ":" + System.Convert.ToBase64String(hash);

            //Build Request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseUrl + uri);
            request.Method      = "POST";
            request.ContentType = "application/json";

            //Add Headers
            request.Headers[System.Net.HttpRequestHeader.Authorization] = signature;
            request.Headers.Add("x-mc-date", hdrDate);
            request.Headers.Add("x-mc-req-id", requestId);
            request.Headers.Add("x-mc-app-id", appId);

            //Add request body
            //Create and write data to stream
            string postData = "{\"data\": [{\"url\": \"" + tb_url2decode.Text + "\"}]}";

            byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

            System.IO.Stream stream = request.GetRequestStream();
            stream.Write(payload, 0, payload.Length);
            stream.Close();

            //Send Request
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

            //Output response to console
            System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
            string responseBody           = "";
            string temp = null;

            while ((temp = reader.ReadLine()) != null)
            {
                responseBody += temp;
            }
            ;

            //json parsing variables - this will retrieve the meta and failure messages to confirm successful entries from Mimecast's API
            var jsonDoc         = JsonDocument.Parse(responseBody);
            var root            = jsonDoc.RootElement;
            var entrystatus     = root.GetProperty("meta");
            var entryfailstatus = root.GetProperty("fail");
            var urlholder1      = root.GetProperty("data");

            //string manipulation to extrapolate the decoded URL - could have used a class for json deserialization - next version will include this
            string urlholder2 = urlholder1.ToString();
            string decodedurl = urlholder2.Substring((9));


            //error handling and updating status if status is 200 and no failures this means the URL was decoded successfully, if not it confirms status ok but there were failures
            if (entrystatus.ToString() == "{\"status\":200}")
            {
                if (entryfailstatus.ToString() == "[]")
                {
                    tb_decodedurl.Text = (decodedurl.Split('\"')[0]);
                    status.Text        = ("URL decoded successfully!");
                }
                else
                {
                    tb_decodedurl.Text = ("Status OK but failures present!");
                    status.Text        = ("Status OK but failures present!");
                }
            }
            else
            {
                tb_decodedurl.Text = ("Could not decode URL, status failed!");
                status.Text        = ("Could not decode URL, status failed!");
            }
        }
Ejemplo n.º 39
0
        protected void decode(int stanzaSize, bool useDecrypt)
        {
            int size = stanzaSize;
            byte[] data = new byte[size];
            byte[] dataReal = null;
            Buffer.BlockCopy(this.buffer.ToArray(), 0, data, 0, size);

            byte[] packet = new byte[size - 4];

            byte[] hashServerByte = new byte[4];
            Buffer.BlockCopy(data, 0, hashServerByte, 0, 4);
            Buffer.BlockCopy(data, 4, packet, 0, size - 4);

            System.Security.Cryptography.HMACSHA1 h = new System.Security.Cryptography.HMACSHA1(this.Encryptionkey);
            byte[] hashByte = new byte[4];
            Buffer.BlockCopy(h.ComputeHash(packet, 0, packet.Length), 0, hashByte, 0, 4);

            if (hashServerByte.SequenceEqual(hashByte))
            {
                this.buffer.RemoveRange(0, 4);
                if (useDecrypt)
                {
                    dataReal = Encryption.WhatsappDecrypt(this.Encryptionkey, packet);
                }
                else
                {
                    dataReal = Encryption.WhatsappEncrypt(this.Encryptionkey, packet, true);
                    //dataReal = new byte[foo.Length - 4];
                    //Buffer.BlockCopy(foo, 0, dataReal, 0, dataReal.Length);
                }

                for (int i = 0; i < size - 4; i++)
                {
                    this.buffer[i] = dataReal[i];
                }
            }
            else
            {
                throw new Exception("Hash doesnt match");
            }
        }
Ejemplo n.º 40
0
        public byte[] Encode(byte[] key, byte[] buffer)
        {
            var hmac = new System.Security.Cryptography.HMACSHA1(key);

            return(hmac.ComputeHash(buffer));
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Generate a Totp using provided binary data.
        /// </summary>
        /// <param name="key">Binary data.</param>
        /// <returns>Time-based One Time Password.</returns>
        public string Generate(byte[] key)
        {
            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true); //Instanciates a new hash provider with a key.
            byte[] hash = hmac.ComputeHash(GetBytes((ulong)Counter)); //Generates hash from key using counter.
            hmac.Clear(); //Clear hash instance securing the key.

            int offset = hash[hash.Length - 1] & 0xf;           //Math.
            int binary =                                        //Math.
                ((hash[offset] & 0x7f) << 24)                   //Math.
                | ((hash[offset + 1] & 0xff) << 16)             //Math.
                | ((hash[offset + 2] & 0xff) << 8)              //Math.
                | (hash[offset + 3] & 0xff);                    //Math.

            int password = binary % (int)Math.Pow(10, _Length); //Math.
            return password.ToString(new string('0', _Length)); //Math.
        }
Ejemplo n.º 42
0
        private static string Sign(string content, string signKey)
        {
#if NETFX_CORE
            Windows.Security.Cryptography.Core.MacAlgorithmProvider HmacSha1Provider = Windows.Security.Cryptography.Core.MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
            var keyMaterial = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(signKey, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
            var hmacSha1Provider = Windows.Security.Cryptography.Core.MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
            var macKey = HmacSha1Provider.CreateKey(keyMaterial);
            var dataToBeSigned = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(content, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
            var signatureBuffer = Windows.Security.Cryptography.Core.CryptographicEngine.Sign(macKey, dataToBeSigned);
            var result = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(signatureBuffer);
#else
            var data = Encoding.UTF8.GetBytes(content);
            var signKeyBytes = Encoding.UTF8.GetBytes(signKey);
            var algorithm = new System.Security.Cryptography.HMACSHA1(signKeyBytes);
            var result = Convert.ToBase64String(algorithm.ComputeHash(data));
#endif
            return result;
        }
Ejemplo n.º 43
0
        string SignString( string toSign, string withKey )
        {
            // sign parameter string
            byte[] sigBase = UTF8Encoding.UTF8.GetBytes ( toSign );
            MemoryStream ms = new MemoryStream();
            ms.Write (sigBase, 0, sigBase.Length );

            byte[] key = UTF8Encoding.UTF8.GetBytes ( withKey );
            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1( key );
            byte[] hashBytes = sha1.ComputeHash ( sigBase );
            return System.Convert.ToBase64String( hashBytes );
        }
Ejemplo n.º 44
0
 /// <summary>
 /// OAuth認証ヘッダの署名作成
 /// </summary>
 /// <param name="tokenSecret">アクセストークン秘密鍵</param>
 /// <param name="method">HTTPメソッド文字列</param>
 /// <param name="uri">アクセス先Uri</param>
 /// <param name="parameter">クエリ、もしくはPOSTデータ</param>
 /// <returns>署名文字列</returns>
 protected virtual string CreateSignature( string tokenSecret, string method, Uri uri, Dictionary< string, string > parameter )
 {
     // パラメタをソート済みディクショナリに詰替(OAuthの仕様)
     SortedDictionary< string, string > sorted = new SortedDictionary< string, string >( parameter );
     // URLエンコード済みのクエリ形式文字列に変換
     string paramString = this.CreateQueryString( sorted );
     // アクセス先URLの整形
     string url = string.Format( "{0}://{1}{2}", uri.Scheme, uri.Host, uri.AbsolutePath );
     // 署名のベース文字列生成(&区切り)。クエリ形式文字列は再エンコードする
     string signatureBase = string.Format( "{0}&{1}&{2}", method, this.UrlEncode( url ), this.UrlEncode( paramString ) );
     // 署名鍵の文字列をコンシューマー秘密鍵とアクセストークン秘密鍵から生成(&区切り。アクセストークン秘密鍵なくても&残すこと)
     string key = this.UrlEncode( this.consumerSecret ) + "&";
     if ( !string.IsNullOrEmpty( tokenSecret ) )
         key += this.UrlEncode( tokenSecret );
     // 鍵生成&署名生成
     using ( HMACSHA1 hmac = new HMACSHA1( Encoding.ASCII.GetBytes( key ) ) )
     {
         byte[] hash = hmac.ComputeHash( Encoding.ASCII.GetBytes( signatureBase ) );
         return Convert.ToBase64String( hash );
     }
 }
Ejemplo n.º 45
0
        public static HttpWebRequest AddOAuth(this HttpWebRequest req, string pData, string ConsumerKey, string ConsumerSecret, string AccessToken, string AccessTokenSecret)
        {
            string nonce = new Random().Next(Int16.MaxValue, Int32.MaxValue).ToString("X", System.Globalization.CultureInfo.InvariantCulture);
            string timeStamp = DateTime.UtcNow.ToUnixTimeStamp().ToString();

            // Create the base string. This is the string that will be hashed for the signature.
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("oauth_consumer_key", ConsumerKey);
            param.Add("oauth_nonce", nonce);
            param.Add("oauth_signature_method", "HMAC-SHA1");
            param.Add("oauth_timestamp", timeStamp);
            if (!string.IsNullOrEmpty(AccessToken))
                param.Add("oauth_token", AccessToken);
            param.Add("oauth_version", "1.0");

            pData += req.RequestUri.Query;

            foreach (string kv in pData.Replace("?", "&").Split('&'))
            {
                string[] akv = kv.Split('=');
                if (akv.Length == 2)
                {
                    param.Add(akv[0], akv[1].PercentDecode());
                }
            }

            StringBuilder sParam = new StringBuilder(); ;
            foreach (KeyValuePair<string, string> p in param.OrderBy(k => k.Key))
            {
                if (sParam.Length > 0)
                    sParam.Append("&");

                sParam.AppendFormat("{0}={1}", p.Key.PercentEncode(), p.Value.PercentEncode());
            }

            string url = req.RequestUri.AbsoluteUri;
            if (!string.IsNullOrEmpty(req.RequestUri.Query))
            {
                url = url.Replace(req.RequestUri.Query, "");
            }

            string signatureBaseString
                = string.Format("{0}&{1}&{2}",
                req.Method.ToUpper(),
                url.PercentEncode(),
                sParam.ToString().PercentEncode()
            );

            // Create our hash key (you might say this is a password)
            string signatureKey = string.Format("{0}&{1}", ConsumerSecret.PercentEncode(), AccessTokenSecret.PercentEncode());

            // Generate the hash
            System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(signatureKey));
            byte[] signatureBytes = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString));

            string signature = Convert.ToBase64String(signatureBytes).PercentEncode();

            string at = string.IsNullOrEmpty(AccessToken) ? "" : string.Format("oauth_token=\"{0}\",", AccessToken);
            string oauth = "OAuth realm=\"{0}\",oauth_consumer_key=\"{1}\",oauth_nonce=\"{2}\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"{3}\",{4}oauth_version=\"1.0\",oauth_signature=\"{5}\"";
            oauth = string.Format(oauth, "Spiral16", ConsumerKey, nonce, timeStamp, at, signature);

            req.Headers.Add("Authorization", oauth);
            req.ContentType = "application/x-www-form-urlencoded";

            return req;
        }
Ejemplo n.º 46
0
        public void ComputeHMACShortTermCredentials(STUNMessage msgWithoutHMAC, int nLengthWithoutMessageIntegrity, string strPassword)
        {
            if (strPassword == null)
                strPassword = "";

            /// No MD5 on short term credentials
            byte[] bKey = System.Text.UTF8Encoding.UTF8.GetBytes(strPassword);

            byte[] bBytes = msgWithoutHMAC.Bytes;

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(bKey);
            HMAC = sha1.ComputeHash(bBytes, 0, nLengthWithoutMessageIntegrity);
        }
Ejemplo n.º 47
0
        public void ComputeHMACShortTermCredentials(byte [] bMsgBytes, int nLengthWithoutMessageIntegrity, string strPassword)
        {
            byte[] bKey = System.Text.UTF8Encoding.UTF8.GetBytes(strPassword);

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(bKey);
            HMAC = sha1.ComputeHash(bMsgBytes, 0, nLengthWithoutMessageIntegrity);
        }
Ejemplo n.º 48
0
        public void ComputeHMACLongTermCredentials(STUNMessage msgWithoutHMAC, int nLengthWithoutMessageIntegrity, string strUserName, string strRealm, string strPassword)
        {
            string strKey = string.Format("{0}:{1}:{2}", strUserName, strRealm, strPassword);
            System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();

            byte[] bKey = md5.ComputeHash(System.Text.UTF8Encoding.UTF8.GetBytes(strKey));

            byte[] bBytes = msgWithoutHMAC.Bytes;

            System.Security.Cryptography.HMACSHA1 sha1 = new System.Security.Cryptography.HMACSHA1(bKey);
            HMAC = sha1.ComputeHash(bBytes, 0, nLengthWithoutMessageIntegrity);
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Signs the specified data (in string format) with HMAC-SHA1 algorithm and the specified <paramref name="signKey"/>.
        /// </summary>
        /// <param name="data">The data to be signed.</param>
        /// <param name="signKey">The sign key.</param>
        /// <returns>The base64 format signature string.</returns>
        private static string Sign(string data, string signKey)
        {
            var dataBytes = Encoding.ASCII.GetBytes(data);
            var signKeyBytes = Encoding.ASCII.GetBytes(signKey);

            var algorithm = new System.Security.Cryptography.HMACSHA1(signKeyBytes);
            var result = Convert.ToBase64String(algorithm.ComputeHash(dataBytes));

            return result;
        }
Ejemplo n.º 50
0
        public static HttpWebRequest AddOAuth(this HttpWebRequest req, string pData, string ConsumerKey, string ConsumerSecret, string AccessToken, string AccessTokenSecret)
        {
            string nonce     = new Random().Next(Int16.MaxValue, Int32.MaxValue).ToString("X", System.Globalization.CultureInfo.InvariantCulture);
            string timeStamp = DateTime.UtcNow.ToUnixTimeStamp().ToString();

            // Create the base string. This is the string that will be hashed for the signature.
            Dictionary <string, string> param = new Dictionary <string, string>();

            param.Add("oauth_consumer_key", ConsumerKey);
            param.Add("oauth_nonce", nonce);
            param.Add("oauth_signature_method", "HMAC-SHA1");
            param.Add("oauth_timestamp", timeStamp);
            if (!string.IsNullOrEmpty(AccessToken))
            {
                param.Add("oauth_token", AccessToken);
            }
            param.Add("oauth_version", "1.0");

            pData += req.RequestUri.Query;

            foreach (string kv in pData.Replace("?", "&").Split('&'))
            {
                string[] akv = kv.Split('=');
                if (akv.Length == 2)
                {
                    param.Add(akv[0], akv[1].PercentDecode());
                }
            }

            StringBuilder sParam = new StringBuilder();;

            foreach (KeyValuePair <string, string> p in param.OrderBy(k => k.Key))
            {
                if (sParam.Length > 0)
                {
                    sParam.Append("&");
                }

                sParam.AppendFormat("{0}={1}", p.Key.PercentEncode(), p.Value.PercentEncode());
            }

            string url = req.RequestUri.AbsoluteUri;

            if (!string.IsNullOrEmpty(req.RequestUri.Query))
            {
                url = url.Replace(req.RequestUri.Query, "");
            }

            string signatureBaseString
                = string.Format("{0}&{1}&{2}",
                                req.Method.ToUpper(),
                                url.PercentEncode(),
                                sParam.ToString().PercentEncode()
                                );


            // Create our hash key (you might say this is a password)
            string signatureKey = string.Format("{0}&{1}", ConsumerSecret.PercentEncode(), AccessTokenSecret.PercentEncode());


            // Generate the hash
            System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(Encoding.UTF8.GetBytes(signatureKey));
            byte[] signatureBytes = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBaseString));

            string signature = Convert.ToBase64String(signatureBytes).PercentEncode();

            string at    = string.IsNullOrEmpty(AccessToken) ? "" : string.Format("oauth_token=\"{0}\",", AccessToken);
            string oauth = "OAuth realm=\"{0}\",oauth_consumer_key=\"{1}\",oauth_nonce=\"{2}\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"{3}\",{4}oauth_version=\"1.0\",oauth_signature=\"{5}\"";

            oauth = string.Format(oauth, "Spiral16", ConsumerKey, nonce, timeStamp, at, signature);

            req.Headers.Add("Authorization", oauth);
            req.ContentType = "application/x-www-form-urlencoded";

            return(req);
        }
Ejemplo n.º 51
0
 public byte[] ComputeHash(byte[] data, int offset, int length)
 {
     _algorithm.Initialize();
     return(_algorithm.ComputeHash(data, offset, length));
 }
Ejemplo n.º 52
0
        Response GetCredentials(string resource_url)
        {
            // unique request details
            var oauth_nonce = Convert.ToBase64String(
                new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));

            var timeSpan        = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

            string baseString = null;


            string baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                                "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";


            baseString = string.Format(baseFormat,
                                       oauth_consumer_key,
                                       oauth_nonce,
                                       oauth_signature_method,
                                       oauth_timestamp,
                                       oauth_token,
                                       oauth_version
                                       );



            baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

            var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                             "&", Uri.EscapeDataString(oauth_token_secret));

            string oauth_signature;

            using (System.Security.Cryptography.HMACSHA1 hasher = new System.Security.Cryptography.HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
            {
                oauth_signature = Convert.ToBase64String(
                    hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
            }

            string authHeader = null;


            // create the request header
            var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " +
                               "oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", " +
                               "oauth_timestamp=\"{4}\", oauth_token=\"{5}\", " +
                               "oauth_version=\"{6}\"";

            authHeader = string.Format(headerFormat,
                                       Uri.EscapeDataString(oauth_consumer_key),
                                       Uri.EscapeDataString(oauth_nonce),
                                       Uri.EscapeDataString(oauth_signature),
                                       Uri.EscapeDataString(oauth_signature_method),
                                       Uri.EscapeDataString(oauth_timestamp),
                                       Uri.EscapeDataString(oauth_token),
                                       Uri.EscapeDataString(oauth_version)
                                       );


            HttpWebRequest request = null;


            request = (HttpWebRequest)WebRequest.Create(resource_url);
            request.Headers.Add("Authorization", authHeader);
            request.Method = "GET";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            ServicePointManager.Expect100Continue = false;
            request.KeepAlive = true;

            Response respon = new Response();

            try
            {
                var response = (HttpWebResponse)request.GetResponse();

                using (var reader = new System.IO.StreamReader(response.GetResponseStream(), ASCIIEncoding.ASCII))
                {
                    string responseText = reader.ReadToEnd();

                    respon.Text = responseText;
                }
            }
            catch (Exception ex)
            {
                respon.Failed = true;
                respon.Text   = ex.Message;
            }

            return(respon);
        }
        private static byte[] GetHMAC(byte[] key, byte[] counter)
        {
            System.Security.Cryptography.HMACSHA1 hmac = new System.Security.Cryptography.HMACSHA1(key, true);

            return hmac.ComputeHash(counter);
        }
Ejemplo n.º 54
0
        HttpWebRequest GetStreamRequest()
        {
            HttpWebRequest request      = null;
            string         resource_url = "https://userstream.twitter.com/1.1/user.json";

            // unique request details
            var oauth_nonce = Convert.ToBase64String(
                new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));

            var timeSpan        = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

            string baseString = null;

            string baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                                "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";


            baseString = string.Format(baseFormat,
                                       oauth_consumer_key,
                                       oauth_nonce,
                                       oauth_signature_method,
                                       oauth_timestamp,
                                       oauth_token,
                                       oauth_version
                                       );



            baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

            var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                             "&", Uri.EscapeDataString(oauth_token_secret));

            string oauth_signature;

            using (System.Security.Cryptography.HMACSHA1 hasher = new System.Security.Cryptography.HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
            {
                oauth_signature = Convert.ToBase64String(
                    hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
            }

            string authHeader = null;

            // create the request header
            var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " +
                               "oauth_signature_method=\"{2}\", oauth_timestamp=\"{3}\", " +
                               "oauth_token=\"{4}\", oauth_version=\"{5}\", " +
                               "oauth_signature=\"{6}\"";

            authHeader = string.Format(headerFormat,
                                       Uri.EscapeDataString(oauth_consumer_key),
                                       Uri.EscapeDataString(oauth_nonce),
                                       Uri.EscapeDataString(oauth_signature_method),
                                       Uri.EscapeDataString(oauth_timestamp),
                                       Uri.EscapeDataString(oauth_token),
                                       Uri.EscapeDataString(oauth_version),
                                       Uri.EscapeDataString(oauth_signature)
                                       );

            request = (HttpWebRequest)WebRequest.Create(resource_url);

            request.Proxy = null;

            request.Headers.Add("Authorization", authHeader);
            request.Method = "POST";

            ServicePointManager.Expect100Continue = false;

            request.ContentType = "application/x-www-form-urlencoded";


            return(request);
        }
Ejemplo n.º 55
0
        public WebResponse SendRequest(String twitterSreenName)
        {
            try
            {
                var oauth_token = "1594158649-FN2fYJKW8aLJopq81cD0HZbUylDtpmIVbOU9KJR";
                var oauth_token_secret = "0t14X8BvUJmyCu5loN5itfH97QejFjzS0xDTaptu8";
                var oauth_consumer_key = "ui7oDxGwLbcoPzQmUuA";
                var oauth_consumer_secret = "Xe68RKvQ77NpXbmcGvUTvcScLT2wWQTFxrp6ckxUzM";

                var oauth_version = "1.0";
                var oauth_signature_method = "HMAC-SHA1";
                var oauth_nonce = Convert.ToBase64String(
                                                  new System.Text.ASCIIEncoding().GetBytes(
                                                       DateTime.Now.Ticks.ToString()));
                var timeSpan = DateTime.UtcNow
                                                  - new DateTime(1970, 1, 1, 0, 0, 0, 0,
                                                       DateTimeKind.Utc);
                var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
                //var slug = "libraries-and-news-sites";
                var owner_screen_name = twitterSreenName;
                var resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
                var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                     "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";

                var baseString = string.Format(baseFormat,
                                            oauth_consumer_key,
                                            oauth_nonce,
                                            oauth_signature_method,
                                            oauth_timestamp,
                                            oauth_token,
                                            oauth_version,
                                            Uri.EscapeDataString(owner_screen_name)

                                            );

                baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url),
                             "&", Uri.EscapeDataString(baseString));

                var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                        "&", Uri.EscapeDataString(oauth_token_secret));

                string oauth_signature;
                using (System.Security.Cryptography.HMACSHA1 hasher = new System.Security.Cryptography.HMACSHA1(System.Text.ASCIIEncoding.ASCII.GetBytes(compositeKey)))
                {
                    oauth_signature = Convert.ToBase64String(
                        hasher.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(baseString)));
                }

                var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", oauth_timestamp=\"{4}\", oauth_token=\"{5}\", oauth_version=\"{6}\"";

                var authHeader = string.Format(headerFormat,
                                        Uri.EscapeDataString(oauth_consumer_key),
                                        Uri.EscapeDataString(oauth_nonce),
                                        Uri.EscapeDataString(oauth_signature),
                                        Uri.EscapeDataString(oauth_signature_method),
                                        Uri.EscapeDataString(oauth_timestamp),
                                        Uri.EscapeDataString(oauth_token),
                                        Uri.EscapeDataString(oauth_version)
                                );

                ServicePointManager.Expect100Continue = false;

                var getBody = "?screen_name=" + Uri.EscapeDataString(owner_screen_name);
                resource_url += getBody;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);

                request.Headers.Add("Authorization", authHeader);
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                WebResponse response = request.GetResponse();
                return response;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 56
0
        Response SendPOSTRequest(Twitt twitt, string resource_url, string media = "", string token = "")
        {
            // unique request details
            var oauth_nonce = Convert.ToBase64String(
                new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));

            var timeSpan        = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();

            string headerMemberName = (token != "") ? "oauth_verifier" : "status";
            var    oauth_token      = (token == "") ? this.oauth_token : token;

            string baseString = null;

            if (twitt.Media == null)
            {
                string baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                                    "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&" + headerMemberName + "={6}";


                baseString = string.Format(baseFormat,
                                           oauth_consumer_key,
                                           oauth_nonce,
                                           oauth_signature_method,
                                           oauth_timestamp,
                                           oauth_token,
                                           oauth_version,
                                           Uri.EscapeDataString(twitt.Text)
                                           );
            }
            else
            {
                // create oauth signature
                var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
                                 "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}";

                baseString = string.Format(baseFormat,
                                           oauth_consumer_key,
                                           oauth_nonce,
                                           oauth_signature_method,
                                           oauth_timestamp,
                                           oauth_token,
                                           oauth_version
                                           );

                if (!string.IsNullOrEmpty(media))
                {
                    baseString = "media_ids=" + Uri.EscapeDataString(media) + "&" + baseString + "&place_id=NoInput&status=" + Uri.EscapeDataString(twitt.Text);
                }
            }


            baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));

            var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                                             "&", Uri.EscapeDataString(oauth_token_secret));

            string oauth_signature;

            using (System.Security.Cryptography.HMACSHA1 hasher = new System.Security.Cryptography.HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
            {
                oauth_signature = Convert.ToBase64String(
                    hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
            }

            string authHeader = null;

            if (twitt.Media == null)
            {
                // create the request header
                var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " +
                                   "oauth_signature_method=\"{2}\", oauth_timestamp=\"{3}\", " +
                                   "oauth_token=\"{4}\", oauth_version=\"{5}\", " +
                                   "oauth_signature=\"{6}\", " + headerMemberName + "=\"{7}\"";

                authHeader = string.Format(headerFormat,
                                           Uri.EscapeDataString(oauth_consumer_key),
                                           Uri.EscapeDataString(oauth_nonce),
                                           Uri.EscapeDataString(oauth_signature_method),
                                           Uri.EscapeDataString(oauth_timestamp),
                                           Uri.EscapeDataString(oauth_token),
                                           Uri.EscapeDataString(oauth_version),
                                           Uri.EscapeDataString(oauth_signature),
                                           Uri.EscapeDataString(twitt.Text)
                                           );

                //if (!string.IsNullOrEmpty(media))
                //    authHeader += $"media_ids=\"{media}\"";
            }
            else
            {
                // create the request header
                var headerFormat = "OAuth oauth_consumer_key=\"{0}\", oauth_nonce=\"{1}\", " +
                                   "oauth_signature=\"{2}\", oauth_signature_method=\"{3}\", " +
                                   "oauth_timestamp=\"{4}\", oauth_token=\"{5}\", " +
                                   "oauth_version=\"{6}\"";

                authHeader = string.Format(headerFormat,
                                           Uri.EscapeDataString(oauth_consumer_key),
                                           Uri.EscapeDataString(oauth_nonce),
                                           Uri.EscapeDataString(oauth_signature),
                                           Uri.EscapeDataString(oauth_signature_method),
                                           Uri.EscapeDataString(oauth_timestamp),
                                           Uri.EscapeDataString(oauth_token),
                                           Uri.EscapeDataString(oauth_version)
                                           );

                //if (!string.IsNullOrEmpty(media))
                //    authHeader = authHeader + ", media_ids=\"" + Uri.EscapeDataString(media) + "\", place_id=\"NoInput\", status=\"" + Uri.EscapeDataString(twitt.Text)+"\"";
            }

            HttpWebRequest request = null;


            if (twitt.Media == null)
            {
                request = (HttpWebRequest)WebRequest.Create(resource_url);
                request.Headers.Add("Authorization", authHeader);
                request.Method = "POST";
                request.Accept = "application/json";

                // make the request
                string postBody = "status=" + Uri.EscapeDataString(twitt.Text);

                ServicePointManager.Expect100Continue = false;

                request.ContentType = "application/x-www-form-urlencoded";
                using (System.IO.Stream stream = request.GetRequestStream())
                {
                    byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
                    stream.Write(content, 0, content.Length);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(media))
                {
                    Encoding EncodingAlgorithm  = Encoding.GetEncoding("iso-8859-1");
                    string   Boundary           = DateTime.Now.Ticks.ToString("x");
                    string   StartBoundary      = string.Format("--{0}\r\n", Boundary);
                    string   EndBoundary        = string.Format("\r\n--{0}--\r\n", Boundary);
                    string   sContentType       = "multipart/form-data;boundary=" + Boundary;
                    string   contentDisposition = "Content-Disposition: form-data; ";
                    string   contenName         = "name=\"media\";\r\n ";
                    string   contentType        = "\r\nContent-Type: application/octet-stream\r\n\r\n";
                    string   Data     = EncodingAlgorithm.GetString(twitt.Media, 0, twitt.Media.Length);
                    var      contents = new System.Text.StringBuilder();
                    contents.Append(String.Format("{0}{1}{2}{3}{4}", StartBoundary, contentDisposition, contenName, contentType, Data));
                    contents.Append(EndBoundary);
                    byte[] Content = EncodingAlgorithm.GetBytes(contents.ToString());

                    request        = (HttpWebRequest)WebRequest.Create(resource_url);
                    request.Method = "POST";
                    request.AllowWriteStreamBuffering = true;
                    request.Headers.Add("Authorization", authHeader);
                    request.ContentType   = sContentType;
                    request.ContentLength = Content.Length;

                    Stream dataStream = request.GetRequestStream();
                    dataStream.Write(Content, 0, Content.Length);
                    dataStream.Close();
                }
                else
                {
                    request                       = (HttpWebRequest)WebRequest.Create(resource_url);
                    request.Method                = "POST";
                    request.Accept                = "application/json";
                    request.ContentType           = "application/x-www-form-urlencoded; charset=utf-8";
                    request.UseDefaultCredentials = true;
                    request.Headers.Add("Authorization", authHeader);
                    request.UserAgent = "LINQ-To-Twitter/3.0";
                    request.Headers.Add("ExpectContinue", "true");
                    request.Headers.Add("CacheControl", "no-cache");
                    request.Date = DateTime.UtcNow;

                    // make the request
                    string postBody = "status=" + Uri.EscapeDataString(twitt.Text) + "&place_id=NoInput&media_ids=" + media;
                    byte[] content  = ASCIIEncoding.UTF8.GetBytes(postBody);

                    request.ContentLength = content.Length;
                    ServicePointManager.Expect100Continue = false;

                    using (System.IO.Stream stream = request.GetRequestStream())
                    {
                        stream.Write(content, 0, content.Length);
                    }
                }
            }

            Dictionary <string, string> responseItems = new Dictionary <string, string>();
            Response res = new Response();

            try
            {
                var response = (HttpWebResponse)request.GetResponse();

                using (var reader = new System.IO.StreamReader(response.GetResponseStream(), ASCIIEncoding.ASCII))
                {
                    string responseText = reader.ReadToEnd();

                    res.Text = responseText;

                    //string[] tokens = responseText.Split(new char[] { '&', '=' });

                    //if (tokens.Length % 2 == 0) // token's response
                    //{
                    //    for (int i = 0; i < tokens.Length; i += 2)
                    //    {
                    //        responseItems[tokens[i]] = tokens[i + 1];
                    //    }
                    //}
                    //else // twitts response
                    //{
                    //    responseItems[twitt.Text] = responseText;

                    //}
                }
            }
            catch (WebException ex)
            {
                var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();

                string error = (string)JObject.Parse(resp).SelectToken("errors[0].message");

                res.Failed = true;
                res.Text   = (error == null)? ex.Message : error;
            }

            return(res);
        }
Ejemplo n.º 57
0
 public static byte[] HMAC_SHA1(byte [] key, byte [] data)
 {
     System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(key);
     return(hmacsha1.ComputeHash(data));
 }
Ejemplo n.º 58
0
 //I have no idea how this works, but it takes the signing key and uses
 //it to create somesort of cryptokey and then applies it to the
 //basestring and then returns the b64 version of it.
 public static string Sign(string signatureBaseString, string signingKey)
 {
     var keyBytes = System.Text.Encoding.ASCII.GetBytes(signingKey);
     using (var myhmacsha1 = new System.Security.Cryptography.HMACSHA1(keyBytes)) {
         byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(signatureBaseString);
         var stream = new MemoryStream(byteArray);
         var signedValue = myhmacsha1.ComputeHash(stream);
         var result = Convert.ToBase64String(signedValue, Base64FormattingOptions.None);
         return result;
     }
 }
Ejemplo n.º 59
0
        public void AddBlockedSite()
        {
            //Setup required variables - ENTER YOUR OWN HERE
            string baseUrl         = "https://us-api.mimecast.com";
            string uri             = "/api/directory/add-group-member";
            string accessKey       = "";
            string secretKey       = "";
            string appId           = "";
            string appKey          = "";
            string blockedsenderid = "";

            //Code borrowed from Mimecast's API Documentation with modifications to work with this application
            //Generate request header values
            string hdrDate   = System.DateTime.Now.ToUniversalTime().ToString("R");
            string requestId = System.Guid.NewGuid().ToString();

            //Create the HMAC SHA1 of the Base64 decoded secret key for the Authorization header
            System.Security.Cryptography.HMAC h = new System.Security.Cryptography.HMACSHA1(System.Convert.FromBase64String(secretKey));

            //Use the HMAC SHA1 value to sign the hdrDate + ":" requestId + ":" + URI + ":" + appkey
            byte[] hash = h.ComputeHash(System.Text.Encoding.Default.GetBytes(hdrDate + ":" + requestId + ":" + uri + ":" + appKey));

            //Build the signature to be included in the Authorization header in your request
            string signature = "MC " + accessKey + ":" + System.Convert.ToBase64String(hash);

            //Build Request
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(baseUrl + uri);
            request.Method      = "POST";
            request.ContentType = "application/json";

            //Add Headers
            request.Headers[System.Net.HttpRequestHeader.Authorization] = signature;
            request.Headers.Add("x-mc-date", hdrDate);
            request.Headers.Add("x-mc-req-id", requestId);
            request.Headers.Add("x-mc-app-id", appId);

            // checks to see if domain or e-mail address is checked
            if ((rb_domain.Checked == false) & (rb_email.Checked == false))
            {
                status.Text = ("Please check domain or e-mail!");
            }
            if (rb_domain.Checked == true)
            {
                status.Text = ("Domain selected.");
                if (CheckDomain(tb_entry.Text))
                {
                    status.Text = ("Domain is valid.");

                    //Add request body
                    //Create and write data to stream
                    string postData = "{\"data\": [{\"id\": \"" + blockedsenderid + "\",\"domain\": \"" + tb_entry.Text + "\"}]}";

                    byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

                    System.IO.Stream stream = request.GetRequestStream();
                    stream.Write(payload, 0, payload.Length);
                    stream.Close();

                    //Send Request
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                    //Output response to console
                    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                    string responseBody           = "";
                    string temp = null;
                    while ((temp = reader.ReadLine()) != null)
                    {
                        responseBody += temp;
                    }
                    ;

                    //json parsing variables - this will retrieve the meta and failure messages to confirm successful entries from Mimecast's API
                    var jsonDoc         = JsonDocument.Parse(responseBody);
                    var root            = jsonDoc.RootElement;
                    var entrystatus     = root.GetProperty("meta");
                    var entryfailstatus = root.GetProperty("fail");

                    //error handling and updating status if status is 200 and no failures this means the site was successfully added, if not it confirms status ok but there were failures
                    if (entrystatus.ToString() == "{\"status\":200}")
                    {
                        if (entryfailstatus.ToString() == "[]")
                        {
                            status.Text = ("Domain added successfully.");
                        }
                        else
                        {
                            status.Text = ("Status OK but failures present!");
                        }
                    }
                    else
                    {
                        status.Text = ("Domain not blocked, status failed.");
                    }
                }
                else
                {
                    status.Text = ("Domain is on free-email list, please recheck!");
                }
            }
            if (rb_email.Checked == true)
            {
                if (ValidateEmail(tb_entry.Text))
                {
                    status.Text = ("Valid e-mail");

                    //Add request body
                    //Create and write data to stream
                    string postData = "{\"data\": [{\"id\": \"" + blockedsenderid + "\",\"emailAddress\": \"" + tb_entry.Text + "\"}]}";

                    byte[] payload = System.Text.Encoding.UTF8.GetBytes(postData);

                    System.IO.Stream stream = request.GetRequestStream();
                    stream.Write(payload, 0, payload.Length);
                    stream.Close();

                    //Send Request
                    System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();

                    //Output response to console
                    System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
                    string responseBody           = "";
                    string temp = null;
                    while ((temp = reader.ReadLine()) != null)
                    {
                        responseBody += temp;
                    }
                    ;

                    //json parsing variables - this will retrieve the meta and failure messages to confirm successful entries
                    var jsonDoc         = JsonDocument.Parse(responseBody);
                    var root            = jsonDoc.RootElement;
                    var entrystatus     = root.GetProperty("meta");
                    var entryfailstatus = root.GetProperty("fail");

                    //error handling and updating status if status is 200 and no failures this means the e-mail was successfully added, if not it confirms status ok but there were failures
                    if (entrystatus.ToString() == "{\"status\":200}")
                    {
                        if (entryfailstatus.ToString() == "[]")
                        {
                            status.Text = ("E-mail address added successfully.");
                        }
                        else
                        {
                            status.Text = ("Status OK but failures present!");
                        }
                    }
                    else
                    {
                        status.Text = ("E-mail address not blocked, status failed.");
                    }
                }
                else
                {
                    status.Text = ("E-mail address entered is not valid!");
                }
            }
        }
Ejemplo n.º 60
0
 public static String Sign(String signatureBaseString, String signingKey)
 {
     Byte[] keyBytes = System.Text.Encoding.ASCII.GetBytes(signingKey);
     using (var myhmacsha1 = new System.Security.Cryptography.HMACSHA1(keyBytes))
     {
         Byte[] byteArray = System.Text.Encoding.ASCII.GetBytes(signatureBaseString);
         Byte[] signedValue = myhmacsha1.ComputeHash(byteArray);//stream);
         return Convert.ToBase64String(signedValue);
     }
 }