Search code examples
javaphpencoderdecoder

I need two functions which encrypts some data in php and decrypts it in java "correctly"


I need to get two functions. I want to transfer data from my website to my server in xml format. Now on my server, I want to make a function that encrypts the data and place it in an xml, and another function in java to decrypt it.

Please tell me if there is any predefined function or can you just spare 5 minutes?


Solution

  • Well, you can use any encrypting mcrypt function in PHP. One example for encrypting in AES 128:

      $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
      $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
      $key = "Put your secret key here";
      $text = "<xml>This is your XML text</xml>";
    
      //encrypting now with RIJNDAEL 128 encryption.
      $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_ECB, $iv);
    
      //Display encrypted content
      echo $crypttext;
    

    And for decrypting, use this code (I'm not a Java pro, so there may be some bugs):

    package org.kamal.crypto;
    
    import java.security.*;
    import java.security.spec.InvalidKeySpecException;
    import javax.crypto.Cipher; 
    import javax.crypto.spec.SecretKeySpec;
    import sun.misc.*;
    
    public class SimpleProtector
    {
        private static final String ALGORITHM = "AES";
        private static final byte[] keyValue = 
            new byte[] { 'P', 'u', 't', ' ', 'Y', 'o', 'u', 'r', ' ', 'S', 'e', 'c', 'r', 'e', 't', ' ', 'K', 'e', 'y', '', 'H', 'e', 'r', 'e'};
    
        public static String decrypt(String encryptedValue) throws Exception {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
            byte[] decValue = c.doFinal(decordedValue);
            String decryptedValue = new String(decValue);
            return decryptedValue;
        }
    
        private static Key generateKey() throws Exception {
            Key key = new SecretKeySpec(keyValue, ALGORITHM);
            // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
            // key = keyFactory.generateSecret(new DESKeySpec(keyValue));
            return key;
        }
    }