Beispiel #1
0
        public void HmacSha256_Does_Not_Accept_Nulls()
        {
            string consumerSecret = "12345678";

            Assert.That(() => OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha256, null, consumerSecret),
                        Throws.TypeOf <ArgumentNullException>());
        }
Beispiel #2
0
        public void HmacSha256_Hashes_Correctly(string value, string expected)
        {
            string consumerSecret = "12345678";
            string actual         = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha256, value, consumerSecret);

            Assert.AreEqual(expected, actual);
        }
Beispiel #3
0
    public OAuthParameters BuildProtectedResourceSignature(string method, WebPairCollection parameters, string url)
    {
        ValidateProtectedResourceState();

        var allParameters = new WebPairCollection();

        allParameters.AddRange(parameters);

        // Include url parameters in query pool
        var uri           = new Uri(url);
        var urlParameters = HttpUtility.ParseQueryString(uri.Query);

        allParameters.AddRange(urlParameters.AllKeys.Select(x => new WebPair(x !, urlParameters[x] !)));

        var timestamp = OAuthTools.GetTimestamp();
        var nonce     = OAuthTools.GetNonce();

        var authParameters = GenerateAuthParameters(timestamp, nonce);

        allParameters.AddRange(authParameters);

        var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, allParameters);

        return(new OAuthParameters {
            Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret),
            Parameters = authParameters
        });
    }
Beispiel #4
0
        private void getCar2GoAccounts(string token, string token_secret, DownloadStringCompletedEventHandler requestCallback)
        {
            var car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/accounts";

            var parameters = new WebParameterCollection();

            parameters.Add("oauth_callback", "oob");
            parameters.Add("oauth_signature_method", "HMAC-SHA1");
            parameters.Add("oauth_token", token);
            parameters.Add("oauth_version", "1.0");
            parameters.Add("oauth_consumer_key", FreeCarsCredentials.Car2Go.ConsumerKey);
            parameters.Add("oauth_timestamp", OAuthTools.GetTimestamp());
            parameters.Add("oauth_nonce", OAuthTools.GetNonce());
            parameters.Add("format", "json");
            parameters.Add("loc", Car2Go.City);
            //parameters.Add("test", "1");
            var signatureBase = OAuthTools.ConcatenateRequestElements("GET", car2GoRequestEndpoint, parameters);
            var signature     = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha1, OAuthSignatureTreatment.Escaped, signatureBase, FreeCarsCredentials.Car2Go.SharedSecred, token_secret);

            var requestParameters = OAuthTools.NormalizeRequestParameters(parameters);
            var requestUrl        = new Uri(car2GoRequestEndpoint + "?" + requestParameters + "&oauth_signature=" + signature, UriKind.Absolute);

            var webClient = new WebClient();

            webClient.DownloadStringCompleted += requestCallback;

            webClient.DownloadStringAsync(requestUrl);
        }
        public void DoesNotThrowForHmacSha1WithoutSupportOfDotNetStandard20()
        {
            void GetHmacSha1Signature() => OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha1,
                                                                   OAuthSignatureTreatment.Escaped, _aStringToSign, _ARsaPemPrivateKey);

            Assert.DoesNotThrow(GetHmacSha1Signature);
        }
Beispiel #6
0
        public void RsaSha1_Signs_Correctly(string value, int keySize)
        {
            //SHA1Managed hasher = new SHA1Managed();
            //SHA1Cng hasher = new SHA1Cng();
            SHA1CryptoServiceProvider hasher = new SHA1CryptoServiceProvider();

            byte[] hash = hasher.ComputeHash(value.GetBytes());

            using (var crypto = new RSACryptoServiceProvider(keySize)
            {
                PersistKeyInCsp = false
            })
            {
                string privateKey = crypto.ToXmlString(true);

                string signature = OAuthTools.GetSignature(
                    OAuthSignatureMethod.RsaSha1,
                    OAuthSignatureTreatment.Unescaped,
                    value,
                    privateKey);

                byte[] signatureBytes = Convert.FromBase64String(signature);

                Assert.IsTrue(crypto.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signatureBytes));
            }
        }
