3

I need to transfer some json data from a php server endpoint to my Android client, however I want to protect obvious reading of the data if the endpoint gets exposed. So I plan to write some simple string encryption function in the php endpoint and have my client decrypt it. Is there any readily made library to do so?

Pinch
  • 2,768
  • 3
  • 28
  • 44
  • http://stackoverflow.com/questions/6529832/rsa-encryption-in-java-decryption-in-php http://stackoverflow.com/questions/7215606/encryption-and-decryption-between-php-and-java http://stackoverflow.com/questions/8612460/how-to-decrypting-the-php-encrypted-string-using-android http://stackoverflow.com/questions/8757101/encrypt-decrypt-string-between-java-and-php http://stackoverflow.com/questions/13506077/encrypting-in-java-and-decrypting-in-php-with-phpseclib Also useful: http://stackoverflow.com/questions/16180435/how-to-decrypt-in-java-an-encrypted-response-from-php – isaacparrot Aug 31 '13 at 05:39

2 Answers2

3

Use the mcrypt PHP module for the encryption

Use the javax.crypto Java package for the decryption

encryption in PHP:

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

Decryption in JAVA:

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;
}

resource: http://www.logikdev.com/2010/11/01/encrypt-with-php-decrypt-with-java/

Balaji Kandasamy
  • 4,446
  • 10
  • 40
  • 58
0

I think you would be better off using SSL / HTTPS. That will encrypt your data, AND it will protect the client against the eventuality that someone could create a fake server to intercept traffic.

The good thing is that SSL is simpler to implement. All you need is a SSL certificate.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216