Android Tutorial OAuth - How to roll your own (easy).

Discussion in 'Tutorials & Examples' started by adrianus, Jul 18, 2011.

  1. adrianus

    adrianus New Member Licensed User


    I have seen a few unanswered OAuth questions here and since making an app for an existing site almost always needs OAuth, I decided to check out what was available.

    Whilst the twitterlib by Always Busy is cool, it is not usable (for me) for some more obscure OAuth site.

    I am of the school 'teach a man how to fish' rather than 'give him a subscription to the fish 'n chips shop', so I will explain but I will not add full blown examples; you learn more by assembling it yourself.

    Now, after this lengthy intro, let's start.

    First, we need some documentation on this OAuth thingy. Luckily the kind people at the IETF keep track of standards.

    Whilst OAuth is not an RFC Standards track document, it is a good starting point.

    So, point your browser to RFC 5849 - The OAuth 1.0 Protocol and start reading.

    With all the examples in there it is quite easy to see what OAuth does.

    The concatenation of strings should also not be a stumbling block, so, in fact, all we really need to be concerned about is the signing.

    We could implement our own SHA1 algorithm, but a Mr. AGraham has provided us with all the crypto stuff we need, including a converter.

    Next, let's do the HMAC-SHA1 key signing. Wikipedia always has some nice references to check if we are doing things right.

    Point your browser to: HMAC - Wikipedia, the free encyclopedia

    Then you need to reference the ByteConverter and the Encryption libs by AGraham and you can use the following code to check that the signing for the OAuth really is that simple:

    Dim MyKeyS As String 'The key as a string
       Dim MyKeyB() As Byte 'The key as a byte array

    Dim MyString As String 'The string we are going to sign   

    "The quick brown fox jumps over the lazy dog"
    'We need our key in byteformat
       Dim ByteEnc As ByteConverter
       MyKeyB = ByteEnc.StringToBytes(MyKeyS,

    'We abuse the KeyGenerator to get a java.crypto.key object
            Dim KeyGen As KeyGenerator

    'The encryption class has a MAC, so things could not be simpler
       Dim MyMac As Mac
    'Dump the hex key to the log, so we can verify with the reference
       Log("KEYSIGN: " & ByteEnc.HexFromBytes(MyMac.Sign()))
    Basically, that's it. Things could be coded in B4A a lot more efficient I guess, but I am a noob at this language (not a noob at coding, that is why I like RFC's).

    Well, that wraps it up. Now you should be able to do any OAuth you want.
  2. agraham

    agraham Expert Licensed User