1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| require_once __DIR__ . '/../vendor/autoload.php';
use Rtgm\sm\RtSm2; use Rtgm\sm\RtSm4;
class ApplyHJS {
private const API_URL = 'api.xxx.com'; private const API_PRE = '/xxx'; private const USER_CODE = 'xxx'; private const PK = 'xxx'; private const PUK = 'xxx'; private const BUK = 'xxxx';
private $sm4; private $sm2; private $userId;
function __construct() {
$this->sm2 = new RtSm2("base64"); $this->sm4 = new RtSm4(base64_decode(self::BUK)); $this->userId = sprintf('%-016s', self::USER_CODE); }
function signAndCrypt($data) {
$privateKey = base64_decode(self::PK); $privateKey = unpack("H*", $privateKey)[1]; $sign = $this->sm2->doSign($data, $privateKey, $this->userId); $sign = base64_decode($sign); $point = \FG\ASN1\ASNObject::fromBinary($sign)->getChildren(); $pointX = $this->formatHex($point[0]->getContent()); $pointY = $this->formatHex($point[1]->getContent()); $sign = $pointX . $pointY; $sign = base64_encode(hex2bin($sign)); $data = str_replace('__signature_sigdat__', $sign, $data); $sm4 = new RtSm4(base64_decode(self::BUK)); $encryptData = $sm4->encrypt($data, 'sm4-cbc', $this->userId, "base64");
return $encryptData; }
function decryptSign($decryptData) {
$json = $this->sm4->decrypt($decryptData, $type = 'sm4-cbc', $this->userId, $formatInput = 'base64'); $data = json_decode($json, true);
return $data; }
function formatHex($dec) { $hex = gmp_strval(gmp_init($dec, 10), 16); $len = strlen($hex); if ($len == 64) { return $hex; } if ($len < 64) { $hex = str_pad($hex, 64, "0", STR_PAD_LEFT); } else { $hex = substr($hex, $len - 64, 64); } return $hex; }
}
|