Java HmacSHA256加密与PHP、Golang语言SHA256互通

最近工作中涉及到关于HmacSHA256加密的方式, PHP同事咨询我说无法加密,其实问题很简单,记录下来,方便那些不细心的码友们^_^。

JAVA中HmacSHA256的加密方式:

public static String SignUp(String secretKey, String plain) {

	        byte[] keyBytes = secretKey.getBytes();
	        byte[] plainBytes = plain.getBytes();

	        try {
	            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
	            SecretKeySpec secret_key = new SecretKeySpec(keyBytes, "HmacSHA256");
	            sha256_HMAC.init(secret_key);
	            byte[] hashs = sha256_HMAC.doFinal(plainBytes);
	            StringBuilder sb = new StringBuilder();
	            for (byte x : hashs) {
	                String b = Integer.toHexString(x & 0XFF);
	                if (b.length() == 1) {
	                    b = '0' + b;
	                }
//	          sb.append(String.format("{0:x2}", x));
	                sb.append(b);
	            }
	            return sb.toString();
	            // String hash =
	            // Base64.encodeToString(sha256_HMAC.doFinal(plainBytes),
	            // Base64.DEFAULT);
//	       return hash;
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return null;
	    }

 大致分为这几部分来分析:

1. 获取SHA256实例

2. 生成一个加密key

3.通过这个加密key初始化SHA256实例

4. 根据提供的字符串,使用此实例进行加密生成hash

4. 最后整体就是转为16进制后再输出字符串

PHP部分很简单

扫描二维码关注公众号,回复: 878729 查看本文章

世界上最好的语言嘛,对不对!!


function ($plain,$secretKey){
  return bin2hex(hash_hmac("sha256",utf8_encode($plain) , utf8_encode($secretKey), true));
}

为了方便对比,我将函数参数都声明为相同的名字。

注意PHP文档中的hash_hmac的声明:   

string hash_hmac ( string $algo , string $data , string $key [, bool $raw_output = FALSE ] )

algo
要使用的哈希算法名称,例如:"md5","sha256","haval160,4" 等。 如何获取受支持的算法清单,请参见 hash_algos()。

data
要进行哈希运算的消息。

key
使用 HMAC 生成信息摘要时所使用的密钥。

raw_output 设置为 TRUE 输出原始二进制数据, 设置为 FALSE 输出小写 16 进制字符串。

就因为JAVA工程师将参数跟PHP的参数传递相反,导致PHP工程师?蒙b!

Golang部分后期更新

=========Golang SHA256 HMAC Hash==========

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
)

func main() {

    secret := "mysecret"
    data := "data"
    fmt.Printf("Secret: %s Data: %s\n", secret, data)

    // Create a new HMAC by defining the hash type and the key (as byte array)
    h := hmac.New(sha256.New, []byte(secret))

    // Write Data to it
    h.Write([]byte(data))

    // Get result and encode as hexadecimal string
    sha := hex.EncodeToString(h.Sum(nil))

    fmt.Println("Result: " + sha)
}

猜你喜欢

转载自my.oschina.net/90design/blog/1636032