Beispiel #7
0
        public void SignsWithRsaSha1()
        {
            var aStringToSign    = "AStringToSign";
            var rsaPemPrivateKey = @"-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDAJjTl6pZ3/Z2uuJMHa4ZSUdNu20BrQBf0qSVaJBARdS1JAYk+
f2sLDABERsqJBvkkk3++28bW7RtzDuvB3MYIK5TZyKIvcE+Tgev3tjmD1b7XY1qo
8o0ledbDB/S3k2FfyA9oIfjpHYY1g/S+fD9abe69RTh1ds60XHOwxUgI4QIDAQAB
AoGAcZmlCJEqqIIeqV+iPW7KmPybfhzN9xqLjzA5TxOnFEssnM71rydxx7QurC8W
KvEedwtlKReSdRr1cY7Ov2yg/slUEq4fNhjSEkzmdxj9E+2dre235r45yyCU5cod
QkbluvDOJAgfLq+ZBPZLvwKhEZN/iVfi/3jfnbuzyyWPiukCQQDfFhoHCQciQZbl
kNpqs4GFhU1TvxkdKPKkyX0xeh+JPSWo+0cw5yxF2IlifIElxfWGGGupqZCn+nxm
MLUSLIZfAkEA3H+fAo9xicTP3F+9TAZCunT0IsheTj7b/E+vbSQam9eLs+ddzgsg
DNCe1Bhw1NC2cnXxCqX0+EZix9s0uTU4vwJAcZ1O+iBF6tNep2Hjaw4qu7aNEEa1
4pz1HqmjQeyBXSKwKGR4+FXzvUqvhWIFYBh2l6meQ1UhX/t5GY5a2XulnwJBAJ/E
/XO+endoG3FEEgbHNoyid8/IPcUWeRH+r0827OzlJv4pdGf62bNPaval6wPZY4nW
edzMWY+YeLT12eMldEMCQQDP7T/nbOomylhOHlCVgojO/BGkbwdhfwOj4EpE8XDU
D3yw8+j8kSgGSLuydIGPxHq0JYqTVdkIbA+agBZOiNRQ
-----END RSA PRIVATE KEY-----
";
            var rsaSha1Signature = OAuthTools.GetSignature(OAuthSignatureMethod.RsaSha1,
                                                           OAuthSignatureTreatment.Escaped, aStringToSign, rsaPemPrivateKey);

            Assert.AreEqual(
                "bh2Ljy82v5FSD0PQaKDPDwTHolA6JrBfQPciDLTlR0nNodgFja%2Fw7UmLJuxuARNerX7gpKpFxboprGAOaCWZp0D5NiB4%2FrejvyM3u9iLkh9NPhtU0jihny0MYiWlxT6Tg4yiHr%2FQ5d6a1DEZvg8L6m9A6ckb0%2Bn69vkrnDd1zoE%3D",
                rsaSha1Signature);
        }
Beispiel #8
0
            public void SignsWithRsaSha1()
            {
                var rsaSha1Signature = OAuthTools.GetSignature(OAuthSignatureMethod.RsaSha1, OAuthSignatureTreatment.Escaped, _aStringToSign, _rsaPemPrivateKey);

                Assert.AreEqual(
                    "bh2Ljy82v5FSD0PQaKDPDwTHolA6JrBfQPciDLTlR0nNodgFja%2Fw7UmLJuxuARNerX7gpKpFxboprGAOaCWZp0D5NiB4%2FrejvyM3u9iLkh9NPhtU0jihny0MYiWlxT6Tg4yiHr%2FQ5d6a1DEZvg8L6m9A6ckb0%2Bn69vkrnDd1zoE%3D",
                    rsaSha1Signature);
            }
