轻源码

  • QingYuanMa.com
  • 全球最大的互联网技术和资源下载平台
搜索
猜你喜欢
查看: 6347|回复: 0

php中关于AES加密对应Java中的SHA1PRNG方式加密的实例详解

[复制链接]

0

主题

0

帖子

1万

积分

钻石会员

Rank: 8Rank: 8

积分
17452
QQ
发表于 2020-3-30 03:30 | 显示全部楼层 |阅读模式
做对接的时候,服务商做的AES加密通过SHA1PRNG算法(只要password一样,每次生成的数组都是一样的,所以可以用来做加密解密的key)进行了又一次加密,搞了好几个小时,直接看对应的代码吧,可以参考一下,只有Java的加密源码


private static byte[] encrypt(byte[] byteContent, byte[] password) throws Exception
  {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    secureRandom.setSeed(password);
    kgen.init(128, secureRandom);
    SecretKey secretKey = kgen.generateKey();    byte[] enCodeFormat = secretKey.getEncoded();
    SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(1, key);    byte[] result = cipher.doFinal(byteContent);    return result;
  }


  private function _pkcs5Pad($text, $blockSize)
    {
        $pad = $blockSize - (strlen($text) % $blockSize);
        return $text . str_repeat(chr($pad), $pad);
    }

    private function _pkcs5Unpad($text)
    {
        $end = substr($text, -1);
        $last = ord($end);
        $len = strlen($text) - $last;
        if(substr($text, $len) == str_repeat($end, $last))
        {
            return substr($text, 0, $len);
        }
        return false;
    }

    public function encrypt($encrypt, $key)
    {
        $blockSize = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $paddedData = $this->_pkcs5Pad($encrypt, $blockSize);
        $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        $key2 = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
        $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key2, $paddedData, MCRYPT_MODE_ECB, $iv);
        return base64_encode($encrypted);
    }

    public function decrypt($decrypt, $key)
    {
        $decoded = $this->hex2bin($decrypt);
        $blockSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($blockSize, MCRYPT_RAND);
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $decoded, MCRYPT_MODE_ECB, $iv);
        return $this->_pkcs5Unpad($decrypted);
    }

    function hex2bin($str)
    {
        $sbin = "";
        $len = strlen($str);
        for($i = 0; $i < $len; $i += 2)
        {
            $sbin .= pack("H*", substr($str, $i, 2));
        }

        return $sbin;
    }

回复

使用道具 举报

轻源码让程序更轻更快

QingYuanMa.com

工作时间 周一至周六 8:00-17:30

客服QQ点击咨询

微信公众号

APP客户端

Copyright © 2016-2019 https://www.qingyuanma.com/ 鲁ICP备17014494号

快速回复 返回顶部 返回列表