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?

1

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

2 Comments

This is too complicated to get it actually working. I hope to have something simpler, doesn't have to be super secured.
@Pinch - If you want a simple solution, use SSL.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.