Java encrypt AES, PHP decrypt AES

♀尐吖头ヾ 提交于 2019-12-21 06:08:28

问题


I was looking for a way to encrypt a string in Java, and decrypt it in PHP. I found this in an answer somewhere on Stackoverflow and I modified it to do the exact opposite. This is my code to encrypt in Java:

public static String encrypt(String data, String initialVectorString, String secretKey) {
        String encryptedData = null;
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(md5(secretKey).substring(0, 16).getBytes(), "AES");
            IvParameterSpec initialVector = new IvParameterSpec(initialVectorString.getBytes());
            Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, initialVector);
            byte[] encrypted = cipher.doFinal(data.getBytes());
            byte[] base64encrypted = (new org.apache.commons.codec.binary.Base64()).encode(encrypted);
            encryptedData = new String(base64encrypted, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedData;
    }

and this is my code to decrypt in PHP:

function decrypt($message, $initialVector, $secretKey) {
        return (
        mcrypt_decrypt( 
        MCRYPT_RIJNDAEL_128,
        substr(md5($secretKey), 0, 16),
        base64_decode($message),  
        MCRYPT_MODE_CFB,
        $initialVector
        )
        );
    }

The secret key and initial vector change every time. The code works for 90% of the time, but sometimes it only partially decrypts the string and the remaining characters are unreadable like this: Microsoft Windows [Version 10.0.1��× which should say Microsoft Windows [Version 10.0.14393]. Did I make any mistakes modifying the code?

EDIT: I may need to add that decrypting in Java using the code from the link above DOES work.

EDIT2: Found the answer, it was a stupid mistake, PHP got the + in a base64 encrypted string as space. Thanks for all of your help, I will still be using alot of it.

来源:https://stackoverflow.com/questions/40063250/java-encrypt-aes-php-decrypt-aes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!