Java和PHP都是應用廣泛的編程語言,而AES是一種高級加密標準,用于加密和解密數字數據流。下面將介紹Java和PHP如何使用AES來實現數據加密和解密。
Java實現AES加密和解密
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class AESUtil { private static final String ALGORITHM = "AES/ECB/PKCS5Padding"; public static byte[] encrypt(String key, String str) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); return cipher.doFinal(str.getBytes()); } public static String decrypt(String key, byte[] bytes) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES"); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); return new String(cipher.doFinal(bytes)); } public static void main(String[] args) throws Exception { String key = "key1234567890"; String str = "Hello, world!"; byte[] encrypted = encrypt(key, str); System.out.println("Encrypted data: " + new String(encrypted)); String decrypted = decrypt(key, encrypted); System.out.println("Decrypted data: " + decrypted); } }
PHP實現AES加密和解密
function aes_encrypt($key, $str) { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB, $iv); return base64_encode($encrypted); } function aes_decrypt($key, $str) { $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($str), MCRYPT_MODE_ECB, $iv); return rtrim($decrypted, "\0"); } $key = "key1234567890"; $str = "Hello, world!"; $encrypted = aes_encrypt($key, $str); echo "Encrypted data: $encrypted\n"; $decrypted = aes_decrypt($key, $encrypted); echo "Decrypted data: $decrypted\n";