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

StackOverflow https://stackoverflow.com/questions/3589303

  •  01-10-2019
  •  | 
  •  

Question

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?

Was it helpful?

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;
    }
}

OTHER TIPS

No point reinventing the wheel here. Use SSL, which is what an HTTPS request would involve. You can do those through CURL.

curl is built into PHP and there is also a java version http://php.net/manual/en/book.curl.php

cURL equivalent in JAVA

Hope that helps.

Have you looked into JSON?

It's not encrypted, but it's an easy way to pass data back and forth between different programs and languages.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top