Table of Contents
回复内容:
Home Backend Development PHP Tutorial 加密解密 - Java Aes 类,可否用 php 实现,求助于懂 Java 代码的 php 程序猿

加密解密 - Java Aes 类,可否用 php 实现,求助于懂 Java 代码的 php 程序猿

Jun 06, 2016 pm 08:31 PM
aes java php encrypt and decode

Java 代码:

<code>import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESSecurityUtil {

    private static final String AES = "AES";  
    private static final String CHARSET_NAME = "utf-8";  


    private static SecretKeySpec getKey(String password) throws NoSuchAlgorithmException{  

        KeyGenerator kgen = KeyGenerator.getInstance(AES);  
        SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes());
        kgen.init(128, random);    

        SecretKey secretKey = kgen.generateKey();  
        byte[] enCodeFormat = secretKey.getEncoded();    
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);   
        return key;  
    }  


    public static String encode(String str, String password)  
    {  
        byte[] arr = encodeToArr(str, password);  
        return byteArrToString(arr);  
    }  


    private static byte[] encodeToArr(String str, String password)  
    {  
        try
        {  
            Cipher cipher = Cipher.getInstance(AES);
            byte[] byteContent = str.getBytes(CHARSET_NAME);  

            cipher.init(Cipher.ENCRYPT_MODE, getKey(password));
            byte[] result = cipher.doFinal(byteContent);    
            return result;  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }    
        return null;  
    }  


    public static String decode(String hexStr, String password){  
        byte[] arr = string2ByteArr(hexStr);  
        return decode(arr, password);  
    }  


    private static String decode(byte[] arr, String password)  {  
        try{  

            Cipher cipher = Cipher.getInstance(AES);  
            cipher.init(Cipher.DECRYPT_MODE, getKey(password));

            byte[] result = cipher.doFinal(arr);  
            return new String(result, CHARSET_NAME);  
        }catch (Exception e){  
            e.printStackTrace();  
        }  
        return null;  
    }  



    private static String byteArrToString(byte[] arr)  {  
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i <arr.length i string s="Integer.toString(arr[i]" if sb.append return sb.tostring private static byte string2bytearr str="0123456789ABCDEF" arr="new" for char s1="s.charAt(i" s2="s.charAt(i" int tmp1="str.indexOf(s1)" tmp2="str.indexOf(s2);" public void main args throws exception system.out.println keystr="UITN25LMUQC436IM" plaintext="this is a string will be AES_Encrypt" enctext="encode(plainText,keyStr);" decstring="decode(encText,keyStr);"></arr.length></code>
Copy after login
Copy after login

背景:对方平台语言是Java,参数必须加密,返回数据也是加密后返回,我这边语言是php
问题:这个Java aes 类,能否用php实现,如果能实现,应该如何实现,请指点。

我写的php代码:

<code><?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 Util_AesEncrypt {

    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, $key) {
        $blockSize = mcrypt_get_block_size($this->_cipher, $this-&gt;_mode);
        $paddedData = $this-&gt;_pkcs5Pad($encrypt, $blockSize);
        $ivSize = mcrypt_get_iv_size($this-&gt;_cipher, $this-&gt;_mode);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        $encrypted = mcrypt_encrypt($this-&gt;_cipher, $key, $paddedData, $this-&gt;_mode, $iv);
        return bin2hex($encrypted);
    }

    public function decrypt($decrypt, $key) {
        $decoded = hex2bin($decrypt);
        $blockSize = mcrypt_get_iv_size($this-&gt;_cipher, $this-&gt;_mode);
        $iv = mcrypt_create_iv($blockSize, MCRYPT_RAND);
        $decrypted = mcrypt_decrypt($this-&gt;_cipher, $key, $decoded, $this-&gt;_mode, $iv);
        return $this-&gt;_pkcs5Unpad($decrypted);
    }
}

$keyStr = 'UITN25LMUQC436IM';
$plainText = 'this is a string will be AES_Encrypt';
$aes = new Util_AesEncrypt();
$encText = $aes-&gt;encrypt($plainText, $keyStr);
$decString = $aes-&gt;decrypt($encText, $keyStr);

echo $encText, "\n", $decString;
</code>
Copy after login
Copy after login

两者运行结果很大差异,并且也没法互相加密解密,应如何改正?

回复内容:

Java 代码:

