douti19680318 2016-01-10 08:57 采纳率: 0%
浏览 75
已采纳

理解使用Zend框架用PHP编写的代码片段

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.

  • 写回答

2条回答 默认 最新

  • dongrong5189 2016-01-10 12:35
    关注

    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");
        }
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?