Beispiel #9
0
    /// <summary>
    /// Generates an OAuth signature to pass to an
    /// <see cref="IAuthenticator" /> for the purpose of requesting an
    /// unauthorized request token.
    /// </summary>
    /// <param name="method">The HTTP method for the intended request</param>
    /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
    /// <returns></returns>
    public OAuthParameters BuildRequestTokenInfo(string method, WebPairCollection parameters)
    {
        ValidateTokenRequestState();

        var allParameters = new WebPairCollection();

        allParameters.AddRange(parameters);

        var timestamp = OAuthTools.GetTimestamp();
        var nonce     = OAuthTools.GetNonce();

        var authParameters = GenerateAuthParameters(timestamp, nonce);

        allParameters.AddRange(authParameters);

        var signatureBase = OAuthTools.ConcatenateRequestElements(method, Ensure.NotNull(RequestTokenUrl, nameof(RequestTokenUrl)), allParameters);

        return(new OAuthParameters {
            Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret),
            Parameters = authParameters
        });
    }
Beispiel #10
0
    /// <summary>
    /// Generates an OAuth signature to pass to an
    /// <see cref="IAuthenticator" /> for the purpose of exchanging user credentials
    /// for an access token authorized by the user at the Service Provider site.
    /// </summary>
    /// <param name="method">The HTTP method for the intended request</param>
    /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
    public OAuthParameters BuildClientAuthAccessTokenSignature(string method, WebPairCollection parameters)
    {
        ValidateClientAuthAccessRequestState();

        var allParameters = new WebPairCollection();

        allParameters.AddRange(parameters);

        var uri       = new Uri(Ensure.NotNull(AccessTokenUrl, nameof(AccessTokenUrl)));
        var timestamp = OAuthTools.GetTimestamp();
        var nonce     = OAuthTools.GetNonce();

        var authParameters = GenerateXAuthParameters(timestamp, nonce);

        allParameters.AddRange(authParameters);

        var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), allParameters);

        return(new OAuthParameters {
            Signature = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret),
            Parameters = authParameters
        });
    }
