java and php aes相互加密解密。

1:RSA加密算法:

1-1:Java RSA公约加密代码

    public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;

    }

1-2:等价PHP代码公约加密代码

//用公钥加密后数据,网上传输
$encrypted = "";
//PHP代码进行RSA的加密解密(用公钥加密)
openssl_public_encrypt($encKeyStr,$encrypted, $pingtaiPublicKey);
//密钥密文 换成Hex字符串
$encKey = strtoupper(bin2hex($encrypted));

2:sha256加密算法

2-1:Java代码

MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(bt);
strDes = bytes2Hex(md.digest()); // to HexString

2-2:等价PHP代码

$macStr = hash('sha256', $macStr, true);

$macStr = bin2hex($macStr);

3:AES加密解密

3-1:Java代码

    public static byte[] encrypt(String content, String password) {
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(password.getBytes("utf-8"));
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, secureRandom);
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("GBK");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
    }


    /**
     * 解密
     *
     * @param content  待解密内容
     * @param password 解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String password) {
    SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    secureRandom.setSeed(password.getBytes("utf-8"));


    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    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(Cipher.DECRYPT_MODE, key);// 初始化
    byte[] result = cipher.doFinal(content);
    return result; // 加密
    }

3-2:PHP代码

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


        return $sbin;
    }
}


class AESUtil {


    private $_cipher = MCRYPT_RIJNDAEL_128;
    private $_mode = MCRYPT_MODE_ECB;


    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, $password) {
    // 对应Java SecureRandom.getInstance("SHA1PRNG")
    $key = substr(openssl_digest(openssl_digest($password, 'sha1', true), 'sha1', true), 0, 16);
        $blockSize = mcrypt_get_block_size($this->_cipher, $this->_mode);
        $paddedData = $this->_pkcs5Pad($encrypt, $blockSize);
        $ivSize = mcrypt_get_iv_size($this->_cipher, $this->_mode);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        $encrypted = mcrypt_encrypt($this->_cipher, $key, $paddedData, $this->_mode, $iv);
        return bin2hex($encrypted);
    }


    public function decrypt($decrypt, $password) {
    $key = substr(openssl_digest(openssl_digest($password, 'sha1', true), 'sha1', true), 0, 16);
        $decoded = hex2bin($decrypt);
        $blockSize = mcrypt_get_iv_size($this->_cipher, $this->_mode);
        $iv = mcrypt_create_iv($blockSize, MCRYPT_RAND);
        $decrypted = mcrypt_decrypt($this->_cipher, $key, $decoded, $this->_mode, $iv);
        return $this->_pkcs5Unpad($decrypted);
    }
}

4:私钥加密

4-1:Java代码

    /**
     *


     * 私钥加密
     *


     *
     * @param data       源数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String privateKey)
            throws Exception {
        byte[] keyBytes = Base64.decodeBase64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

4-2:PHP代码私钥加密 

$maced="";
openssl_private_encrypt($macStr, $maced, $merPrivateKey); //私钥加密  
$mac = strtoupper(bin2hex($maced));

你可能感兴趣的:(Java)