Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to generate an HMAC in Java equivalent to a Python example?
    primarykey
    data
    text
    <p>I'm looking at implementing an app getting <a href="http://apiwiki.twitter.com/Authentication" rel="noreferrer">Twitter authorization via Oauth</a> in Java. The first step is <a href="http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-oauth-request_token" rel="noreferrer">getting a request token</a>. Here is a <a href="http://github.com/tav/tweetapp/blob/master/standalone/twitter_oauth_handler.py" rel="noreferrer">Python example</a> for app engine. </p> <p>To test my code, I am running Python and checking output with Java. Here is an example of Python generating a Hash-Based Message Authentication Code (HMAC):</p> <pre><code>#!/usr/bin/python from hashlib import sha1 from hmac import new as hmac key = "qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50" message = "foo" print "%s" % hmac(key, message, sha1).digest().encode('base64')[:-1] </code></pre> <p>Output:</p> <pre><code>$ ./foo.py +3h2gpjf4xcynjCGU5lbdMBwGOc= </code></pre> <p>How does one replicate this example in Java?</p> <p>I've seen an <a href="http://exampledepot.8waytrips.com/egs/javax.crypto/GenMac.html" rel="noreferrer">example of HMAC</a> in Java:</p> <pre><code>try { // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104 // In practice, you would save this key. KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5"); SecretKey key = keyGen.generateKey(); // Create a MAC object using HMAC-MD5 and initialize with key Mac mac = Mac.getInstance(key.getAlgorithm()); mac.init(key); String str = "This message will be digested"; // Encode the string into bytes using utf-8 and digest it byte[] utf8 = str.getBytes("UTF8"); byte[] digest = mac.doFinal(utf8); // If desired, convert the digest into a string String digestB64 = new sun.misc.BASE64Encoder().encode(digest); } catch (InvalidKeyException e) { } catch (NoSuchAlgorithmException e) { } catch (UnsupportedEncodingException e) { } </code></pre> <p>It uses <a href="http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/crypto/Mac.html" rel="noreferrer">javax.crypto.Mac</a>, all good. However, the <a href="http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/crypto/SecretKey.html" rel="noreferrer">SecretKey</a> constructors take bytes and an algorithm. </p> <p>What's the algorithm in the Python example? How can one create a Java secret key without an algorithm?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload