简体   繁体   English

Java:如何使用已知密钥解码在PHP上加密的字符串?

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

so I encrypted a string on my php server. 所以我在我的php服务器上加密了一个字符串。

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 顺便说一句,这会返回一些奇怪的字符串......我期待着字母和数字: ZöÞ ÔP»8

Back on Java, I need to decrypt this string with the key. 回到Java,我需要用密钥解密这个字符串。

I'm not au fait with mcrypt, but running ASCII plaintext through encryption doesn't always result in an ASCII ciphertext. 我不喜欢mcrypt,但是通过加密运行ASCII明文并不总是会产生ASCII密文。 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. 当您尝试将其解释为ASCII或unicode文本时,您生成的加密密文可能会转换为“奇怪的字符串”。

first, make sure it isn't an one-way encryption. 首先,确保它不是单向加密。 second, algorithm and arguments used in php and reverse engineering in java 第二,用于PHP中的算法和参数以及java中的逆向工程

I think this will be useful. 我认为这会很有用。 Note that the charset is UTF-8. 请注意,charset是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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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