Posts Tagged mcrypt

Encrypt with PHP – Decrypt with Java

For security reason, I wanted to encrypt the data transferred between PHP web services and a Java application. But the problem was to encrypt the data with PHP in a way that it is possible to decrypt it using Java.

It obviously exists a lot of ways of doing this. But here is the way I choose:

  • Use a secret key and an initialisation vector for the encryption and decryption
  • Use the mcrypt PHP module for the encryption
  • Use the javax.crypto Java package for the decryption

Please find below the PHP code for the encryption:

function encrypt($message, $initialVector, $secretKey) {
    return base64_encode(
        mcrypt_encrypt( 
            MCRYPT_RIJNDAEL_128,
            md5($secretKey),
            $message,  
            MCRYPT_MODE_CFB,
            $initialVector
        )
    );
}

And please see below the Java code for the decryption:

public static String md5(String input) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] messageDigest = md.digest(input.getBytes());
    BigInteger number = new BigInteger(1, messageDigest);
    return number.toString(16);
}

public String decrypt(String encryptedData, String initialVectorString, String secretKey) {
    String decryptedData = null;
    try {
        SecretKeySpec skeySpec = new SecretKeySpec(md5(secretKey).getBytes(), "AES");
        IvParameterSpec initialVector = new IvParameterSpec(initialVectorString.getBytes());
        Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, initialVector);
        byte[] encryptedByteArray = (new org.apache.commons.codec.binary.Base64()).decode(encryptedData.getBytes());
        byte[] decryptedByteArray = cipher.doFinal(encryptedByteArray);
        decryptedData = new String(decryptedByteArray, "UTF8");
    } catch (Exception e) {
        LOGGER.debug("Problem decrypting the data", e);
    }
    return decryptedData;
}

EDIT: The line number.toString(16) of the md5 method needs to be replaced by String.format("%032x", number). See this article for more details.

, , , , ,

45 Comments