douweng7233 2017-08-23 07:26
浏览 70

在php中重新创建java hmac函数

This is the have code which i am currently looking into

package com.security;
import java.util.Map;
import javax.xml.bind.DatatypeConverter;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;

public class Signature {
    private static final String HMAC_SHA256 = "HmacSHA256";
    private static final String SECRET_KEY = "LF8np6Lk0PvQ8yQvOnsqvC5WOnRbLOEadpZOAYd22QNdXnSKI08VXfo6Kl0yV5wx";

    public static String sign(Map<String,String> params) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
        return sign(buildDataToSign(params), SECRET_KEY).trim();
    }

    private static String sign(String data, String secretKey) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), HMAC_SHA256);
        Mac mac = Mac.getInstance(HMAC_SHA256);
        mac.init(secretKeySpec);
        byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));
        return DatatypeConverter.printBase64Binary(rawHmac).replace("
", "").trim();
    }

    private static String buildDataToSign(Map<String,String> params) {
        String[] signedFieldNames = String.valueOf(params.get("signed_fields")).split(",");
        ArrayList<String> dataToSign = new ArrayList<String>();
        for (String signedFieldName : signedFieldNames) {
            dataToSign.add(signedFieldName + "=" + String.valueOf(params.get(signedFieldName)).trim());
        }
        return commaSeparate(dataToSign);
    }

    private static String commaSeparate(ArrayList<String> dataToSign) {
        StringBuilder csv = new StringBuilder();
        for (Iterator<String> it = dataToSign.iterator(); it.hasNext(); ) {
            csv.append(it.next());
            if (it.hasNext()) {
                csv.append(",");
            }
        }
        return csv.toString();
    }
}

Here i understand that hmac ashing mechanism is being used and it generates base64 like string in the end.

I am planning to recreate the code in php which suppose to deliver the same output, can someone please explain what's actually happening here.

Thanks in advance.

At the end the above code generates a random string like:

gPRbQMzGGu4ShTwS1NzhzObRWLuGuxvKJuVpSpOaFZk=

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?