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 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数