I have this Java code to encrypt a data using a key:
static String IV = "\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000";
static String key = "somerandomkey0987";
public static String encrypt(String myData, String key) throws Exception {
for(int i = 0; i < myData.length() % 16; ++i) {
myData = myData + "\u0000";
}
Cipher encripta = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
encripta.init(1, key, new IvParameterSpec(IV.getBytes("UTF-8")));
return byteToHex(encripta.doFinal(myData.getBytes("UTF-8")));
}
public static String byteToHex(byte[] hash) {
Formatter formatter = new Formatter();
byte[] var2 = hash;
int var3 = hash.length;
for(int var4 = 0; var4 < var3; ++var4) {
byte b = var2[var4];
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
This is working as expected. Now I need a PHP version of that, but I'm beginer on PHP. How can this method should be? I tried this:
public function encrypt($data = '', $key = NULL) {
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($data, $cipher, $key, 0, $iv);
return bin2hex($ciphertext_raw);
}
source https://stackoverflow.com/questions/68988305/php-version-of-cipher-and-secretkeyspec
Comments
Post a Comment