<code>import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESSecurityUtil {

    private static final String AES = "AES";  
    private static final String CHARSET_NAME = "utf-8";  


    private static SecretKeySpec getKey(String password) throws NoSuchAlgorithmException{  

        KeyGenerator kgen = KeyGenerator.getInstance(AES);  
        SecureRandom random=SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(password.getBytes());
        kgen.init(128, random);    

        SecretKey secretKey = kgen.generateKey();  
        byte[] enCodeFormat = secretKey.getEncoded();    
        SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);   
        return key;  
    }  


    public static String encode(String str, String password)  
    {  
        byte[] arr = encodeToArr(str, password);  
        return byteArrToString(arr);  
    }  


    private static byte[] encodeToArr(String str, String password)  
    {  
        try
        {  
            Cipher cipher = Cipher.getInstance(AES);
            byte[] byteContent = str.getBytes(CHARSET_NAME);  

            cipher.init(Cipher.ENCRYPT_MODE, getKey(password));
            byte[] result = cipher.doFinal(byteContent);    
            return result;  
        }  
        catch (Exception e)  
        {  
            e.printStackTrace();  
        }    
        return null;  
    }  


    public static String decode(String hexStr, String password){  
        byte[] arr = string2ByteArr(hexStr);  
        return decode(arr, password);  
    }  


    private static String decode(byte[] arr, String password)  {  
        try{  

            Cipher cipher = Cipher.getInstance(AES);  
            cipher.init(Cipher.DECRYPT_MODE, getKey(password));

            byte[] result = cipher.doFinal(arr);  
            return new String(result, CHARSET_NAME);  
        }catch (Exception e){  
            e.printStackTrace();  
        }  
        return null;  
    }  



    private static String byteArrToString(byte[] arr)  {  
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i <arr.length i string s="Integer.toString(arr[i]" if sb.append return sb.tostring private static byte string2bytearr str="0123456789ABCDEF" arr="new" for char s1="s.charAt(i" s2="s.charAt(i" int tmp1="str.indexOf(s1)" tmp2="str.indexOf(s2);" public void main args throws exception system.out.println keystr="UITN25LMUQC436IM" plaintext="this is a string will be AES_Encrypt" enctext="encode(plainText,keyStr);" decstring="decode(encText,keyStr);"></arr.length></code>
Copy after login
Copy after login

背景:对方平台语言是Java,参数必须加密,返回数据也是加密后返回,我这边语言是php
问题:这个Java aes 类,能否用php实现,如果能实现,应该如何实现,请指点。

我写的php代码:

<code><?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 Util_AesEncrypt {

    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, $key) {
        $blockSize = mcrypt_get_block_size($this->_cipher, $this-&gt;_mode);
        $paddedData = $this-&gt;_pkcs5Pad($encrypt, $blockSize);
        $ivSize = mcrypt_get_iv_size($this-&gt;_cipher, $this-&gt;_mode);
        $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
        $encrypted = mcrypt_encrypt($this-&gt;_cipher, $key, $paddedData, $this-&gt;_mode, $iv);
        return bin2hex($encrypted);
    }

    public function decrypt($decrypt, $key) {
        $decoded = hex2bin($decrypt);
        $blockSize = mcrypt_get_iv_size($this-&gt;_cipher, $this-&gt;_mode);
        $iv = mcrypt_create_iv($blockSize, MCRYPT_RAND);
        $decrypted = mcrypt_decrypt($this-&gt;_cipher, $key, $decoded, $this-&gt;_mode, $iv);
        return $this-&gt;_pkcs5Unpad($decrypted);
    }
}

$keyStr = 'UITN25LMUQC436IM';
$plainText = 'this is a string will be AES_Encrypt';
$aes = new Util_AesEncrypt();
$encText = $aes-&gt;encrypt($plainText, $keyStr);
$decString = $aes-&gt;decrypt($encText, $keyStr);

echo $encText, "\n", $decString;
</code>
Copy after login
Copy after login

两者运行结果很大差异,并且也没法互相加密解密,应如何改正?

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

How To Set Up Visual Studio Code (VS Code) for PHP Development

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

How do you parse and process HTML/XML in PHP?

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Break or return from Java 8 stream forEach?

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

PHP Program to Count Vowels in a String

Java Made Simple: A Beginner's Guide to Programming Power Java Made Simple: A Beginner's Guide to Programming Power Oct 11, 2024 pm 06:30 PM

Java Made Simple: A Beginner's Guide to Programming Power

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Create the Future: Java Programming for Absolute Beginners

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Java Program to Find the Volume of Capsule

See all articles