简体   繁体   English

如何像在Java上的代码一样在php上加密字符串?

[英]How to encrypt string on php as same as a code on java?

For a project I should encrypt strings on php as same as a code block on java side. 对于项目,我应该像在Java端的代码块一样在php上加密字符串。 Below there is the java code. 下面是Java代码。 "input" is the string to be encrypted and "key" encryption key. “输入”是要加密的字符串和“密钥”加密密钥。

    MessageDigest digest;
    try {
        digest = MessageDigest.getInstance("MD5");
        byte[] md5key = digest.digest(key.getBytes("UTF-8"));
        Cipher cipher = Cipher.getInstance("DESEDE/ECB/PKCS5Padding");
        SecretKeySpec myKey = new SecretKeySpec(md5key, "DESede");
        cipher.init(Cipher.ENCRYPT_MODE, myKey);

        try {
            byte[] encryptedPlainText = cipher.doFinal(input.getBytes());

            String encrypted = Base64.encodeToString(encryptedPlainText, 0);
            return encrypted;

        }
    }

And here is the php code that I tried to encrypt strings. 这是我尝试加密字符串的php代码。 "encryptText_3des" function gets the string and the key, and returns encrypted string. “ encryptText_3des”函数获取字符串和密钥,并返回加密的字符串。

function encryptText_3des($plainText, $key) {
    $key = hash("md5", $key, true);
    $padded = pkcs5_pad($plainText, mcrypt_get_block_size(MCRYPT_3DES, MCRYPT_MODE_ECB));
    $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $padded, MCRYPT_MODE_ECB));
    return $encrypted;
}

function pkcs5_pad ($text, $blocksize) 
{ 
    $pad = $blocksize - (strlen($text) % $blocksize); 
    return $text . str_repeat(chr($pad), $pad); 
}

The output strings of java and php codes are not same. java和php代码的输出字符串不同。 What the point that I am missing? 我想念的是什么?

Thanks... 谢谢...

The problem is that PHP seems to use it's own proprietary key extension mechanism. 问题是PHP似乎使用了它自己的专有密钥扩展机制。 Instead of using the 16 bytes as DES ABA key (16 bytes) it simply extends the key with 0 valued characters until it has 24 bytes to use as DES ABC key. 与其使用16个字节作为DES ABA密钥(16个字节),不如将密钥扩展为0个值的字符,直到它具有24个字节用作DES ABC密钥。

If you want to have DES EDE with 16 bytes key, then you should repeat the first 8 bytes of your key (retrieved from MD5) at the end of your key: 如果要使用带16个字节密钥的DES EDE,则应在密钥末尾重复密钥的前8个字节(从MD5检索):

$key = hash("md5", $key, true);
$key = $key . substr($key, 0, 8);

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

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