Comment générer un HMAC en Java équivalent à un exemple Python?

Je suis à la recherche à la mise en œuvre d'une application se Twitter autorisation via Oauth en Java. La première étape est l'obtention d'un jeton de demande. Voici une Exemple Python pour app engine.

Pour tester mon code, je suis en cours d'exécution Python et la vérification de sortie avec Java. Voici un exemple de Python générer un Hash Message Authentication Code (HMAC):

#!/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]

De sortie:

$ ./foo.py
+3h2gpjf4xcynjCGU5lbdMBwGOc=

Comment reproduire cet exemple en Java?

J'ai vu un exemple de HMAC en Java:

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) {
}

Il utilise javax.crypto.Mac, toutes les bonnes. Cependant, la SecretKey les constructeurs ont octets et d'un algorithme.

Quel est l'algorithme dans l'exemple Python? Comment peut-on créer un Java clé secrète sans un algorithme?

InformationsquelleAutor dfrankow | 2010-07-08