-3
我在java中有這樣的代碼,我需要在PHP中的等效,我也有這個代碼在.NET中,並且工作完美,但我需要在PHP中。這是在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");
}
看[這個Mcrypt庫(http://php.net/manual/en/ref .mcrypt.php)。類似[mcrypt-encrypt](http://php.net/manual/en/function.mcrypt-encrypt.php)/ [mcrypt-decrypt](http://php.net/manual/en/function.mcrypt -decrypt.php)應該完成這項工作。您可能還需要[pack](http://php.net/manual/en/function.pack.php)來處理二進制數據。 –
最好不要使用mcrypt,它是放棄的,多年沒有更新,不支持標準的PKCS#7(néePKCS#5)填充,只有非標準的null填充甚至不能用於二進制數據。 mcrypt有很多優秀的[bug](https://sourceforge.net/p/mcrypt/bugs/)可以追溯到2003年。反而考慮使用[defuse](https://github.com/defuse/php-encryption)它正在維護和正確。 – zaph
@AlexBlex請注意,OP的代碼指定了「PKCS5Padding」,而mcrypt不支持「PKCS5Padding」。 – zaph