¿Cómo generar un HMAC en Java equivalente a un ejemplo de Python?
Estoy buscando implementar una aplicación paraAutorización de Twitter a través de Oauth en Java El primer paso esobtener un token de solicitud. Aquí hay unEjemplo de Python para motor de aplicaciones.
Para probar mi código, estoy ejecutando Python y verificando la salida con Java. Aquí hay un ejemplo de Python que genera un Código de autenticación de mensajes basado en hash (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]
Salida:
$ ./foo.py
+3h2gpjf4xcynjCGU5lbdMBwGOc=
¿Cómo se replica este ejemplo en Java?
He visto unejemplo 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) {
}
Usajavax.crypto.Mac, todo bien. sin embargo, elLlave secreta los constructores toman bytes y un algoritmo.
¿Cuál es el algoritmo en el ejemplo de Python? ¿Cómo se puede crear una clave secreta de Java sin un algoritmo?