php实现sm3 hash加密和文件签名示例代码

代码语言:php

所属分类:加密解密

代码描述:php实现sm3 hash加密和文件签名示例代码

代码标签: php sm3 hash 加密 文件 签名 示例 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?php
class Sm3
{
    private $IV      = '7380166f4914b2b9172442d7da8a0600a96f30bc163138aae38dee4db0fb0e4e';
    private $LEN     = 512;
    private $STR_LEN = 64;

    public function sign($str)
    {
        $l   = strlen($str) * 8;
        $k   = $this->getK($l);
        $bt  = $this->getB($k);
        $str = $str . $bt . pack('J', $l);

        $count = strlen($str);
        $l     = $count / $this->STR_LEN;
        $vr    = hex2bin($this->IV);
        for ($i = 0; $i < $l; $i++) {
            $vr = $this->cf($vr, substr($str, $i * $this->STR_LEN, $this->STR_LEN));
        }
        return bin2hex($vr);

    }

    private function getK($l)
    {
        $v = $l % $this->LEN;
        return $v + $this->STR_LEN < $this->LEN
            ? $this->LEN - $this->STR_LEN - $v - 1
            : ($this->LEN * 2) - $this->STR_LEN - $v - 1;
    }

    private function getB($k)
    {
        $arg = [128];
        $arg = array_merge($arg, array_fill(0, intval($k / 8), 0));
        return pack('C*', ...$arg);
    }

    public function signFile($file)
    {
        $l  = filesize($file) * 8;
        $k  = $this->getK($l);
        $bt = $this->getB($k) . pack('J', $l);

        $hd  = fopen($file, 'r');
        $vr  = hex2bin($this->IV);
        $str = fread($hd, $this->STR_LEN);
        if ($l > $this->LEN - $this->STR_LEN - 1) {
            do {
                $vr  = $this->cf($vr, $str);
                $str = fread($hd, $this->STR_LEN);
            } while (!feof($hd));
        }

        $str   = $str . $bt;
        $count = strlen($str) * 8;
        $l     = $count / $this->LEN;
        for ($i = 0; $i < $l; $i++) {
            $vr = $this->cf($vr, substr($str, $i * $this->STR_LEN, $this->STR_LEN));
        }
        return bin2hex($vr);
    }


    private function t($i)
    {
        return $i < 16 ? 0x79cc4519 : 0x7a879d8a;
    }

    private function cf($ai, $bi)
    {
        $wr = array_values(unp.........完整代码请登录后点击上方下载按钮下载查看

网友评论0