I'm trying to write a PHP function to encrypt some text that will then be passed to the ScriptMaster FileMaker plugin which uses Java to decrypt that text.
Here's the Java code (which I'm trying to mimic in PHP) that encrypts the text:
[text]import javax.crypto.*;
import javax.crypto.spec.*;
import sun.misc.*;
byte[] salt = [4, 7, 29, 81, 5, 121, 117, 73]; //Any random set of 8 bytes will do.
// It is a good idea to change these to something else than the demo values for yourself.
// If you do change them, be sure to make the same change for both decryptiong/encrypting.
PBEKeySpec keySpec = new PBEKeySpec( password.toCharArray() );
SecretKey secretKey = SecretKeyFactory.getInstance( "PBEWithMD5AndDES" ).generateSecret( keySpec );
Cipher cipher = Cipher.getInstance( "PBEWithMD5AndDES" );
cipher.init( Cipher.ENCRYPT_MODE, secretKey, new PBEParameterSpec( salt, 1 ) );
byte[] encryptedBytes = cipher.doFinal( textToEncode.getBytes() );
String base64text = new BASE64Encoder().encode( encryptedBytes );
return base64text.replaceAll("\n", ""); //Get rid of return characters[/text]
Using the password "sheep" and the text "Test", the result is "smCdE4fAFEo=".
And here's the Java code that decrypts the text:
[text]import javax.crypto.*;
import javax.crypto.spec.*;
import sun.misc.*;
byte[] salt = [4, 7, 29, 81, 5, 121, 117, 73]; //Any random set of 8 bytes will do.
// It is a good idea to change these to something else than the demo values for yourself.
// If you do change them, be sure to make the same change for both decryptiong/encrypting.
PBEKeySpec keySpec = new PBEKeySpec( password.toCharArray() );
SecretKey secretKey = SecretKeyFactory.getInstance( "PBEWithMD5AndDES" ).generateSecret( keySpec );
Cipher cipher = Cipher.getInstance( "PBEWithMD5AndDES" );
cipher.init( Cipher.DECRYPT_MODE, secretKey, new PBEParameterSpec( salt, 1 ) );
byte[] bytes = new BASE64Decoder().decodeBuffer( textToDecode );
return new String( cipher.doFinal( bytes ) );[/text]
Here's my PHP code:
Code: Select all
protected function pkcs5_pad ($text, $blocksize){
$pad = $blocksize - (strlen($text) % $blocksize);
return $text . str_repeat(chr($pad), $pad);
}
protected function encryptNotes($noteText){
$iv = array(4, 7, 29, 81, 5, 121, 117, 73);
$key = "sheep";
$keyPacked = pack('H*',utf8_encode($key));
$noteText = $this->pkcs5_pad(pack('H*', utf8_encode($noteText)), 8 );
$cipherText = mcrypt_encrypt(MCRYPT_DES, $keyPacked, $noteText, MCRYPT_MODE_ECB, $iv);
echo base64_encode($cipherText); die;
}
Does anyone know what I'm missing, or if what I'm trying to do isn't possible?
Thanks!