天天看點

PHP實作國密SM3算法

        最近對接一個第三方系統,對方要求接口簽名加密使用sm3加密算法,不過php沒有原生支援該算法的函數,是以需要借助外力了。網上查資料發現在PHP中實作sm3算法,大概有一下三種途徑:

        A.使用PHP的OpenSSL擴充實作

        B.使用一個PHP擴充(php-sm3)實作

        C.使用大佬封裝好的PHP類庫實作

方法A

      openssl在1.1.1版本中支援了國密算法,但是我看了一下我的環境,内置的openssl是1.0.2k,版本比較老。但是更新openssl也牽扯到對php中openssl擴充的更新,此伺服器還有其他項目在運作,是以此方法就放棄了。

方法B

      在網上發現了a php extension for sm3(實作sm3算法的php擴充),Git位址:https://github.com/luzhuqun/php-sm3 。按照裡邊的方法進行安裝:

PHP實作國密SM3算法

      從安裝到測試都很順利,但是在使用的時候,出現了很多不可思議的錯誤,我的環境的PHP版本是7.2。在加密之後去調用第三方系統接口的時候,偶爾會出現nginx抛出的502錯誤,查了nginx的error log如下:

recv() failed (104: Connection reset by peer) while reading response header from upstream           

      再去檢查下php-fpm的錯誤log如下:

[15-Sep-2021 14:54:29] NOTICE: [pool www] child 20665 exited with code 0 after 8620.062716 seconds from start
[15-Sep-2021 14:54:29] NOTICE: [pool www] child 12189 started
[15-Sep-2021 14:54:29] NOTICE: [pool www] child 20646 exited with code 0 after 8636.730784 seconds from start
[15-Sep-2021 14:54:29] NOTICE: [pool www] child 12190 started
[15-Sep-2021 14:54:35] NOTICE: [pool www] child 20700 exited with code 0 after 8622.456855 seconds from start
[15-Sep-2021 14:54:35] NOTICE: [pool www] child 12196 started
[15-Sep-2021 14:54:54] NOTICE: [pool www] child 20657 exited with code 0 after 8649.930169 seconds from start
[15-Sep-2021 14:54:54] NOTICE: [pool www] child 12246 started
[15-Sep-2021 14:56:49] NOTICE: [pool www] child 20710 exited with code 0 after 8744.678411 seconds from start
[15-Sep-2021 14:56:49] NOTICE: [pool www] child 12548 started
[15-Sep-2021 15:04:39] NOTICE: [pool www] child 21734 exited with code 0 after 8807.254438 seconds from start
[15-Sep-2021 15:04:39] NOTICE: [pool www] child 13876 started
[15-Sep-2021 15:07:53] NOTICE: [pool www] child 23979 exited with code 0 after 8235.041492 seconds from start
[15-Sep-2021 15:07:53] NOTICE: [pool www] child 14342 started
[15-Sep-2021 15:14:39] NOTICE: [pool www] child 26275 exited with code 0 after 7821.893523 seconds from start
[15-Sep-2021 15:14:39] NOTICE: [pool www] child 15539 started           

      php worker程序頻繁地挂掉和拉起,查了很多資料,各種方法嘗試也沒解決,最後不得已去嘗試方法C。

方法C

      在網上找到了兩個可以實作sm3的類庫

      1.OneSm 類庫,但是我看有同胞的文章中說用這個類庫加密後有時候得到的結果不準确,而且加密長字元串的時候速度比較慢。于是乎,我就沒有去嘗試。

      2.SM3-PHP 類庫,簡介詳盡,并且作者字裡行間盡顯真誠和專業。

PHP實作國密SM3算法

      我就按照簡介方法內建到項目中,果然沒讓我失望,完美運作,nice!