【问题标题】:Why did the result of DES Encryption executed in Java different from executed in PHP?为什么在 Java 中执行 DES 加密的结果与在 PHP 中执行的结果不同?
【发布时间】:2019-06-02 23:41:34
【问题描述】:

我在 Java 中使用 null IV 运行了 Trible DES 加密(我已经运行了 cipher.getIV() 方法,实际上它的 IV 为空),并且相同的字符串在 PHP 中使用 null IV 运行了三重 DES 加密,但是我得到不同的结果。这是为什么呢?

Java 代码:

private static final String model = "DESede/ECB/PKCS5Padding";
public static String desEncrypt(String message, String key) throws Exception {
    byte[] keyBytes = null;
    if(key.length() == 16){
        keyBytes = newInstance8Key(ByteUtil.convertHexString(key));
    } else if(key.length() == 32){
        keyBytes = newInstance16Key(ByteUtil.convertHexString(key));
    } else if(key.length() == 48){
        keyBytes = newInstance24Key(ByteUtil.convertHexString(key));
    }

    SecretKey deskey = new SecretKeySpec(keyBytes, "DESede");

    Cipher cipher = Cipher.getInstance(model);
    cipher.init(1, deskey);
    return ByteUtil.toHexString(cipher.doFinal(message.getBytes("UTF-8")));
}

PHP 代码:

// composer require phpseclib/phpseclib
use phpseclib\Crypt\TripleDES;

function desEncrypt($str,$key){
    $cipher = new TripleDES();
    $cipher->setKey(hex2bin($key));

    $cryptText = $cipher->encrypt($str);

   return unpack("H*",$cryptText)[1];
}

我想修改我的 PHP 代码以适应 Java 加密过程,我应该怎么做?问题在哪里?

Java 加密结果:

before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: c9aa8ebfcc12ce13e22a33b05d4c18cf

PHP 加密结果:

before: 622700300000
key: 0123456789ABCDEFFEDCBA98765432100123456789ABCDEF
after: a6e7a000d4ce79ac8b3db9f6acf73de3

固定的 PHP 代码:

/**
 * Triple DES (ECB) Encryption Function
 * PKCS5Padding
 * 
 * @param string $message String needed to be encode
 * @param string $key Hex encoded key
 * @return string Hex Encoded
 */
function desEncrypt($message,$key){
    $cipher = new TripleDES(TripleDES::MODE_ECB);
    $cipher->setKey(hex2bin($key));

    $cryptText = $cipher->encrypt($message);

   return bin2hex($cryptText);
}

【问题讨论】:

标签: java php encryption des 3des


【解决方案1】:

您忘记在使用之前对密钥进行十六进制解码。您还使用了 CBC 模式而不是 ECB 模式,但由于您的 IV 全部为零,这相当于第一个加密数据块

【讨论】:

  • 我已经在$key中添加了一个bin2hex()函数(我已经更新了我的帖子),但它似乎与Java代码的结果仍然不同。
  • 将模式显式设置为 ECB 并删除 setIV。在 ECB 模式下它不会做任何事情,但 ECB 模式不使用 IV。
  • 你是用bin2hex代替hex2bin吗?真的吗?
  • 如何在 php 中将模式设置为 ECB? phpseclib 中的 DES 类似乎只有 phpseclib\Crypt\DES 和 phpseclib\Crypt\TripleDES 方法。
  • 不客气。我希望你也能忘记,因为....密钥不应该是字符串,不推荐使用三重 DES,ECB 模式不安全,您需要一个传输协议来保护传输中的数据,口袋妖怪异常处理不好,字符串化代码不好,分配 null 不好,if 而不是 switch 不好,编码为十六进制不好(使用 base 64 if 你想要一个字符串),使用 1 文字不好 - 的Java代码基本上是垃圾......我可以轻松地再制作10个cmet......
猜你喜欢
  • 2017-02-06
  • 2017-08-25
  • 2016-12-10
  • 2012-08-24
  • 2015-02-09
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 2021-06-21
相关资源
最近更新 更多