如何使用Java加密Jma by HmacSHA256

时间:2018-06-05 05:52:23

标签: java json hmac

我有这样一个Json:

{
    "idcardno":"510525198803154232",
    "name":"丁品"
}

如果我使用HmacSHA256用密钥

加密它
252c04cdb0d047f8ab9a1eb49b1db1686e321104756ff792779a4d40d94f0dfd70a8b9ffa6d6d930e57d0e7206d26d13

然后我应该得到这样的结果:

cd1fe72697a832d57198b8c0d00289309dffe6f05750aa2a145f9359e41f1843

我需要在java environemnt中加密这个json对象,所以我使用下面的java代码来实现这个目的:

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

import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;

public class EncryptUtil {

    // Charset to use when encrypting a string.
    private static final String UTF_8 = "UTF-8";
    // Encrypt key
    private static final String APP_SECRET = "252c04cdb0d047f8ab9a1eb49b1db1686e321104756ff792779a4d40d94f0dfd70a8b9ffa6d6d930e57d0e7206d";

    public static void main(String[] args) throws Exception {   
        //build json object
        JSONObject object = new JSONObject();
        object.put("idcardno", "510525198803154232");
        object.put("name", "丁品");

        String result = enCode(object.toString());
        //print encrpted result
        System.out.println(result);
    }

    public static String enCode(String orginalMsg) throws Exception {
        try {   
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            SecretKeySpec secret_key = new SecretKeySpec(APP_SECRET.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(orginalMsg.getBytes(UTF_8)));
            return hash;
        }
        catch (Exception e){
            throw new Exception(e);
        }
    }
}

但是加密的结果是:

i2hF1WyxmS9MctkFLxBM2mgXeicraH9DhR9P9JySDFk=

如何通过Java代码获得正确的结果?

0 个答案:

没有答案