Question

EDIT: java equivalent to php's hmac-SHA1
(well hopefully, trying a.t.m.)

My understanding is that to create a signature I need a 'base string' and a 'key'. I guess I know how to create the base string, and I assume I'm supposed to use 'OAuth Consumer Secret' that Google have assigned to my app as the key.

But what am I supposed to do with these two to obtain the signature? Is there any HMAC-class on GAE/Java?

Would it play if I just stored somewhere what OAuth Playground generates for me? Is it how you do it? Or does OAuth signature have some expiration date?

(I tried AuthSub before but failed too, even though it looks quite simple. Also OAuth seems like more 'standard' to me, so I'd like to stick with OAuth.)

Was it helpful?

Solution

public String computeHmac(String baseString, String key)
    throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException
{
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] digest = mac.doFinal(baseString.getBytes());
    return Base64.encode(digest);
}

OTHER TIPS

For some reason hmac_init on Quercus and GAE gives errors. One solution is to use above mentioned java method and class, import it to PHP instance and call compute.

1) Add scr/phpgae directory id you dont have yet 2) Add phpgae.HmacSHA256 line to src/WEB-INF/services/com.caucho.QuercusModule 3) Add scr/phpgae/HmacSHA256.java to your GAE application:

package phpgae;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

import com.caucho.util.Base64;

import com.caucho.quercus.module.AbstractQuercusModule;

public class HmacSHA256 extends AbstractQuercusModule {

    public String compute(String baseString, String key) throws InvalidKeyException, NoSuchAlgorithmException {
        Mac mac;
        mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
        mac.init(secret);
        byte[] digest = mac.doFinal(baseString.getBytes());
        return Base64.encode(digest);
    }
}

Note I'm using SHA256 here. Eclipse compiles everything on fly, otherwise you need to complile class manually.

4) On PHP here is what you do:

<?php

import phpgae.HmacSHA256;

$c = new HmacSHA256;

echo $c->compute( 'your base string' ,  'your key' );

?>

You can find more practical PHP on Google App Engine examples from: http://php-apps.appspot.com/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top