Sto cercando di implementare un'app ottenendo Twitter authorization via Oauth in Java. Il primo passaggio è getting a request token. Ecco un Python example per il motore di app.Come generare un HMAC in Java equivalente ad un esempio Python?
Per testare il mio codice, eseguo Python e controllo l'output con Java. Ecco un esempio di Python generare un Hash-based 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]
uscita:
$ ./foo.py
+3h2gpjf4xcynjCGU5lbdMBwGOc=
Come si fa a replicare questo esempio in Java?
Ho visto un example of HMAC in 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) {
}
Esso utilizza javax.crypto.Mac, tutto bene. Tuttavia, i costruttori SecretKey accettano byte e un algoritmo.
Qual è l'algoritmo nell'esempio Python? Come si può creare una chiave segreta Java senza un algoritmo?
buona! Grazie. – dfrankow
@Bruno hi, potresti spiegare come posso "azzerare" la chiave segreta qui se è più piccola della dimensione del blocco consigliata, che è 160 bit per SHA1 tnx – Spring
Grazie mille, ottimo esempio. Per la cronaca, penso che cambierete sicuramente il vostro codice con Apache Commons Codec o il codificatore di Guava;) – Brice