Encrypting the Query String

Last post 07-31-2007 9:28 AM by wolkje. 8 replies.

Sort Posts:

  • Encrypting the Query String

    07-31-2007, 5:13 AM
    • Loading...
    • taimoor2
    • Joined on 07-01-2007, 4:07 PM
    • Posts 49

    Hi all....

    I have just setup my site for paypal website payment standard. The way I tranfer all the variables to paypal is this.I let user add everything to a cart and all normal stuff and than when he click the checkout button, I dynamically generate the url with relevant query strings and then use  response.redirect(url,false) to paypal site. For example, one example is:

    https://www.paypal.com/cgi-bin/webscr?cmd=_cart&currency_code=SGD&business=someone@something.com&upload=1&item_name_1="Item1"&amount_1="200"&item_name_2="Item2"&amount_2="300"

    Now the problem is that the above query string is extremely easy to manipulate. Is there some way to encrypt this key so normal users,atleast novice users,cannot alter it? I know you can encrypt buttons but encrypting this is quite hard for me...there must be some way....

    Please Help!

     

     

  • Re: Encrypting the Query String

    07-31-2007, 6:05 AM
    • Loading...
    • jackyang
    • Joined on 11-16-2006, 7:27 PM
    • Canada
    • Posts 420

    The easiest way is to obfuscate the query string, a good example with code: http://www.eggheadcafe.com/articles/20060427.asp

    If you really want a safe guard, you can always use AES to do encryption/decryption, examples: http://channel9.msdn.com/wiki/default.aspx/SecurityWiki.SecurityCodeExamples2 Note that it's strongly recommended you store the encryption key in a safe storage, use either DPAPI or RSA.

    Jack Yang
    .NET Developer
  • Re: Encrypting the Query String

    07-31-2007, 7:28 AM

    Hi,

    Check out these,

     

    http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html
    http://msdn2.microsoft.com/en-us/library/dtkwfdky.aspx 
    http://weblogs.asp.net/scottgu/archive/2006/01/09/434893.aspx 

     

    Mehedi Hasan


    Mark as answer if the post meets your requirement!
  • Re: Encrypting the Query String

    07-31-2007, 7:36 AM
    • Loading...
    • taimoor2
    • Joined on 07-01-2007, 4:07 PM
    • Posts 49

    Actually none of the solutions given above works!

     The thing is I am passing the query string to paypal so I have no control whatsoever over the recieving end. I cannot hash the string or encrypt it in some other way because paypal won't know what to do! Has no one faced this problem before? Even the e-commerce kit just passes the query string without any encryption!!!This is very very wasy for ANYONE to fool so there must be some other way!

  • Re: Encrypting the Query String

    07-31-2007, 7:42 AM
    • Loading...
    • wolkje
    • Joined on 07-27-2007, 8:31 AM
    • The Netherlands
    • Posts 30

    This is indeed impossible to do, without the help of Paypal itself. However ask yourself this:

     What could go wrong?

    Altering the querystring only results in different amounts being transferred to you; either more or less. It is not like they can fake users into paying someone else their money. So although this might seem like a security risk, where is the actual risk? Plus if it really is a risk, why hasn't anyone at Paypal done anything about it?

     

    Hope this helps.

    me.Dispose();

    -- Please Mark Posts that helped you as Answers, and share a summary of what solved the problem.
  • Re: Encrypting the Query String

    07-31-2007, 7:53 AM

    PayPal api allows you to do just that. There are various methods to secure query string in paypal using the api

    Please Mark Post that helped you as answer, also include a summary of what solved the problem as it helps others in similar situations
  • Re: Encrypting the Query String

    07-31-2007, 8:31 AM
    • Loading...
    • taimoor2
    • Joined on 07-01-2007, 4:07 PM
    • Posts 49

    naturehermit:

    PayPal api allows you to do just that. There are various methods to secure query string in paypal using the api

    How mean!!! Now I know something can be done about it yet I don't know how to do it! Can you please please elaborate on how I can use paypal APIs to do just that?

  • Re: Encrypting the Query String

    07-31-2007, 9:26 AM

    Unfortunately i can say very little because its a paid stuff. however they have got SSL, Url security etc stuff as part of the api, for your query sake i can put a little example

    In this first block of code we will respond to some click on a button within an ASPX page. You'll notice that we build a query string that contains all the information that PayPal requires in order to handle the transaction.

    Private Sub PurchaseBtn_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles cmdPurchase.Click
      ::
      If Page.IsValid Then                
        ' build secure PayPal URL
        Dim sBaseURL As String = IIf(Request.ApplicationPath = "/", "", _
            Request.ApplicationPath) & "/PayPalIPN"
        Dim strPayPalURL As String = ""
        ' strProcessorId is your PayPal account name.
        strPayPalURL = "https://www.paypal.com/xclick/business=" & HTTPPOSTEncode(strProcessorUserId)
        ' strProductName is the name of the product you want displayed to the user on the payment screen.
        strPayPalURL =+ "&item_name=" & HTTPPOSTEncode(strProductName)
        ' An item number for your product.
        strPayPalURL =+ "&item_number=" & HTTPPOSTEncode(strItemNumber)
        ' Quantity that the user is purchasing.
        strPayPalURL =+ "&quantity=1"
        ' Custom can be any value you want, here we are passing the user account for the site.
        strPayPalURL =+ "&custom=" & HTTPPOSTEncode(Context.User.Identity.Name)
        ' The price of the product.
        strPayPalURL =+"&amount=" & HTTPPOSTEncode(strPrice)
        ' Optional currency type for the transaction.
        strPayPalURL =+ "¤cy_code=" & HTTPPOSTEncode(lblTotalCurrency.Text)
        ' Where do you want the customer to go once they pay for the item?
        strPayPalURL =+ "&return=" & HTTPPOSTEncode("http://" & GetDomainName(Request))
        ' This is for redirecting to a cancel page if the customer decides to cancel the purchase.
        strPayPalURL =+ "&cancel_return=" & HTTPPOSTEncode("http://" & GetDomainName(Request))
        ' this is where you want PayPal to send the IPN to. 
        ' You can also use the default one configured via the
        ' PayPal site, but this allows you to specify a dynamic URL for accepting the IPN.
        strPayPalURL =+ "¬ify_url=" & HTTPPOSTEncode(sBaseURL & "/PaymentNotify.aspx")
        strPayPalURL =+ "&undefined_quantity=&no_note=1&no_shipping=1"
        ' redirect to PayPal
        Response.Redirect(strPayPalURL)
      End If
    End Sub

    Now that we have the code to send PayPal the information we need to set up three pages:

    1. The Cancel Page. We not going to cover this here. This page can contain some kind of message to the user or send them back to your site.
    2. The Thank You Page. Again, this page we don't do anything special. At this point we do not know if the transaction was successful, we won't know this until PayPal sends a message to our IPN handler page.
    3. The IPN Handler. This is where we do the bulk of our application logic. This page is going to accept the request from PayPal, validate the request, ensure the values are correct, and then do some action like send the user an email with a download link.

    The IPN Handler

    This is the page that is the bulk of the application. In this page we are going to handle the information from PayPal. We will verify the information from PayPal to make sure it is coming from PayPal, check the transaction information to see if the payment was complete. We will then check the transaction amount from PayPal to make sure it matches up with the amount for the product, then send the user an email notifying them of a successful transaction.

    We will create a PayPalNotify.aspx for receiving the IPNs. In the code behind we'll first include a couple namespaces:

    Imports System.Net
    Imports System.IO
    

    PayPal is going to send an HTTP Post to this page, so we need to handle the post values coming in and then post it back to PayPal for verification. In the Page_OnLoad event we'll accept the parameters and assign them to variables. Then we'll send this information back to PayPal for verification.

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      ' assign posted variables to local variables
      Receiver_email = Request.Params("receiver_email")
      Item_name = Request.Params("item_name")
      Item_number = Request.Params("item_number")
      Quantity = Request.Params("quantity")
      Invoice = Request.Params("invoice")
      Custom = Request.Params("custom")
      Payment_status = Request.Params("payment_status")
      Pending_reason = Request.Params("pending_reason")
      Payment_date = Request.Params("payment_date")
      Payment_fee = Request.Params("payment_fee")
      Payment_gross = Request.Params("payment_gross")
      Txn_id = Request.Params("txn_id")
      Txn_type = Request.Params("txn_type")
      First_name = Request.Params("first_name")
      Last_name = Request.Params("last_name")
      Address_street = Request.Params("address_street")
      Address_city = Request.Params("address_city")
      Address_state = Request.Params("address_state")
      Address_zip = Request.Params("address_zip")
      Address_country = Request.Params("address_country")
      Address_status = Request.Params("address_status")
      Payer_email = Request.Params("payer_email")
      Payer_status = Request.Params("payer_status")
      Payment_type = Request.Params("payment_type")
      Notify_version = Request.Params("notify_version")
      Verify_sign = Request.Params("verify_sign")
      ::
      ::

    strToSend = Request.Form.ToString()

    'Create the string to post back to PayPal system to validate

    strToSend &= "&cmd=_notify-validate"

    'Initialize the WebRequest.

    Dim PostMode As String = "2"

    Dim WebURL As String

    Dim SdHost As String

    '//* 1 = Live Via PayPal Network Non-Secure

    '//* 2 = Live Via PayPal Network SSL-Secure

    '//* 3 = Test Via EliteWeaver UK Non-Secure

    '//* 4 = Test Via EliteWeaver UK SSL-Secure

    If PostMode = "1" Then

    '// Live Via PayPal Network Non-Secure

    WebURL = "http://www.paypal.com/cgi-bin/webscr"

    SdHost = "www.paypal.com"

    ElseIf PostMode = "2" Then

    '// Live Via PayPal Network SSL-Secure

    WebURL = "https://www.paypal.com/cgi-bin/webscr"

    SdHost = "www.paypal.com"

    ElseIf PostMode = "3" Then 'strictly for testing!!!

    '// Test Via EliteWeaver UK Non-Secure

    WebURL = "http://www.eliteweaver.co.uk/testing/ipntest.php"

    SdHost = "www.eliteweaver.co.uk"

    Else

    '// Selected PostMode was Probably Not Set to 1, 2, 3 or 4

    Response.Write("PostMode: " & (PostMode) & " is invalid!")

    End If

    Now we'll take our values and post them back to PayPal.

    ::
    ::
    Dim myRequest As HttpWebRequest = CType(HttpWebRequest.Create(WebURL), HttpWebRequest)
    myRequest.AllowAutoRedirect = False
    myRequest.Method = "POST"
    myRequest.ContentType = "application/x-www-form-urlencoded"
    'Create post stream
    Dim RequestStream As Stream = myRequest.GetRequestStream()
    Dim SomeBytes() As Byte = Encoding.UTF8.GetBytes(strToSend)
    RequestStream.Write(SomeBytes, 0, SomeBytes.Length)
    RequestStream.Close()
    'Send request and get response
    Dim myResponse As HttpWebResponse = CType(myRequest.GetResponse(), HttpWebResponse)
    If myResponse.StatusCode = HttpStatusCode.OK Then
      'Get the stream.
      Dim ReceiveStream As Stream = myResponse.GetResponseStream()
      Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")
      'send the stream to a reader. 
      Dim readStream As StreamReader = New StreamReader(ReceiveStream, encode)
      'Read the result
      Dim Result As String = readStream.ReadLine()
      If Result = "INVALID" Then
        ' The result was invalid so send a failure notice or some other handling.
      ElseIf Result = "VERIFIED" Then
        Select Case (Payment_status)
          Case "Completed"        
            ' The payment has been completed and the 
            ' funds are successfully in your account balance.
            ' Add code for emailing user. First check your database 
            ' to make sure the price that was sent to PayPal
            ' is the same price as your product. 
            ' This will prevent people from URL tampering with your price.
       End Select
     End If
     myResponse.Close()
    End If
    End Sub
    

    You can download the SDK for the IPN from PayPal and expand upon this code for your own applications.

    Update:

    Several comments have been placed here asking me what is HTTPPostEncode. The code from this article is pulled from an implementation on DotNetNuke. DotNetNuke provides the method HTTPPostEncode, basically this is to replace any backslashes in the directory path to something a bit more friendly for posting. Below is the HTTPPostEncode method.
     ' encodes a URL for posting to an external site
            Public Function HTTPPOSTEncode(ByVal strPost As String) As String
                strPost = Replace(strPost, "\", "")
                strPost = System.Web.HttpUtility.UrlEncode(strPost)
                strPost = Replace(strPost, "%2f", "/")
                HTTPPOSTEncode = strPost
            End Function
    
    also check out the last part http://www.vsj.co.uk/dotnet/display.asp?id=541
    Please Mark Post that helped you as answer, also include a summary of what solved the problem as it helps others in similar situations
  • Re: Encrypting the Query String

    07-31-2007, 9:28 AM
    Answer
    • Loading...
    • wolkje
    • Joined on 07-27-2007, 8:31 AM
    • The Netherlands
    • Posts 30

    You are the one with the Paypal API developer login. I'd recommend you go here. This is no ASP.NET problem, but purely a Paypal API question :) They can easily answer this question.

    Hope this helps.

    me.Dispose();

    -- Please Mark Posts that helped you as Answers, and share a summary of what solved the problem.
Page 1 of 1 (9 items)
Microsoft Communities
Page view counter