Java Aes类转换为php [英] Java Aes class convert to php

查看:55
本文介绍了Java Aes类转换为php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java代码:

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] + 128, 16);  
            if (s.length() == 1){  
                s = "0" + s;  
            }    
            sb.append(s);  
        }  

        return sb.toString().toUpperCase();  
    }  


    private static byte[] string2ByteArr(String s)  {  
        s = s.toUpperCase();  
        String str = "0123456789ABCDEF";    
        byte[] arr = new byte[s.length() / 2];   
        for (int i = 0; i <arr.length; i++){  
            char s1 = s.charAt(i * 2);  
            char s2 = s.charAt(i * 2 + 1);    
            int tmp1 = str.indexOf(s1) * 16;  
            int tmp2 = str.indexOf(s2);    
            arr[i] = (byte) (tmp1 + tmp2 - 128);  
        }    
        return arr;  
    }  

    public static void main(String[] args) throws Exception  {
        System.out.println(decode("03AB8A3B85AFDD3926850B14C1BFF608", "imcc"));
        String keyStr = "UITN25LMUQC436IM";  

        String plainText = "this is a string will be AES_Encrypt";

        String encText = encode(plainText,keyStr);
        String decString = decode(encText,keyStr); 

        System.out.println(encText); 
        System.out.println(decString); 
    }
}

该类可以转换为php代码以实现加密和解密吗?我认为问题在于 getKey 方法无法在php中实现.

Does the class can turn into a php code to achieve encryption and decryption ? I think the problem is that the getKey method can not achieve in php.

由平台端提供的Java类,不需要进行更改.

This Java class, provided by the platform side, can not require making changes.

请告诉我问题出在哪里?

Please tell me where the problem is?

谢谢

附加...我的PHP代码:

Append ...my 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;

不同的加密结果

推荐答案

JAVA getKey()函数将从使用 SHA1PRNG 的密码中获取128位密钥,您可以使用此功能从密码获取密钥的PHP代码:

The JAVA getKey() function will get 128bit key from password use SHA1PRNG, you can use this PHP code to get key from password:

$key = substr(openssl_digest(openssl_digest($password, 'sha1', true), 'sha1', true), 0, 16);

在这种情况下,我也花了很多时间,祝你好运.

I also spent a lot of time in this case, Good Luck.

这篇关于Java Aes类转换为php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