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

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