加密解密 - Java Aes 类,可否用 php 实现,求助于懂 Java 代码的 php 程序猿
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>
背景:对方平台语言是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->_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, $key) { $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); } } $keyStr = 'UITN25LMUQC436IM'; $plainText = 'this is a string will be AES_Encrypt'; $aes = new Util_AesEncrypt(); $encText = $aes->encrypt($plainText, $keyStr); $decString = $aes->decrypt($encText, $keyStr); echo $encText, "\n", $decString; </code>
两者运行结果很大差异,并且也没法互相加密解密,应如何改正?
回复内容:
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>
背景:对方平台语言是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->_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, $key) { $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); } } $keyStr = 'UITN25LMUQC436IM'; $plainText = 'this is a string will be AES_Encrypt'; $aes = new Util_AesEncrypt(); $encText = $aes->encrypt($plainText, $keyStr); $decString = $aes->decrypt($encText, $keyStr); echo $encText, "\n", $decString; </code>
两者运行结果很大差异,并且也没法互相加密解密,应如何改正?

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.
