Domanda

I'm attempting to make an hmac implementation that interacts with a server api and the only example I have to go off of is a python snippet. Unfortunately I've never touched python and my Java is a bit rusty.

The python example code includes the function:

handshake = str(hmac.new(secret, hash_data, sha512))

where secret is the decoded hash retrieved from the server being connected to, hash_data is the data to be sent, and sha512 is the "MessageDigest" type when converted to Java.

I'm just wondering if there is a close java equivalent to this function. It seems like it should be in the Java.Security class but I'm having trouble finding hmac functions and implementations.

È stato utile?

Soluzione

API's and functions related to cryptology are present in javax.crypto, not java.security.

I don't know Python, but given your description and the documentation of the methods shown, you want something along these lines:

final Charset charset = Charset.forName("ASCII");
final String secret = "mykey";
final String data = "A message to be turned to gibberish";
final String algorithm = "HmacSHA512";

byte[] keyBytes = secret.getBytes(charset);
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, algorithm);

Mac mac = Mac.getInstance(algorithm);
mac.init(signingKey);

byte[] hashed = mac.doFinal(data.getBytes(charset));
System.out.println(new String(hashed, charset));

The code assumes byte and string conversions are based on ASCII (which I believe Python uses by default). You will in all likelihood have to tweak the logic, but its a good starting point.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top