2

I saw some same questions in stack-overflow but it doesn't help me.

I have this php code

$signature=base64_encode(hash_hmac("sha256", trim($xmlReq), $signature_key, True));

I want to write java equivalent to that and this is my java code.

public static String encodeXML(String key, String data) {
    String result = "";
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        mac.init(secretKeySpec);
        result = Base64.encodeBase64String(mac.doFinal(data.getBytes("UTF-8")));
    } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
        log.error("exception occured when encording HmacSHA256 hash");
    }
    return result;
}

but they give different results. someone help.

2 Answers 2

1

Apache Commons Codec

 import org.apache.commons.codec.binary.Base64;
 ....
 Base64.encodeBase64String(.....);
Sign up to request clarification or add additional context in comments.

Comments

0

PHP Test Code:

 $signature=base64_encode(hash_hmac("sha256", 'Message', 'secret', true));
 echo $signature;

Java Test Code:

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import java.util.Base64;
public class TestJava {

   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);

         Base64.Encoder encoder = Base64.getEncoder();
         String hash = encoder.encodeToString(sha256_HMAC.doFinal(message.getBytes()));
         System.out.println(hash);
     } catch (Exception e){
       System.out.println("Error");
     }
  }
}

Output for both should be: qnR8UCqJggD55PohusaBNviGoOJ67HC6Btry4qXLVZc=

1 Comment

Base64.Encoder is in java 8. How to do this using java 7?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.