Reputation: 4973
I am java developer and I am trying to use one WEB Service API (ticketutils) where they have explained two examples first one with PHP
and second one with C#
. Unfortunately I am not able to get any of them. I have mentioned PHP example below.
public function GenerateSignature($Secret,$PathAndQuery)
{
return base64_encode(\Zend_Crypt_Hmac::compute($Secret, 'sha256',
$PathAndQuery, \Zend_Crypt_Hmac::BINARY));
}
Can anyone please explain me how can I achieve the same with Java code? I have tried below code but it seems it's not generating proper outcome.
public static String generateSignature(String secrete, String pathAndQuery){
String encoded = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(secrete.getBytes("UTF-8"));
md.update(pathAndQuery.getBytes("UTF-8"));
byte[] digest = md.digest();
encoded = Base64.getEncoder().encodeToString(digest);
} catch (Exception e) {
e.printStackTrace();
}
return encoded;
}
NOTE : I have used Java-8 for while writing above code.
Upvotes: 0
Views: 109
Reputation:
Hash a Secret keyword with sha256..Then use the keyword to encode anything in Base64..
Have a look at http://www.jokecamp.com/blog/examples-of-creating-base64-hashes-using-hmac-sha256-in-different-languages/#java
Not exactly what you are looking for but you can turn the process into a function which takes two arguments and returns the Base64 value..
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class ApiSecurityExample {
public static void main(String[] args) {
try {
String secret = "secret";
String message = "Message";
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secret_key);
String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
System.out.println(hash);
}
catch (Exception e){
System.out.println("Error");
}
}
}
Upvotes: 1
Reputation: 1483
The Java API for message digests is very similar to the C# one. Please follow this example: https://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html
Upvotes: 0