Beispiel #11
0
        private void LoadBookedCars()
        {
            HasBooking = false;
            try {
                var token       = (string)App.GetAppSetting("car2go.oauth_token");
                var tokenSecret = (string)App.GetAppSetting("car2go.oauth_token_secret");
                if (null == token || null == tokenSecret)
                {
                    return;
                }

                const string car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/booking";
                var          parameters            = new WebParameterCollection {
                    { "oauth_callback", "oob" },
                    { "oauth_signature_method", "HMAC-SHA1" },
                    { "oauth_token", token },
                    { "oauth_version", "1.0" },
                    { "oauth_consumer_key", consumerkey },
                    { "oauth_timestamp", OAuthTools.GetTimestamp() },
                    { "oauth_nonce", OAuthTools.GetNonce() },
                    { "format", "json" },
                    { "loc", City },
                };
                //parameters.Add("test", "1");
                var signatureBase = OAuthTools.ConcatenateRequestElements("GET", car2GoRequestEndpoint, parameters);
                var signature     = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha1, OAuthSignatureTreatment.Escaped, signatureBase, FreeCarsCredentials.Car2Go.SharedSecred, tokenSecret);

                var requestParameters = OAuthTools.NormalizeRequestParameters(parameters);
                var requestUrl        = new Uri(car2GoRequestEndpoint + "?" + requestParameters + "&oauth_signature=" + signature, UriKind.Absolute);

                var webClient = new WebClient();
                webClient.OpenReadCompleted += (sender, args) => {
                    try {
                        if (0 == args.Result.Length)
                        {
                            return;
                        }
                        try {
                            var serializer    = new DataContractJsonSerializer(typeof(Car2GoBookingResult));
                            var bookingResult = (Car2GoBookingResult)serializer.ReadObject(args.Result);
                            var car2GoCars    = new List <Car2GoMarker>();
                            if (0 == bookingResult.ReturnValue.Code)
                            {
                                if (bookingResult.Booking.Length > 0)
                                {
                                    lastBookedCarsUpdate = DateTime.Now;
                                }
                                foreach (var booking in bookingResult.Booking)
                                {
                                    var           car         = booking.Vehicle;
                                    GeoCoordinate carPosition = null;
                                    try {
                                        carPosition = new GeoCoordinate(car.Position.Latitude, car.Position.Longitude);
                                    } catch {}
                                    var carInfo = new Car2GoMarker {
                                        model        = ("CE" == car.EngineType) ? "C-Smart" : "Smart ElectricDrive",
                                        fuelState    = car.Fuel,
                                        position     = carPosition,
                                        licensePlate = car.NumberPlate,
                                        ID           = car.VIN,
                                        exterior     = car.Exterior,
                                        interior     = car.Interior,
                                        isBooked     = true,
                                        BookingId    = bookingResult.Booking[0].BookingId,
                                    };
                                    HasBooking = true;
                                    car2GoCars.Add(carInfo);
                                }
                                Markers = car2GoCars;
                                if (null != Updated)
                                {
                                    Updated(this, null);
                                }
                            }
                        } catch (NullReferenceException) { }
                    } catch (WebException) { }
                };

                webClient.OpenReadAsync(requestUrl);
            } catch (Exception e) {
                Console.WriteLine(e);
            }
        }
        private void CreateCar2GoBooking(DownloadStringCompletedEventHandler requestCallback)
        {
            var item = (Car2GoMarker)Item;
            var car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/bookings";
            var oauth_timestamp = (DateTime?)App.GetAppSetting("car2go.oauth_token_timestamp");
            if (null == oauth_timestamp) {
                App.ClearAppSetting("car2go.oauth_token");
                App.ClearAppSetting("car2go.oauth_token_secret");
            } else if (((DateTime)oauth_timestamp).AddDays(90.0).CompareTo(DateTime.UtcNow) <= 0) {
                App.ClearAppSetting("car2go.oauth_token");
                App.ClearAppSetting("car2go.oauth_token_secret");
            }
            var oauthToken = (string)App.GetAppSetting("car2go.oauth_token");
            var oauthTokenSecret = (string)App.GetAppSetting("car2go.oauth_token_secret");
            if (null == oauthToken || null == oauthTokenSecret) {
                HandleNotConnectedToCar2Go(null == oauth_timestamp ? "" : Strings.SettingsPageCar2GoAuthExpired);
            }
            var accountId = "";
            try {
                accountId = ((int)App.GetAppSetting("car2go.oauth_account_id")).ToString();
            } catch (NullReferenceException) {
                return;
            }

            var parameters = new WebParameterCollection();
            parameters.Add("oauth_callback", "oob");
            parameters.Add("oauth_signature_method", "HMAC-SHA1");
            parameters.Add("oauth_token", oauthToken);
            parameters.Add("oauth_version", "1.0");
            parameters.Add("oauth_consumer_key", FreeCarsCredentials.Car2Go.ConsumerKey);
            parameters.Add("oauth_timestamp", OAuthTools.GetTimestamp());
            parameters.Add("oauth_nonce", OAuthTools.GetNonce());
            parameters.Add("format", "json");
            parameters.Add("loc", Car2Go.City);
            parameters.Add("vin", item.ID);
            parameters.Add("account", accountId);
            var signatureBase = OAuthTools.ConcatenateRequestElements("POST", car2GoRequestEndpoint, parameters);
            var signature = OAuthTools.GetSignature(
                OAuthSignatureMethod.HmacSha1,
                OAuthSignatureTreatment.Escaped,
                signatureBase,
                FreeCarsCredentials.Car2Go.SharedSecred,
                oauthTokenSecret);

            var requestParameters = OAuthTools.NormalizeRequestParameters(parameters);
            var para = requestParameters + "&oauth_signature=" + signature;

            Helpers.Post(car2GoRequestEndpoint, para, delegate(Stream response) {
                if (null == response) return;
                var serializer = new DataContractJsonSerializer(typeof(Car2GoBookingResult));
                var resultAccounts = (Car2GoBookingResult)serializer.ReadObject(response);
                Dispatcher.BeginInvoke(() => {
                    var mbResult = MessageBoxResult.None;
                    try {
                        mbResult = 0 == resultAccounts.ReturnValue.Code
                            ? MessageBox.Show(resultAccounts.Booking[0].Vehicle.Position.Address, resultAccounts.ReturnValue.Description, MessageBoxButton.OK)
                            : MessageBox.Show(resultAccounts.ReturnValue.Description);
                    } catch (Exception) {
                        Deactivate();
                    }
                    if (mbResult == MessageBoxResult.OK) {
                        InvokeActionCompleted();
                        FlurryWP7SDK.Api.LogEvent("Car2GoBookingSucessfull");
                    }
                });
            });
            FlurryWP7SDK.Api.LogEvent("Car2GoookingStarted");
        }
