Java HmacSHA256加密與PHP、Golang語言SHA256互連

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

 

 

最近工作中涉及到關於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部分很簡單

世界上最好的語言嘛,對不對!!

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部分後期更新

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.