我在java中有这个代码,我需要PHP中的等价物,我在.NET中也有这个代码并且工作完美,但我需要PHP。
public static String decrypt(String pValor) throws UnsupportedEncodingException {
byte vBytesDecodificados[] = null;
try {
KeySpec vClave = new DESKeySpec("MyKey".getBytes("UTF-8"));
SecretKey vClaveSecreta = SecretKeyFactory.getInstance("DES").generateSecret(vClave);
IvParameterSpec iv = new IvParameterSpec(Hex.decodeHex("1234567890ABCDEF".toCharArray()));
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, vClaveSecreta, iv);
vBytesDecodificados = cipher.doFinal(Base64.decodeBase64(pValor.getBytes()));
} catch (Exception e) {
}
return new String(vBytesDecodificados, "UTF-8");
}
public static String encrypt(String pValor) throws UnsupportedEncodingException {
byte vBytesCodificados[] = null;
try {
KeySpec vClave = new DESKeySpec("MyKey".getBytes("UTF-8"));
SecretKey vClaveSecreta = SecretKeyFactory.getInstance("DES").generateSecret(vClave);
IvParameterSpec iv = new IvParameterSpec(Hex.decodeHex("1234567890ABCDEF".toCharArray()));
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, vClaveSecreta, iv);
byte[] utf8 = pValor.getBytes("UTF8");
byte[] enc = cipher.doFinal(utf8);
vBytesCodificados = Base64.encodeBase64(enc);
} catch (Exception e) {
}
return new String(vBytesCodificados, "UTF-8");
}
答案 0 :(得分:0)
我已经知道使用此方法并不安全,但这是解决方案:
class Encriptacion {
private $iv = '1234567890ABCDEF';
private $key = 'MyKey';
function encode($str) {
$size = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
$str = $this->pkcs5Pad($str, $size);
$aaa = mcrypt_cbc(MCRYPT_DES, $this->key, $str, MCRYPT_ENCRYPT, $this->hex2bin($this->iv));
$ret = base64_encode($aaa);
return $ret;
}
function decode($str) {
$str = base64_decode($str);
$str = mcrypt_cbc(MCRYPT_DES, $this->key, $str, MCRYPT_DECRYPT, $this->hex2bin($this->iv));
$str = $this->pkcs5Unpad($str);
return $str;
}
function hex2bin($hexData) {
$binData = "";
for ($i = 0; $i < strlen($hexData); $i += 2) {
$binData .= chr(hexdec(substr($hexData, $i, 2)));
}
return $binData;
}
function pkcs5Pad($text, $blocksize) {
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
function pkcs5Unpad($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);
}
}