希望这可以帮助您入门。缺少错误处理并且密钥是硬编码的。生产质量代码需要解决这两个问题。在 Java 端,您可以使用 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);
}
在 PHP 方面,您将需要 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);
}
?>
函数pkcs5_unpad 是从here 复制而来的,因为PHP Mcrypt 似乎不包含对PKCS5 填充的支持。 Java 代码在数据前面加上用于加密的初始化向量。随后 PHP 代码将其拆分为两部分,初始化向量和加密数据。
此代码在 CBC 模式下使用 128 位 AES (Rijndael),对于大多数用途来说应该足够安全。除了简单的加密,我建议使用HMAC 描述的here 以确保数据不被篡改。要在 Java 中执行 HMAC,请使用 Mac 类。对于 PHP,请参阅Mhash。