I was looking to encrypt data between a PHP server and a Java Client. Individually the code works fine and I would like to stick with OpenSSL on the PHP server.
Do
In Java 8, you cannot use
import com.sun.org.apache.xml.internal.security.utils.Base64;
Instead, you can use
import android.util.Base64;
Then you also need to change the Base64.decode and Base64.encode lines.
The complete code will be as follows (the comment from petrnohejl, about MCRYPT that has been deprecated in PHP7, taken into account):
Java:
import android.util.Base64;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class MyClass {
public static void main(String[] args) {
String data = "Arnab C";
final String enc = DarKnight.getEncrypted(data);
System.out.println("Encrypted : " + enc);
System.out.println("Decrypted : " + DarKnight.getDecrypted(enc));
}
static class DarKnight {
private static final String ALGORITHM = "AES";
private static final byte[] SALT = "tHeApAcHe6410111".getBytes();// THE KEY MUST BE SAME
private static final String X = DarKnight.class.getSimpleName();
static String getEncrypted(String plainText) {
if (plainText == null) {
return null;
}
Key salt = getSalt();
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, salt);
byte[] encodedValue = cipher.doFinal(plainText.getBytes());
return Base64.encodeToString(encodedValue,Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
throw new IllegalArgumentException("Failed to encrypt data");
}
public static String getDecrypted(String encodedText) {
if (encodedText == null) {
return null;
}
Key salt = getSalt();
try {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, salt);
byte[] decodedValue = Base64.decode(encodedText, Base64.DEFAULT);
byte[] decValue = cipher.doFinal(decodedValue);
return new String(decValue);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
static Key getSalt() {
return new SecretKeySpec(SALT, ALGORITHM);
}
}
}
PHP:
";
$dec = decrypt($enc,$GLOBALS['key']);
echo "Decrypted : ".$dec;
?>
Don't give me credits, I am just the messenger, who combined a few posts.