0

现在有个java的加解密程序,需要改成php的方法来实现

现在有对方的java加密程序程序,但是百度找的php加密程序得出的加过总是对不上号

相关代码

java的是


package com.picc.web.common.utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * AES加密
 *
 * @author 夏祥
 *
 */
public class AESUtils {

    public static final String AESKey = "key2019";

    /**
     * AES加密方法
     *
     * @param content
     * @return
     */
    public static String encrypt(String content) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            kgen.init(128, new SecureRandom(AESKey.getBytes()));// 利用用户密码作为随机数初始化出
            // 加密没关系,SecureRandom是生成安全随机数序列,password.getBytes()是种子,只要种子相同,序列就一样,所以解密只要有password就行
            SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥,如果此密钥不支持编码,则返回
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("UTF-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化为加密模式的密码器
            byte[] result = cipher.doFinal(byteContent);// 加密
            return AESUtils.parseByte2HexStr(result);
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * AES解密
     *
     * @param encrypt
     * @return
     */
    public static String decrypt(String encrypt) {
        try {
            // 如果的到的是16进制密文,别忘了先转为2进制再解密
            byte[] content = AESUtils.parseHexStr2Byte(encrypt);
            KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
            kgen.init(128, new SecureRandom(AESKey.getBytes()));
            SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥
            byte[] enCodeFormat = secretKey.getEncoded();// 返回基本编码格式的密钥
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 转换为AES专用密钥
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化为解密模式的密码器
            byte[] result = cipher.doFinal(content);
            return new String(result,"UTF-8"); // 明文
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),
                    16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

   public static void main(String[] args){

        // D:\java\cs>javac -encoding UTF-8 AESUtils.java
        // D:\java\cs>java AESUtils.java

        AESUtils aes = new AESUtils();

        String encrypt_str = aes.encrypt("abc123");

        System.out.println("encrypt_str : " + encrypt_str);

        // String decrypt_str = aes.decrypt(encrypt_str);

        // System.out.println("decrypt_str : " + decrypt_str);

   }

}

结果是B389C9F38EFF2F97F22F764CC25FCB2C

然后找到了两个php的AES加密方法

class CryptAES
{
    protected $cipher     = MCRYPT_RIJNDAEL_128;
    protected $mode       = MCRYPT_MODE_ECB;
    protected $pad_method = null;
    protected $secret_key = '';
    protected $iv         = '';

    public function set_cipher($cipher)
    {
        $this->cipher = $cipher;
    }

    public function set_mode($mode)
    {
        $this->mode = $mode;
    }

    public function set_iv($iv)
    {
        $this->iv = $iv;
    }

    public function set_key($key)
    {
        $this->secret_key = $key;
    }

    public function require_pkcs5()
    {
        $this->pad_method = 'pkcs5';
    }

    protected function pad_or_unpad($str, $ext)
    {
        if (is_null($this->pad_method)) {
            return $str;
        } else {
            $func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
            if (is_callable($func_name)) {
                $size = mcrypt_get_block_size($this->cipher, $this->mode);
                return call_user_func($func_name, $str, $size);
            }
        }
        return $str;
    }

    protected function pad($str)
    {
        return $this->pad_or_unpad($str, '');
    }

    protected function unpad($str)
    {
        return $this->pad_or_unpad($str, 'un');
    }

    public function encrypt($str)
    {
        $str = $this->pad($str);
        $td  = mcrypt_module_open($this->cipher, '', $this->mode, '');

        if (empty($this->iv)) {
            $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        } else {
            $iv = $this->iv;
        }

        mcrypt_generic_init($td, $this->secret_key, $iv);
        $cyper_text = mcrypt_generic($td, $str);
        $rt         = base64_encode($cyper_text);
        //$rt = bin2hex($cyper_text);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);

        return $rt;
    }

    public function decrypt($str)
    {
        $td = mcrypt_module_open($this->cipher, '', $this->mode, '');

        if (empty($this->iv)) {
            $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        } else {
            $iv = $this->iv;
        }

        mcrypt_generic_init($td, $this->secret_key, $iv);
        //$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
        $decrypted_text = mdecrypt_generic($td, base64_decode($str));
        $rt             = $decrypted_text;
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);

        return $this->unpad($rt);
    }

    public static function hex2bin($hexdata)
    {
        $bindata = '';
        $length  = strlen($hexdata);
        for ($i = 0; $i < $length; $i += 2) {
            $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
        }
        return $bindata;
    }

    public static function pkcs5_pad($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    public static function pkcs5_unpad($text)
    {
        $pad = ord($text{strlen($text) - 1});
        if ($pad > strlen($text)) {
            return false;
        }

        if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
            return false;
        }

        return substr($text, 0, -1 * $pad);
    }
}

$keyStr    = 'key2019';
$plainText = 'abc123';

$aes = new CryptAES();
$aes->set_key($keyStr);
$aes->require_pkcs5();
$encText   = $aes->encrypt($plainText);
$decString = $aes->decrypt($encText);

// D:\www\cs\encrypt>php cryptAES.php

echo $encText, "\n".'<hr />', $decString;

结果是 GIjvEh210Q2EUux+2YxEtQ==

另一个是

/**
 * AES/CBC/PKCS5Padding Encrypter
 *
 * @param $str
 * @param $key
 * @return string
 */
function encrypt($str, $key)
{
    $zeroPack = pack('i*', 0);
    $iv       = str_repeat($zeroPack, 4);
    mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
    $key = md5($key);
    // $key = substr($key, 8, 16);
    $encryptedStr = mcrypt_encrypt(
        MCRYPT_RIJNDAEL_128,
        hex2bin($key),
        pkcs5_pad($str, mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
        MCRYPT_MODE_CBC,
        $iv)
    ;
    return bin2hex($encryptedStr);
}

/**
 * AES/CBC/PKCS5Padding Decrypter
 *
 * @param $encryptedStr
 * @param $key
 * @return string
 */
function decrypt($encryptedStr, $key)
{
    $zeroPack = pack('i*', 0);
    $iv       = str_repeat($zeroPack, 4);
    return pkcs5_unpad(mcrypt_decrypt(
        MCRYPT_RIJNDAEL_128,
        hex2bin(md5($key)),
        hex2bin($encryptedStr),
        MCRYPT_MODE_CBC,
        $iv
    ));
}

function pkcs5_pad($text, $blocksize)
{
    $pad = $blocksize - (strlen($text) % $blocksize);
    return $text . str_repeat(chr($pad), $pad);
}

function pkcs5_unpad($text)
{
    $pad = ord($text{strlen($text) - 1});
    if ($pad > strlen($text)) {
        return false;
    }

    if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
        return false;
    }

    return substr($text, 0, -1 * $pad);
}

$key = 'key2019';

$str = 'abc123';

// D:\www\cs\encrypt>php aes_cbc_mcrypt.php

$encrypt = encrypt($str, $key);

$decrypt = decrypt(encrypt($str, $key), $key);

// var_dump($str, $encrypt, $decrypt);

echo $encrypt, "\n".'<hr />', $decrypt;

结果是 86e373b92cf0be2e9a005fa3fd05e98a

希望大佬给个php的返回值能和java相等的程序,谢谢啦

2019-05-16 提问
2 个回答
1

已采纳

看了下,明天帮你解决,来得及么

0

楼主解决办法参考的哪篇文章 能给个链接吗

撰写答案

推广链接