简体   繁体   中英

Java: How to decode string encrypted on php with known key?

so I encrypted a string on my php server.

encrypt("http://google.com", "happy");

function encrypt($str, $key)
{
    $block = mcrypt_get_block_size('des', 'ecb');
    $pad = $block - (strlen($str) % $block);
    $str .= str_repeat(chr($pad), $pad);

    return mcrypt_encrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB);
}

btw, this returns some weird string...I was expecting letters and numbers: ZöÞ ÔP»8

Back on Java, I need to decrypt this string with the key.

I'm not au fait with mcrypt, but running ASCII plaintext through encryption doesn't always result in an ASCII ciphertext. Chances are your generated encrypted ciphertext is going to translate into a 'weird string' when you try and interpret it as ASCII or unicode text.

first, make sure it isn't an one-way encryption. second, algorithm and arguments used in php and reverse engineering in java

I think this will be useful. Note that the charset is UTF-8.

public class Foo {

    public static void main(String[] args) {
        try {
            String cipherSpec = "DES/ECB/NoPadding";
            Cipher cipher = Cipher.getInstance(cipherSpec);
            int blockSize = cipher.getBlockSize();

            String keyText = "happy";
            Key key = new SecretKeySpec(padRight(keyText, blockSize).getBytes("UTF-8"), "DES");

            String input = "http://google.com";
                   input = padRight(input, input.length() + blockSize - (input.length() % blockSize));

            // encrypt
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] cipherText = cipher.doFinal(input.getBytes(CHARSET));
            System.out.println("\ncipher text: ");
            System.out.println(new String(cipherText, CHARSET));

            // decrypt
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] plainText = cipher.doFinal(cipherText);
            System.out.println("\nplain text: ");
            System.out.println(new String(plainText, CHARSET));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    final static String CHARSET = "UTF-8";

    static String padRight(String s, int n) {
        return String.format("%1$-" + n + "s", s);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM