Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP和JAVA加密解密(AES,Base64 URL Safe)
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AesCipher {
private static String CIPHER_NAME = "AES/CBC/PKCS5PADDING";
private static int CIPHER_KEY_LEN = 16; //128 bits
public static String urlSafeBase64Encode(byte[] data) {
String encodeBase64 = Base64.encode(data);
String safeBase64Str = encodeBase64.replace('+', '-');
safeBase64Str = safeBase64Str.replace('/', '_');
safeBase64Str = safeBase64Str.replaceAll("=", "");
return safeBase64Str;
}
public static byte[] urlSafeBase64Decode(final String safeBase64Str) {
String base64Str = safeBase64Str.replace('-', '+');
base64Str = base64Str.replace('_', '/');
int mod4 = base64Str.length() % 4;
if (mod4 > 0) {
base64Str = base64Str + "====".substring(mod4);
}
return Base64.decode(base64Str);
}
/**
* AES-128-CBC加密
*
* @param key
* @param iv
* @param data
* @return
*/
public static String encrypt(String key, String iv, String data) {
try {
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
SecretKeySpec secretKey = new SecretKeySpec(fixKey(key).getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance(AesCipher.CIPHER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
byte[] encryptedData = cipher.doFinal((data.getBytes()));
String encryptedDataInBase64 = urlSafeBase64Encode(encryptedData);
String ivInBase64 = urlSafeBase64Encode(iv.getBytes("UTF-8"));
return encryptedDataInBase64 + ":" + ivInBase64;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private static String fixKey(String key) {
if (key.length() < AesCipher.CIPHER_KEY_LEN) {
int numPad = AesCipher.CIPHER_KEY_LEN - key.length();
for (int i = 0; i < numPad; i++) {
key += "0"; //0 pad to len 16 bytes
}
return key;
}
if (key.length() > AesCipher.CIPHER_KEY_LEN) {
return key.substring(0, CIPHER_KEY_LEN); //truncate to 16 bytes
}
return key;
}
/**
* AES-128-CBC解密
*
* @param key
* @param data
* @return
*/
public static String decrypt(String key, String data) {
try {
String[] parts = data.split(":");
IvParameterSpec iv = new IvParameterSpec(urlSafeBase64Decode(parts[1]));
SecretKeySpec secretKey = new SecretKeySpec(fixKey(key).getBytes(), "AES");
Cipher cipher = Cipher.getInstance(AesCipher.CIPHER_NAME);
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] decodedEncryptedData = urlSafeBase64Decode(parts[0]);
byte[] original = cipher.doFinal(decodedEncryptedData);
return new String(original);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void main(String[] args) {
String key = "9da76eb9f16e6ddf2de8eaf927d81c52"; // 128 bit key
String initVector = key.substring(0, 16); // 16 bytes IV, it is recommended to use a different random IV for every message!
String plain_text = "mima";
String encrypted = encrypt(key, initVector, plain_text);
System.out.println(encrypted);
String decrypt = decrypt(key, encrypted);
System.out.println(decrypt);
}
}
<?php
class AesCipher
{
const OPENSSL_CIPHER_NAME = "aes-128-cbc";
const CIPHER_KEY_LEN = 16; //128 bits
public static function urlSafeBase64Decode($string)
{
$data = str_replace(array('-', '_'), array('+', '/'), $string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
public static function urlSafeBase64Encode($string)
{
$data = base64_encode($string);
$data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
return $data;
}
private static function fixKey($key)
{
if (strlen($key) < self::CIPHER_KEY_LEN) {
//0 pad to len 16
return str_pad("$key", self::CIPHER_KEY_LEN, "0");
}
if (strlen($key) > self::CIPHER_KEY_LEN) {
//truncate to 16 bytes
return substr($key, 0, self::CIPHER_KEY_LEN);
}
return $key;
}
/**
* aes-128-cbc加密
* @param $key
* @param $iv
* @param $data
* @return string
*/
public static function encrypt($key, $iv, $data)
{
$encodedEncryptedData = self::urlSafeBase64Encode(openssl_encrypt($data, self::OPENSSL_CIPHER_NAME, self::fixKey($key), OPENSSL_RAW_DATA, $iv));
$encodedIV = self::urlSafeBase64Encode($iv);
$encryptedPayload = $encodedEncryptedData . ":" . $encodedIV;
return $encryptedPayload;
}
/**
* aes-128-cbc解密
* @param $key
* @param $data
* @return string
*/
public static function decrypt($key, $data)
{
$parts = explode(':', $data); //Separate Encrypted data from iv.
$encrypted = $parts[0];
$iv = $parts[1];
$decryptedData = openssl_decrypt(self::urlSafeBase64Decode($encrypted), self::OPENSSL_CIPHER_NAME, self::fixKey($key), OPENSSL_RAW_DATA, self::urlSafeBase64Decode($iv));
return $decryptedData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment