Esperamos que esto pueda comenzar. El manejo de errores falta y la clave secreta está codificada. Ambos tendrían que ser tratados para el código de calidad de producción. Desde el lado de Java se puede utilizar el Java Cryptography Architecture (JCA):
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public final void testTesting() throws Exception {
final String plainText = "plain text";
final String result = encrypt(plainText);
System.out.println(result);
}
public String encrypt(final String plainText) throws Exception {
final byte[] data = plainText.getBytes("UTF-8");
final byte[] encoded = encrypt(data);
final String result = new String(encoded);
return result;
}
public byte[] encrypt(final byte[] data) throws Exception {
// this is just an example key, real code should use a properly generated shared secret
final byte[] secret = new byte[] {42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42};
final SecretKeySpec key = new SecretKeySpec(secret, "AES");
final Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, key);
final byte[] iv = encryptCipher.getIV();
final byte[] encrypted = encryptCipher.doFinal(data);
final int outputLength = encrypted.length;
final int ivLength = iv.length;
final byte[] results = new byte[outputLength + ivLength];
System.arraycopy(iv, 0, results, 0, ivLength);
System.arraycopy(encrypted, 0, results, ivLength, outputLength);
return DatatypeConverter.printBase64Binary(encoded);
}
desde el lado de PHP, usted va a necesitar Mcrypt.
<?php
$key = base64_decode('KioqKioqKioqKioqKioqKg==');
$input = base64_decode($_GET['input']);
$plain_text = substr($input, 16);
$initialization_vector = substr($input, 0, 16);
echo pkcs5_unpad(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $plain_text, MCRYPT_MODE_CBC, $initialization_vector));
function pkcs5_unpad($text) {
$pad = ord($text{strlen($text)-1});
if ($pad > strlen($text)) {
return false;
}
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) {
return false;
}
return substr($text, 0, -1 * $pad);
}
?>
La función pkcs5_unpad
fue copiado de here ya que parece que PHP Mcrypt no incluye soporte para el relleno PKCS5. El código de Java prefija los datos con el vector de inicialización utilizado para encriptarlo. Posteriormente, el código PHP lo divide en dos, el vector de inicialización y los datos cifrados.
Este código usa 128 bit AES (Rijndael) en el modo CBC que debería ser lo suficientemente seguro para la mayoría de los usos. Además de la encriptación simple, recomiendo usar un HMAC como se describe en here para asegurar que los datos no sean alterados. Para realizar el HMAC en Java, use la clase Mac. Para PHP, vea Mhash.
Wow, sí, esto es exactamente lo que necesito. Voy a intentarlo, gracias por configurar todo esto, informaré de nuevo. – user246114