Related
I tried to decrypt en encrypted string in JAVA with to code below.
SecretKey secretKey = new SecretKeySpec(build3DesKey(key), "DESede");
Cipher cipher = Cipher.getInstance("DESede");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] b = cipher.doFinal(str2ByteArray(dest));
String decoder = new String(b, "utf-8");
private static byte[] build3DesKey(String keyStr) throws Exception {
byte[] key = new byte[24];
byte[] temp = keyStr.getBytes("utf-8");
if (key.length > temp.length) {
System.arraycopy(temp, 0, key, 0, temp.length);
} else {
System.arraycopy(temp, 0, key, 0, key.length);
}
return key;
}
How can I get the same result with PHP version? I tried to write in PHP and It outputs with wrong result.
$data = '69C16E8142F2BDDE7569842BB0D68A3176624264E...';
$key = 'rpwdvbppnrvr56m123+#';
function decrypt($data, $secret)
{
//Generate a key from a hash
$key = md5(utf8_encode($secret), true);
//Take first 8 bytes of $key and append them to the end of $key.
$key .= substr($key, 0, 8);
$data = base64_decode($data);
$data = mcrypt_decrypt('tripledes', $key, $data, 'ecb');
$block = mcrypt_get_block_size('tripledes', 'ecb');
$len = strlen($data);
$pad = ord($data[$len-1]);
return substr($data, 0, strlen($data) - $pad);
}
var_dump(utf8_encode(Decrypt($data, $key)));
The build3DesKey() function expands a too short 3DES key to 24 bytes by padding the end with 0x00 values, for too long keys the end is simply truncated. build3DesKey() can be implemented in PHP as follows:
$key = substr(str_pad($key, 24, "\0"), 0, 24);
Although the str2ByteArray() function is missing, its functionality can be deduced. Since in your example the ciphertext is hexadecimal encoded, this function seems to simply perform a hex decoding. In PHP, the analog to str2ByteArray() is hex2bin().
Thus, a possible implementation for decryption is (using PHP/OpenSSL):
$key = "12345";
$ciphertext = "84b24172c57752385251d142abadbed1d9945301a3aee429ce00c1e291a605c30ad18c5e00007f6db394fc6138a2ee4c";
$key = substr(str_pad($key, 24, "\0"), 0, 24);
$plaintext = openssl_decrypt(hex2bin($ciphertext), "des-ede3", $key, OPENSSL_RAW_DATA);
print($plaintext. PHP_EOL); // The quick brown fox jumps over the lazy dog
The Java code returns the same plain text for these input data!
Differences to your code:
Your code uses the deprecated mcrypt. This should not be applied nowadays for security reasons. A better alternative is PHP/OpenSSL, which is used in the code above. Also, the implemented key derivation is wrong, e.g. it applies the digest MD5, which is not used in the Java code at all.
Security:
Even though this is probably a legacy application, a few words about security:
The key derivation build3DesKey() is insecure. If the key material is a string, it is generally not a key, but a password. Therefore a reliable key derivation function should be used, e.g. Argon2 or PBKDF2.
des-ede3 applies ECB mode, which is also insecure. Nowadays authenticated encryption, e.g. AES-GCM should be used.
3DES/TripleDES is outdated and the only not yet deprecated variant, triple-length keys or 3TDEA will be soon, and is comparatively slow. Today's standard AES should be applied here.
I am finding it difficult to convert a piece of code to php from java.
I searched on the internet about the meaning of each line of code written in my java code example but I didn't find any.
I want to understand what each line does in this particular example.
This is what I tried.
function my_aes_encrypt($key, $data) {
if(16 !== strlen($key)) $key = hash('MD5', $key, true);
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_ECB, str_repeat("\0", 16)));
}
function my_aes_decrypt($str, $key){
$str = base64_decode($str);
$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $str, MCRYPT_MODE_ECB);
$block = mcrypt_get_block_size('rijndael_128', 'ecb');
$pad = ord($str[($len = strlen($str)) - 1]);
$len = strlen($str);
$pad = ord($str[$len-1]);
return substr($str, 0, strlen($str) - $pad);
}
Convert from Java to PHP
//provided key
byte[] keyBinary = DatatypeConverter.parseBase64Binary("r/RloSflFkLj3Pq2gFmdBQ==");
SecretKey secret = new SecretKeySpec(keyBinary, "AES");
// encrypted string
byte[] bytes = DatatypeConverter.parseBase64Binary("IKWpOq9rhTAz/K1ZR0znPA==");
// iv
byte[] iv = DatatypeConverter.parseBase64Binary("yzXzUhr3OAt1A47g7zmYxw==");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
String msisdn = new String(cipher.doFinal(bytes), "UTF-8");
It would be great if you guys let me know the details of each line written in Java.
The functionalities of the Java- and the PHP-code differ significantly. First of all, the Java-code contains only the decryption part, whereas the PHP-part contains both, the encryption- and decryption part. Contrary to the Java-code, in the PHP-my_aes_decrypt-method the insecure ECB-mode (https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption) seems to be used instead of the CBC-mode and thus, no IV is involved. Less important, but nonetheless different, the key doesn't seem to be base64-encoded because it's not decoded anywhere. In addition, in the PHP-code deprecated methods like mcrypt_encrypt (http://php.net/manual/de/function.mcrypt-encrypt.php) or cryptographic weak algorithms like MD5 (https://en.wikipedia.org/wiki/MD5) are used.
If I get it right, the Java code is the reference code and you need the PHP-counterpart. Thus, I focus on the Java-code and ignore the differing and outdated PHP-code completely.
In the Java-code, the key, the data and the IV, all base64-encoded, become decoded and then, the encrypted data are decrypted using these decoded data.
A possible PHP-counterpart for the decryption could be:
<?php
$keyBinary = base64_decode('r/RloSflFkLj3Pq2gFmdBQ=='); // decode base64-encoded key in a string (internally, PHP strings are byte arrays)
$bytes = base64_decode('IKWpOq9rhTAz/K1ZR0znPA=='); // decode base64-encoded encrypted data in a string
$iv = base64_decode('yzXzUhr3OAt1A47g7zmYxw=='); // decode base64-encoded IV in a string
$msisdn = openssl_decrypt($bytes, 'AES-128-CBC', $keyBinary, OPENSSL_RAW_DATA, $iv); // decrypt data using AES-128, CBC-mode and PKCS7-Padding (default-padding)
// - when OPENSSL_RAW_DATA is specified raw data are returned, otherwise base64-encoded data (= default)
// - when OPENSSL_ZERO_PADDING is specified no padding is used, otherwise PKCS7-padding (= default)
// - The value XXX in AES-XXX-CBC is determined by the length of the key in Bit used in the Java-code,
// e.g. for a 32 Byte (256 Bit)-key AES-256-CBC has to be used.
print $msisdn."\n"; // Output: 1234567 // print decrypted data
The desired explanation for the Java-code can be found in the comments:
//provided key
byte[] keyBinary = DatatypeConverter.parseBase64Binary("r/RloSflFkLj3Pq2gFmdBQ=="); // decode base64-encoded key in a byte-array
SecretKey secret = new SecretKeySpec(keyBinary, "AES"); // create AES-key from byte-array (currently 16 Byte = 128 Bit long)
// encrypted string
byte[] bytes = DatatypeConverter.parseBase64Binary("IKWpOq9rhTAz/K1ZR0znPA=="); // decode base64-encoded encrypted data in a byte-array
// iv
byte[] iv = DatatypeConverter.parseBase64Binary("yzXzUhr3OAt1A47g7zmYxw=="); // decode base64-encoded IV in a byte-array
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // create cipher-instance for using AES in CBC-mode with PKCS5-Padding (Java counterpart to PKCS7)
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); // initialize cipher-instance for decryption with specified AES-key and IV (the latter created from corresponding byte-array)
String msisdn = new String(cipher.doFinal(bytes), "UTF-8"); // decrypt data using AES-128 (128 determined by length of used key in Bit), CBC-mode and PKCS5-Padding,
// and put them in a UTF-8 string
System.out.println(msisdn); // Output: 1234567 // print decrypted data
The PHP-encryption part could be:
<?php
$keyBinary = base64_decode('r/RloSflFkLj3Pq2gFmdBQ==');
$msisdn = '1234567'; // plain text
$iv = openssl_random_pseudo_bytes(16); // generate random IV
//$iv = base64_decode('yzXzUhr3OAt1A47g7zmYxw=='); // use this line for tests with your base64-encoded test-IV yzXzUhr3OAt1A47g7zmYxw==
$bytes = openssl_encrypt($msisdn, 'AES-128-CBC', $keyBinary, OPENSSL_RAW_DATA, $iv); // encrypt data using AES-128, CBC-mode and PKCS7-Padding (default-padding)
$ivBase64 = base64_encode($iv); // base64-encode IV
$bytesBase64 = base64_encode($bytes); // base64-encode encrypted data
print $ivBase64."\n".$bytesBase64."\n"; // print base64-encoded IV and encrypted data
I have the following Java code which was shared by one of an integration partner for their API encryption
import java.nio.ByteBuffer;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AES256 {
/**
*
* #param word
* #param keyString
* #return
* #throws Exception
*/
public static String encrypt(String word, String keyString) throws Exception {
byte[] ivBytes;
//String password = "zohokeyoct2017";
/*you can give whatever you want for password. This is for testing purpose*/
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[20];
random.nextBytes(bytes);
byte[] saltBytes = bytes;
System.out.println("salt enc:"+saltBytes.toString());
// Derive the key
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(keyString.toCharArray(), saltBytes, 65556, 256);
SecretKey secretKey = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
//encrypting the word
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(word.getBytes("UTF-8"));
//prepend salt and vi
byte[] buffer = new byte[saltBytes.length + ivBytes.length + encryptedTextBytes.length];
System.arraycopy(saltBytes, 0, buffer, 0, saltBytes.length);
System.arraycopy(ivBytes, 0, buffer, saltBytes.length, ivBytes.length);
System.arraycopy(encryptedTextBytes, 0, buffer, saltBytes.length + ivBytes.length, encryptedTextBytes.length);
return new Base64().encodeToString(buffer);
}
/**
*
* #param encryptedText
* #param keyString
* #return
* #throws Exception
*/
public static String decrypt(String encryptedText, String keyString) throws Exception {
//String password = "zohokeyoct2017";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//strip off the salt and iv
ByteBuffer buffer = ByteBuffer.wrap(new Base64().decode(encryptedText));
byte[] saltBytes = new byte[20];
buffer.get(saltBytes, 0, saltBytes.length);
byte[] ivBytes1 = new byte[16];
buffer.get(ivBytes1, 0, ivBytes1.length);
byte[] encryptedTextBytes = new byte[buffer.capacity() - saltBytes.length - ivBytes1.length];
buffer.get(encryptedTextBytes);
// Deriving the key
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(keyString.toCharArray(), saltBytes, 65556, 256);
SecretKey secretKey = factory.generateSecret(spec);
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes1));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException | BadPaddingException e) {
System.out.println("Exception"+e);
}
return new String(decryptedTextBytes);
}
public static void main (String []args) throws Exception{
String encryptedText;
encryptedText = AES256.encrypt("106_2002005_9000000106","3264324");
System.out.println("Encrypted Text:"+encryptedText);
System.out.println("Decrypted Text:"+AES256.decrypt(encryptedText,"3264324"));
}
}
And I tried couple of PHP codes which I got from stackoverflow or google. COuldnt make any of them working.
The code which I tried lately on PHP is below
class AtomAES {
public function encrypt($data = '', $key = NULL, $salt = "") {
if($key != NULL && $data != "" && $salt != ""){
$method = "AES-256-CBC";
//Converting Array to bytes
$iv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
$chars = array_map("chr", $iv);
$IVbytes = join($chars);
$salt1 = mb_convert_encoding($salt, "UTF-8"); //Encoding to UTF-8
$key1 = mb_convert_encoding($key, "UTF-8"); //Encoding to UTF-8
//SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
$hash = openssl_pbkdf2($key1,$salt1,'256','65536', 'sha1');
$encrypted = openssl_encrypt($data, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);
return bin2hex($encrypted);
}else{
return "String to encrypt, Salt and Key is required.";
}
}
public function decrypt($data="", $key = NULL, $salt = "") {
if($key != NULL && $data != "" && $salt != ""){
$dataEncypted = hex2bin($data);
$method = "AES-256-CBC";
//Converting Array to bytes
$iv = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
$chars = array_map("chr", $iv);
$IVbytes = join($chars);
$salt1 = mb_convert_encoding($salt, "UTF-8");//Encoding to UTF-8
$key1 = mb_convert_encoding($key, "UTF-8");//Encoding to UTF-8
//SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
$hash = openssl_pbkdf2($key1,$salt1,'256','65536', 'sha1');
$decrypted = openssl_decrypt($dataEncypted, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);
return $decrypted;
}else{
return "Encrypted String to decrypt, Salt and Key is required.";
}
}
}
This is the PHP code which I wanted to try but it doesnt work as expected as per the Java code.
Encrypted Text:1HO8iuSZf41RzP/gUleEJY3zhtLJVwFMnhZiphnoG0m9ss+g93Sj5SqQg0D7OsgSvUZCeX2Ck5QPpFrPxM0FE/yFE5s=
Decrypted Text:This is a sample text
KEY: NEWENCTEST
Try decrypting the above java encrypted text using the PHP code and the key, if it works then great.
If someone can help me with this it will of a great help!
TIA!
In the Java encrypt-method the (randomly generated) salt- and IV-bytes are copied together with the encryption-bytes in a single byte-array which becomes base64-encoded and which is returned then. In contrast, the PHP encrypt-method returns a hex-representation of the encryption bytes only. Thus, the information concerning the salt and IV get lost and decryption is no longer possible (unless salt and IV are reconstructed in other ways). In order to prevent this, you have to change the PHP encrypt-method as follows:
public function encrypt($data = '', $key = NULL) {
if($key != NULL && $data != ""){
$method = "AES-256-CBC";
$key1 = mb_convert_encoding($key, "UTF-8"); //Encoding to UTF-8
//Randomly generate IV and salt
$salt1 = random_bytes (20);
$IVbytes = random_bytes (16);
//SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
$hash = openssl_pbkdf2($key1,$salt1,'256','65556', 'sha1');
// Encrypt
$encrypted = openssl_encrypt($data, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);
// Concatenate salt, IV and encrypted text and base64-encode the result
$result = base64_encode($salt1.$IVbytes.$encrypted);
return $result;
}else{
return "String to encrypt, Key is required.";
}
}
Now, the parameter $result is a base64-encoded string containing the salt, IV and the encryption. By the way, the parameters $salt1 and $IVbytes are also randomly generated now (analogous to the Java encrypt-method). Morover the iteration count used for the key generation has been changed from 65536 to 65556 (analogous to the Java encrypt-method). Note: Generally, the encrypted text isn't reproducible (even in the case of the same plain text, and the same key/password) due to the random nature of salt and IV.
The Java decrypt-method decodes the base64-encoded string and then determines the three portions i.e. salt-, IV- and encryption-bytes which are necessary for decryption. The PHP decrypt-method has to be supplemented with these functionalities:
public function decrypt($data="", $key = NULL) {
if($key != NULL && $data != ""){
$method = "AES-256-CBC";
$key1 = mb_convert_encoding($key, "UTF-8");//Encoding to UTF-8
// Base64-decode data
$dataDecoded = base64_decode($data);
// Derive salt, IV and encrypted text from decoded data
$salt1 = substr($dataDecoded,0,20);
$IVbytes = substr($dataDecoded,20,16);
$dataEncrypted = substr($dataDecoded,36);
// SecretKeyFactory Instance of PBKDF2WithHmacSHA1 Java Equivalent
$hash = openssl_pbkdf2($key1,$salt1,'256','65556', 'sha1');
// Decrypt
$decrypted = openssl_decrypt($dataEncrypted, $method, $hash, OPENSSL_RAW_DATA, $IVbytes);
return $decrypted;
}else{
return "Encrypted String to decrypt, Key is required.";
}
}
Now, the parameter $dataDecoded contains the decoded base64-encoded string from which salt- ($salt1), IV- ($IVbytes) and encryption-
($dataEncrypted) bytes are derived. Morover the iteration count used for the key generation has been changed from 65536 to 65556 (analogous to the Java decrypt-method).
Test case 1: Encrypt and Decrypt with PHP
$atomAES = new AtomAES();
$encrypt = $atomAES->encrypt("This is a text...This is a text...This is a text...", "This is the password");
echo $encrypt;
$decrypt = $atomAES->decrypt($encrypt, "This is the password");
echo $decrypt;
with the result for $encrypt (which is in general different for each encryption due to the random nature of salt and IV):
6n4V9wqgsQq87HOYNRZmddnncSNyjFZZb8nSSAi681+hs+jwzDVQCugcg108iTMZLlmBB2KQ4iist+SuboFH0bnJxW6+rmZK07CiZ1Ip+8XOv6UuJPjVPxXTIny5p3QptpBGpw==
and for $decrypt:
This is a text...This is a text...This is a text...
Test case 2: Encrypt with Java, Decrypt with PHP
encryptedText = AES256.encrypt("This is a text...This is a text...This is a text...","This is the password");
System.out.println(encryptedText);
with the result for encryptedText (which is in general different for each encryption due to the random nature of salt and IV):
qfR76lc04eYAPjjqYiE1wXoraD9bI7ql41gSV/hsT/BLoJe0i0GgJnud7IXOHdcCljgtyFkXB95XibSyr/CazoMhwPeK6xsgPbQkr7ljSg8H1i17c8iWpEXBQPm0nij9qQNJ8A==
and
$decrypt = $atomAES->decrypt("qfR76lc04eYAPjjqYiE1wXoraD9bI7ql41gSV/hsT/BLoJe0i0GgJnud7IXOHdcCljgtyFkXB95XibSyr/CazoMhwPeK6xsgPbQkr7ljSg8H1i17c8iWpEXBQPm0nij9qQNJ8A==", "This is the password");
echo $decrypt;
with the result for $decrypt:
This is a text...This is a text...This is a text...
Test case 3: Encrypt with Java, Decrypt with PHP
encryptedText = AES256.encrypt("This is a sample text","NEWENCTEST");
System.out.println(encryptedText);
1HO8iuSZf41RzP/gUleEJY3zhtLJVwFMnhZiphnoG0m9ss+g93Sj5SqQg0D7OsgSvUZCeX2Ck5QPpFrPxM0FE/yFE5s=
and
$decrypt = $atomAES->decrypt("1HO8iuSZf41RzP/gUleEJY3zhtLJVwFMnhZiphnoG0m9ss+g93Sj5SqQg0D7OsgSvUZCeX2Ck5QPpFrPxM0FE/yFE5s=", "NEWENCTEST");
echo $decrypt;
with the result for $decrypt:
This is a sample text
Java AES/CBC/PKCS5PADDING function
public static String encrypt_key_data(String password, String message) {
//password = 4lt0iD3biT#2O17l8
//message = "{"key_id":"101","merchant_code":"65010A"}";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", "SunJCE");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] hashedpassword = sha.digest(password.getBytes("UTF-8"));
hashedpassword = Arrays.copyOf(hashedpassword, 16);
SecretKeySpec key = new SecretKeySpec(hashedpassword, "AES");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes("UTF-8")));
byte[] encrypted;
encrypted = cipher.doFinal(message.getBytes());
return asHex(encrypted);
}
java function resulting value = 'bc26d620be9fa0d810e31e62b00a518f79524f6142b90550b9148d50a1ab94ba55671e68f6cf3ebc44dd6af12f566ee8'
PHP AES-256-CBC function
function encrypt($password, $iv, $data) {
$password = '4lt0iD3biT#2O17l8';
$iv = 'AAAAAAAAAAAAAAAA';
$data = '{"key_id":"101","merchant_code":"65010A"}';
$encodedEncryptedData = (openssl_encrypt(($data), 'AES-256-CBC', fixKey(sha1($password)), OPENSSL_RAW_DATA, $iv));
print_r(bin2hex($encodedEncryptedData));
}
function fixKey($key) {
if (strlen($key) < 32) {
//0 pad to len 32
return str_pad("$key", 32, "0");
}
if (strlen($key) > 32) {
//truncate to 32 bytes
return substr($key, 0, 32);
}
return $key;
}
php function resulting value = 'cf20379c95a41429d4097f0ef7982c72a0d25c014cc09d93ba4a111bb9c11c38bc75d6c9f16cd9cb6545dc8c31560985'
I use same password and same IV, and i have read that AES/CBC/PKCS5PADDING is equivalent with AES-256-CBC. But why mine is resulting different result?
Please tell me where is my fault
==============================================
solved. I need to hex2bin($key) then use the key to encrypt using aes
To do AES-256 you would need a 256 bit key, but you are only providing 128 bits - both in java with:
hashedpassword = Arrays.copyOf(hashedpassword, 16);
.. and in PHP with:
if (strlen($key) > 32) {
//truncate to 32 bytes
return substr($key, 0, 32);
}
as $key is a hexstring with only 4 bit per digit (4 * 32 = 128).
As Java deterts key length from the key provided, you end up with 128 bit encryption in Java. Exactly what PHP/Openssl ends up doing is a bit unknown as you provide conflicting information. You ask for AES-256-CBC but only provides a 128 bit key.
Also, you should not use a simple SHA1 to derive keys from passwords. Instead use a key deriving function like pbkdf2, or just use an actual binary key.
I am in a situation where a JSON is encrypted in PHP's openssl_encrypt and needs to be decrypted in JAVA.
$encrypted = "...ENCRYPTED DATA...";
$secretFile = "/path/to/secret/saved/in/text_file";
$secret = base64_decode(file_get_contents($secretFile));
var_dump(strlen($secret)); // prints : int(370)
$iv = substr($encrypted, 0, 16);
$data = substr($encrypted, 16);
$decrypted = openssl_decrypt($data, "aes-256-cbc", $secret, null, $iv);
This $decrypted has correct data which is now decrypted.
Now, the problem is when I try to do same things in Java it doesn't work :(
String path = "/path/to/secret/saved/in/text";
String payload = "...ENCRYPTED DATA...";
StringBuilder output = new StringBuilder();
String iv = payload.substring(0, 16);
byte[] secret = Base64.getDecoder().decode(Files.readAllBytes(Paths.get(path)));
String data = payload.substring(16);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(secret, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes(), 0, cipher.getBlockSize());
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); // This line throws exception :
cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
Here it is:
Exception in thread "main" java.security.InvalidKeyException: Invalid AES key length: 370 bytes
at com.sun.crypto.provider.AESCrypt.init(AESCrypt.java:87)
at com.sun.crypto.provider.CipherBlockChaining.init(CipherBlockChaining.java:91)
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:591)
at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:346)
at javax.crypto.Cipher.init(Cipher.java:1394)
at javax.crypto.Cipher.init(Cipher.java:1327)
at com.sample.App.main(App.java:70)
I have already visited similar question like
AES-256 CBC encrypt in php and decrypt in Java or vice-versa
openssl_encrypt 256 CBC raw_data in java
Unable to exchange data encrypted with AES-256 between Java and PHP
and list continues.... but no luck there
btw, this is how encryption is done in PHP
$secretFile = "/path/to/secret/saved/in/text_file";
$secret = base64_decode(file_get_contents($secretFile));
$iv = bin2hex(openssl_random_pseudo_bytes(8));
$enc = openssl_encrypt($plainText, "aes-256-cbc", $secret, false, $iv);
return $iv.$enc;
and yes, I forgot to mention that my JRE is already at UnlimitedJCEPolicy and I can't change PHP code.
I am totally stuck at this point and can't move forward. Please help out.
EDIT#1
byte[] payload = ....;
byte[] iv = ....;
byte[] secret = ....; // Now 370 bits
byte[] data = Base64.getDecoder().decode(payload);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKeySpec secretKeySpec = new SecretKeySpec(Arrays.copyOfRange(secret, 0, 32), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv, 0, cipher.getBlockSize());
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] output = cipher.doFinal(data);
System.out.println(new String(output).trim());
Above snippet seems to be working with openssl_encrypt
EDIT#2
I am not sure if this is correct, but following is what I have done and encryption-decryption on both side are working fine.
Encrypt in PHP, Decrypt in JAVA use AES/CBC/NoPadding
Encrypt in JAVA, Decrypt in PHP use AES/CBC/PKCS5Padding
I won't provide a complete solution, but there are a few differences you should take care of
Encoding:
String iv = payload.substring(0, 16);
String data = payload.substring(16);
are you sure the IV and data are the same in Java and PHP (The IV is string?)? If the data are encrypted, they should be treated as a byte array, not string. Just REALLY make sure they are THE SAME (print hex/base64 in php and java)
For the IV you at the end call iv.getBytes(), but the locale encoding may/will corrupt your values. The String should be use only when it's really string (text). Don't use string for binaries.
Simply treat data and iv as byte[]
Key generation according to the openssl
AES key must have length of 256 bit for aes-256-cbc used. The thing is - openssl by default doesn't use the provided secret as a key (I believe it can, but I don't know how it is to be specified in PHP).
see OpenSSL EVP_BytesToKey issue in Java
and here is the EVP_BytesToKey implementation: https://olabini.com/blog/tag/evp_bytestokey/
you should generate a 256 bit key usging the EVP_BytesToKey function (it's a key derivation function used by openssl).
Edit:
Maarten (in the comments) is right. The key parameter is the key. Seems the PHP function is accepting parameter of any length which is misleading. According to some articles (e.g. http://thefsb.tumblr.com/post/110749271235/using-opensslendecrypt-in-php-instead-of) the key is trucated or padded to necessary length (so seems 370 bit key is truncated to length of 256 bits).
According to your example, I wrote fully working code for PHP and Java:
AesCipher class: https://gist.github.com/demisang/716250080d77a7f65e66f4e813e5a636
Notes:
-By default algo is AES-128-CBC.
-By default init vector is 16 bytes.
-Encoded result = base64(initVector + aes crypt).
-Encoded/Decoded results present as itself object, it gets more helpful and get possibility to check error, get error message and get init vector value after encode/decode operations.
PHP:
$secretKey = '26kozQaKwRuNJ24t';
$text = 'Some text'
$encrypted = AesCipher::encrypt($secretKey, $text);
$decrypted = AesCipher::decrypt($secretKey, $encrypted);
$encrypted->hasError(); // TRUE if operation failed, FALSE otherwise
$encrypted->getData(); // Encoded/Decoded result
$encrypted->getInitVector(); // Get used (random if encode) init vector
// $decrypted->* has identical methods
JAVA:
String secretKey = "26kozQaKwRuNJ24t";
String text = "Some text";
AesCipher encrypted = AesCipher.encrypt(secretKey, text);
AesCipher decrypted = AesCipher.decrypt(secretKey, encrypted);
encrypted.hasError(); // TRUE if operation failed, FALSE otherwise
encrypted.getData(); // Encoded/Decoded result
encrypted.getInitVector(); // Get used (random if encode) init vector
// decrypted.* has identical methods