有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中复制PHP代码

我正在尝试将以下PHP代码翻译成Java

private function _aes256_cbc_encrypt($key, $data, $iv) {
    if (32 !== strlen($key))
        $key = hash('SHA256', $key, true);
    if (16 !== strlen($iv))
        $iv = hash('MD5', $iv, true);
    $padding = 16 - (strlen($data) % 16);
    $data .= str_repeat(chr($padding), $padding);
    return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv);
}

到目前为止,这就是我在Java中所拥有的

 private String aes256_cbc_encrypt(String key, String data, String iv) throws Exception {
    if (32 != key.length())
        key = sha256(key);
    if (16 != iv.length())
        iv = md5(iv);

    char padding = (char) (16-(data.length() % 16));
    char[] paddingArray = new char[padding];
    Arrays.fill(paddingArray, padding);
    data = data + new String(paddingArray);
    String mcryptData = data;
    MCrypt mcrypt = new MCrypt();
    String encrypted = mcrypt.bytesToHex(mcrypt.encrypt(mcryptData));
    return encrypted;
}

sha256和md5方法包括:

public static String md5(String input) throws NoSuchAlgorithmException{
    String result = input;
    if(input != null) {
        MessageDigest md = MessageDigest.getInstance("MD5"); 
        md.update(input.getBytes());
        BigInteger hash = new BigInteger(1, md.digest());
        result = hash.toString(16);
        while(result.length() < 32) {
            result = "0" + result;
        }
    }
    return result;
}

public static String sha256(String input) throws NoSuchAlgorithmException{
    String result = input;
    if(input != null) {
        MessageDigest md = MessageDigest.getInstance("MD5"); 
        md.update(input.getBytes());
        BigInteger hash = new BigInteger(1, md.digest());
        result = hash.toString(16);
        while(result.length() < 32) {
            result = "0" + result;
        }
    }
    return result;
}

我正在使用的mcrypt类(我在这里找到了https://github.com/serpro/Android-PHP-Encrypt-Decrypt/blob/master/Java/src/com/serpro/library/String/MCrypt.java)是

    import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

class MCrypt {

        static char[] HEX_CHARS = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

        private String iv = "{Yr5xwjQp0:\\EC4L";
        private IvParameterSpec ivspec;
        private SecretKeySpec keyspec;
        private Cipher cipher;

        private String SecretKey = "m78gLMbPQ";

        public MCrypt()
        {
                ivspec = new IvParameterSpec(iv.getBytes());

                keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");

                try {
                        cipher = Cipher.getInstance("AES/CBC/NoPadding");
                } catch (NoSuchAlgorithmException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }

        public  byte[] encrypt(String text) throws Exception
        {
                if(text == null || text.length() == 0)
                        throw new Exception("Empty string");

                byte[] encrypted = null;

                try {
                        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
                        encrypted = cipher.doFinal(padString(text).getBytes());
                } catch (Exception e)
                {                       
                        throw new Exception("[encrypt] " + e.getMessage());
                }

                return encrypted;
        }

        public byte[] decrypt(String code) throws Exception
        {
                if(code == null || code.length() == 0)
                        throw new Exception("Empty string");

                byte[] decrypted = null;

                try {
                        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

                        decrypted = cipher.doFinal(hexToBytes(code));
                        //Remove trailing zeroes
                        if( decrypted.length > 0)
                        {
                            int trim = 0;
                            for( int i = decrypted.length - 1; i >= 0; i-- ) if( decrypted[i] == 0 ) trim++;

                            if( trim > 0 )
                            {
                                byte[] newArray = new byte[decrypted.length - trim];
                                System.arraycopy(decrypted, 0, newArray, 0, decrypted.length - trim);
                                decrypted = newArray;
                            }
                        }
                } catch (Exception e)
                {
                        throw new Exception("[decrypt] " + e.getMessage());
                }
                return decrypted;
        }      


        public static String bytesToHex(byte[] buf)
        {
            char[] chars = new char[2 * buf.length];
            for (int i = 0; i < buf.length; ++i)
            {
                chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4];
                chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F];
            }
            return new String(chars);
        }


        public static byte[] hexToBytes(String str) {
                if (str==null) {
                        return null;
                } else if (str.length() < 2) {
                        return null;
                } else {
                        int len = str.length() / 2;
                        byte[] buffer = new byte[len];
                        for (int i=0; i<len; i++) {
                                buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
                        }
                        return buffer;
                }
        }



        private static String padString(String source)
        {
          char paddingChar = 0;
          int size = 16;
          int x = source.length() % size;
          int padLength = size - x;

          for (int i = 0; i < padLength; i++)
          {
                  source += paddingChar;
          }

          return source;
        }
}

然而,这两个代码给出了不同的结果。谁能解释一下为什么会这样


共 (0) 个答案