-1

I have some code in PHP:

return base64_encode( hash_hmac( self::HASH_ALGORITHM, $string_to_sign, $this->_consumer_secret, true ) );

I want to write it in JavaScript. Because I am building an app in Phonegap and PHP does not work in Phonegap.

I had tried this:

var hash = CryptoJS.HmacSHA256(HASH_ALGORITHM,string_to_sign,consumer_secret);
var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
return hashInBase64;

here is the php code for signature generate

public function generate_oauth_signature( $params, $http_method, $endpoint ) {
        $base_request_uri = rawurlencode( $this->_api_url . $endpoint );

        // normalize parameter key/values and sort them
        array_walk( $params, array( $this, 'normalize_parameters' ) );
        uksort( $params, 'strcmp' );

        // form query string
        $query_params = array();
        foreach ( $params as $param_key => $param_value ) {
            $query_params[] = $param_key . '%3D' . $param_value; // join with equals sign
        }

        $query_string = implode( '%26', $query_params ); // join with ampersand

        // form string to sign (first key)
        $string_to_sign = $http_method . '&' . $base_request_uri . '&' . $query_string;
        return base64_encode( hash_hmac( self::HASH_ALGORITHM, $string_to_sign, $this->_consumer_secret, true ) );
    }

So please anyone can help me.

15
  • Maybe phpjs can help: phpjs.org Commented Apr 10, 2014 at 12:34
  • i had tried it already Commented Apr 10, 2014 at 12:35
  • Do you try base64_encode phpjs.org/functions/base64_encode and hash_hmac from stackoverflow.com/questions/12099092/… ? Commented Apr 10, 2014 at 12:36
  • 1
    @UmNyobe I rolled back the edit from sulthan Commented Apr 10, 2014 at 12:40
  • 1
    @Thanks Icarus, I was about to do it. Commented Apr 10, 2014 at 12:40

1 Answer 1

1

Take a closer look at how you're using the cryptojs function... You're specifying the hashing algorithm in a way the method doesn't appear to support.

This:

var hash = CryptoJS.HmacSHA256(HASH_ALGORITHM,string_to_sign,consumer_secret);

... should be this:

var hash = CryptoJS.HmacSHA256(string_to_sign,consumer_secret);

... because HmacSHA256 already specifies SHA256 as the HASH_ALGORITHM.

Sign up to request clarification or add additional context in comments.

1 Comment

still there is same issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.