DES/CBC/PKCS5Padding 对称加密 java 和 php 的实现对比

java 版本

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Map;
import java.util.TreeMap;
 
 
public class Main {
    private static final byte[] DES_IV =  { (byte) 0x00, (byte) 0x00, (byte) 0x00,(byte) 0x00,(byte) 0x00, (byte) 0x00, (byte) 0x00,(byte) 0x00 };
 
    public static void main(String[] args) throws Exception {
 
        String key = "1876ebf1c532b75e1c16a6f230633c0a";
        String data = "aCode=abcde123&source=yq.aliyun.com";
 
        DESKeySpec dks = new DESKeySpec(key.getBytes());
 
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
 
        IvParameterSpec iv = new IvParameterSpec(DES_IV);
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
 
        byte[] bytes = cipher.doFinal(data.getBytes());
 
        System.out.println(new String(Base64.encodeBase64(bytes), "UTF-8"));
    }
 
}

结果是

pJnDpCzlc5zRdbl3Gkt8mSh1rArkb4TsiMAx+tEKwWesLAUWG/4zvw==

PHP 版本

function mcrypt_des_cbc_pkcs5padding($text, $key)
{
    $blockSize = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
    $pad = $blockSize - (strlen($text) % $blockSize);
    $text = $text . str_repeat(chr($pad), $pad);
 
    $iv = "\x00\x00\x00\x00\x00\x00\x00\x00";
    $encode = base64_encode(mcrypt_encrypt(MCRYPT_DES, substr($key,0,8), $text, MCRYPT_MODE_CBC, $iv));
 
    return $encode;
}
 
$res = mcrypt_des_cbc_pkcs5padding("aCode=abcde123&source=yq.aliyun.com", "1876ebf1c532b75e1c16a6f230633c0a");
var_dump($res);

在 java 的源码中可以看到 key 实际只取了前8个字符,在 php 版本中未做了截取,会报错,所以还是要照着java里面做截取。
iv 默认就是x00x00x00x00x00x00x00x00,PHP 中可以不用传。

上一篇:kvm 网络配置之nat、用户模式


下一篇:tomcat 部署位置定义方法备忘