Beispiel #13
0
        /// <summary>
        /// Signs the specified URL with HMAC-SHA1 using the private key.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <returns>Signed URL.</returns>
        private string SignURL(string url)
        {
            var guid = Guid.NewGuid();

            return(url + "&appid=android2&device=" + guid + "&locale=en_US&timestamp=" + OAuthTools.GetTimestamp() + "&sig=and2-" + OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha1, url + "&appid=android2&device=" + guid + "&locale=en_US", Key));
        }
Beispiel #14
0
            public void ThrowsForRsaSha1SignatureWithoutSupportOfDotNetStandard20()
            {
                void GetRsaSha1Signature() => OAuthTools.GetSignature(OAuthSignatureMethod.RsaSha1, OAuthSignatureTreatment.Escaped, _aStringToSign, _ARsaPemPrivateKey);

                Assert.Throws <NotImplementedException>(GetRsaSha1Signature);
            }
Beispiel #15
0
 public void HmacSha256_Does_Not_Accept_Nulls()
 {
     string consumerSecret = "12345678";
     string actual         = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha256, null, consumerSecret);
 }
Beispiel #16
0
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var url = client.BuildUri(request).ToString();

            // add body xauth arguments
            var arguments = new Dictionary <string, object>();

            if (string.IsNullOrWhiteSpace(Token))
            {
                arguments.Add("x_auth_username", Username);
                arguments.Add("x_auth_mode", "client_auth");
                arguments.Add("x_auth_password", Password);

                foreach (var item in arguments)
                {
                    request.AddParameter(item.Key, item.Value);
                }
            }
            else
            {
                foreach (var parameter in request.Parameters)
                {
                    arguments.Add(parameter.Name, parameter.Value);
                }
            }

            var nonce           = OAuthTools.GetNonce();
            var signatureMethod = "HMAC-SHA1";
            var timeStamp       = OAuthTools.GetTimestamp();
            var version         = "1.0";

            var oauthArguments = new Dictionary <string, string>();

            oauthArguments.Add("oauth_signature_method", signatureMethod);
            oauthArguments.Add("oauth_nonce", nonce);
            oauthArguments.Add("oauth_consumer_key", ConsumerKey);
            oauthArguments.Add("oauth_timestamp", timeStamp);
            oauthArguments.Add("oauth_version", version);
            if (!string.IsNullOrWhiteSpace(Token))
            {
                oauthArguments.Add("oauth_token", Token);
            }

            var mergedArguments = new Dictionary <string, object>(arguments);

            foreach (var item in oauthArguments)
            {
                mergedArguments.Add(item.Key, item.Value);
            }

            mergedArguments = mergedArguments.OrderBy(i => i.Key).ToDictionary(pair => pair.Key, pair => pair.Value);

            var signatureBase = String.Format("{0}&{1}&", Method.POST, OAuthTools.UrlEncodeRelaxed(url));

            foreach (var item in mergedArguments)
            {
                var    encodedKey = OAuthTools.UrlEncodeRelaxed(item.Key);
                string encodedValue;
                if (item.Value != null)
                {
                    encodedValue = OAuthTools.UrlEncodeRelaxed(item.Value.ToString());
                }
                else
                {
                    encodedValue = string.Empty;
                }
                signatureBase += String.Format("{0}%3D{1}%26", encodedKey, encodedValue);
            }

            signatureBase = signatureBase.Substring(0, signatureBase.Length - 3);
            signatureBase = signatureBase.Replace("%40", "%2540"); // ugly hack for now...

            var signature = OAuthTools.GetSignature(signatureBase, ConsumerSecret, TokenSecret);

            // create authorization header
            var authHeader = "OAuth ";

            authHeader += string.Format("{0}=\"{1}\"", "oauth_signature", signature);

            foreach (var item in oauthArguments)
            {
                authHeader += string.Format(", {0}=\"{1}\"", item.Key, item.Value);
            }
            request.AddHeader("Authorization", authHeader);
        }
        private void CancelCar2GoBooking()
        {
            var item = (Car2GoMarker)Item;
            var car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/booking/" + item.BookingId;

            var oauthToken = (string)App.GetAppSetting("car2go.oauth_token");
            var oauthTokenSecret = (string)App.GetAppSetting("car2go.oauth_token_secret");
            if (null == oauthToken || null == oauthTokenSecret) {
                HandleNotConnectedToCar2Go();
            }
            var accountId = "";
            try {
                accountId = ((int)App.GetAppSetting("car2go.oauth_account_id")).ToString();
            } catch (NullReferenceException) {
                return;
            }

            var parameters = new WebParameterCollection();
            parameters.Add("oauth_callback", "oob");
            parameters.Add("oauth_signature_method", "HMAC-SHA1");
            parameters.Add("oauth_token", oauthToken);
            parameters.Add("oauth_version", "1.0");
            parameters.Add("oauth_consumer_key", FreeCarsCredentials.Car2Go.ConsumerKey);
            parameters.Add("oauth_timestamp", OAuthTools.GetTimestamp());
            parameters.Add("oauth_nonce", OAuthTools.GetNonce());
            parameters.Add("format", "json");
            parameters.Add("account", accountId);
            var signatureBase = OAuthTools.ConcatenateRequestElements("DELETE", car2GoRequestEndpoint, parameters);
            var signature = OAuthTools.GetSignature(
                OAuthSignatureMethod.HmacSha1,
                OAuthSignatureTreatment.Escaped,
                signatureBase,
                FreeCarsCredentials.Car2Go.SharedSecred,
                oauthTokenSecret);

            var requestParameters = OAuthTools.NormalizeRequestParameters(parameters);
            var para = requestParameters + "&oauth_signature=" + signature;

            Helpers.Delete(car2GoRequestEndpoint, para, delegate(Stream args) {
                if (null == args) return;
                try {
                    var serializer = new DataContractJsonSerializer(typeof(Car2GoCancelBookingResult));
                    var resultAccount = (Car2GoCancelBookingResult)serializer.ReadObject(args);
                    Dispatcher.BeginInvoke(() => {
                        var mbResult = MessageBoxResult.None;
                        try {
                            if (0 == resultAccount.ReturnValue.Code) {
                                var message = (resultAccount.CancelBooking[0].cancelFeeExists)
                                                  ? String.Format(
                                                      Strings.BookingPageC2GCancelationSuccessful,
                                                      resultAccount.CancelBooking[0].cancelFee,
                                                      resultAccount.CancelBooking[0].cancelFeeCurrency)
                                                  : String.Format(
                                                      Strings.BookingPageC2GCancelationSuccessful,
                                                      0, "");
                                mbResult = MessageBox.Show(
                                    message,
                                    resultAccount.ReturnValue.Description, MessageBoxButton.OK);
                            } else {
                                mbResult = MessageBox.Show(resultAccount.ReturnValue.Description);
                            }
                        } catch (Exception) {
                            Deactivate();
                        }
                        if (mbResult != MessageBoxResult.OK) {
                            return;
                        }
                        InvokeActionCompleted();
                    });
                } catch (SerializationException) {
                    InvokeActionCompleted();
                }
            });
        }