Wednesday, November 20, 2013

PHP Equivalent for DESede/CBC/PKCS5Padding

Recently I tried porting an encryption implementation to PHP from Java.

It was not possible to touch the existing encryption/ decryption implementation So the requirement is to have the similar encryption implementation in PHP which will give same result as in Java.


The Java implementation is
    public String encryptTest(String message) throws Exception {
     final MessageDigest messageDigest = MessageDigest.getInstance("md5");
     String keyString = "AB12CD3EF4";
  final byte[] passwordDigest = messageDigest.digest(keyString.getBytes("utf-8"));
     final byte[] keyBytes = paddKeyString(passwordDigest);
     final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
     cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(keyBytes, "DESede"), new IvParameterSpec(new byte[8]));
     final byte[] encryptedText = cipher.doFinal(message.getBytes("utf-8"));
     return Base64.encodeBase64String(encryptedText);
    }

 private byte[] paddKeyString(final byte[] passwordDigest) {
  final byte[] keyBytes = Arrays.copyOf(passwordDigest, 24);
  int pos = 16;
     for (int index = 0; index < 8;) {
      keyBytes[pos++] = keyBytes[index++];
     }
  return keyBytes;
 }

After couple of hours of trial and error , got the following PHP implementation which will produce the same result as the Java counterpart.
function encryptText_3des($plainText, $key) {
 $key = hash("md5", $key, TRUE); 
 for ($x=0;$x<8;$x++) {
  $key = $key.substr($key, $x, 1);
 }
 $padded = pkcs5_pad($plainText,
        mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_CBC));
 $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_CBC));
    return $encrypted;
}
Note: pkcs5_pad method is available here http://php.net/manual/en/ref.mcrypt.php
PHP is fun , I am going to give it little more time :)

1 comment:

  1. Hello Ratheesh, my name is julian, actually im trying to develop the equivalent in PHP of the nest java decrypt but im kinda lost
    public static String decrypt(String encryptedText, String publicKey)
    throws Exception
    {
    byte[] message = Base64.decodeBase64(encryptedText.getBytes("utf-8"));

    MessageDigest md = MessageDigest.getInstance(Constants.MD5);
    byte[] digestOfPassword = md.digest(publicKey.getBytes(Constants.UTF_8));
    byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
    int j = 0;
    for (int k = 16; j < 8;) {
    keyBytes[(k++)] = keyBytes[(j++)];
    }
    SecretKey key = new SecretKeySpec(keyBytes, Constants.DE_SEDE);
    IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    Cipher decipher = Cipher.getInstance(Constants.DE_SEDE_CBC_PKCS5_PADDING);
    decipher.init(2, key, iv);

    byte[] plainText = decipher.doFinal(message);

    return new String(plainText, Constants.UTF_8);
    }

    Can you give me a hand?
    Kind regards!!!

    ReplyDelete