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?
Asked
Modified
12 years, 3 months ago
Viewed
4k times
Part
of PHP and Mobile Development Collectives
1
-
stackoverflow.com/questions/6529832/… stackoverflow.com/questions/7215606/… stackoverflow.com/questions/8612460/… stackoverflow.com/questions/8757101/… stackoverflow.com/questions/13506077/… Also useful: stackoverflow.com/questions/16180435/…isaacparrot– isaacparrot2013-08-31 05:39:07 +00:00Commented Aug 31, 2013 at 5:39
Add a comment
|
2 Answers
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/