I am writing a program using Java 1.6 that should generate a message of the format:
"Your invoice #123 for 100.00 is at https://my.site.com/documents/invoice?p=xxxxxxxxxxx"
with xxxxx containing an encrypted JSON string. The website at my.site.com runs PHP. It would open the URL with the invoice info:
<?php
$cipher = "AES-128-CTR";
$encryption_iv = "1234567891011121";
$encryption_key = "MyPassword";
$encryption_options = 0;
$enrypted_parm = urldecode( $this->input->get('p') );
$iv_length = openssl_cipher_iv_length( $cipher );
$decrypted_parm = openssl_decrypt( $enrypted_parm, $cipher, $encryption_key, $encryption_options, $encryption_iv );
$parms = json_decode($decrypted_parm);
echo "id=" . $parms->id . "&db=" . $parms->db . "&archived=" . $parms->archived;
?>
To generate the message from Java, I have tried this:
encryption_key = "MyPassword";
JsonObject joParms = new JsonObject();
joParms.addProperty("id", invoiceId);
joParms.addProperty("db", db);
joParms.addProperty("archived", isArchive);
SecretKeySpec secretKeySpec = new SecretKeySpec(encryption_key.concat(" ").substring(0,16).getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] byteEncryptedString = cipher.doFinal(joParms.toString().getBytes());
String encodedString = Base64.encodeBase64String(byteEncryptedString);
String message = messageTemplate.replace("{INVNO}", invNo).replace("{AMOUNT}", amount).concat(" ").concat(siteUrl).concat("?p=").concat(encodedString);
The encrypted string generated thus does not get decrypted by PHP. I think the two don’t quite match in specs. Can someone help?
2
Answers
For compatibility with the PHP code, in the Java code:
IvParameterSpec
(or if no user-defined IV is applied, the automatically generated IV must be retrieved withcipher.getIV()
, as this is required for decryption).In addition, for security reasons:
getBytes()
. Otherwise, a platform-dependent default encoding is used (at least in earlier Java versions).Sample code for Java 1.6:
which can be decrypted with the following PHP code:
One common approach is using AES encryption with a shared secret key. Below is an example (Ecnrypt Java):
Decrypt PHP example :