我无法在Java中创建相当于php DES的解密,总是有不同的结果。 这里是php-code我想复制的内容:
$key = substr(sha1("m",true),0,8); //8-byte key
$iv = mcrypt_encrypt (MCRYPT_DES,$key,hex2bin("0000000000000000"),MCRYPT_MODE_ECB); //get Iv
print(bin2hex($iv)."\n"); // "b5872289d3c49605"
$plain_text = "MZ4aXMCMO/TQAsZ2bYwagw==";
$plain_text = base64_decode($plain_text);
$cipher_text = mcrypt_decrypt (MCRYPT_DES, $key, $plain_text, MCRYPT_MODE_CFB, $iv);
print("\nThe ciphertext: ".$cipher_text);
print("\nThe expected : "."489B4F2ADD728755");
和我的Java代码:
public static void desCipherDecrypt(String key, String encodedString) throws Exception {
byte [] keyByte = Arrays.copyOf(DigestUtils.sha1(key),8);
byte [] encodedByte = Base64.decodeBase64(encodedString);
byte [] iv = DatatypeConverter.parseHexBinary("B5872289D3C49605"); //same as Iv in php
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
Cipher desCipherDecrypt;
desCipherDecrypt = Cipher.getInstance("DES/CFB/NoPadding");
DESKeySpec dks = new DESKeySpec(keyByte);
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
SecretKey desKey = skf.generateSecret(dks);
desCipherDecrypt.init(Cipher.DECRYPT_MODE, desKey,paramSpec);
byte[] cryptByte = desCipherDecrypt.doFinal(encodedByte);
System.out.println("resultBytes: "+Arrays.toString(cryptByte)+"\n");
System.out.println("resultHex: "+DatatypeConverter.printHexBinary(cryptByte)+"\n");
System.out.println("Decryption ended");
}
...
desCipherDecrypt("m", "MZ4aXMCMO/TQAsZ2bYwagw==");
答案 0 :(得分:0)
所以,这是一个愚蠢的错误,由于某种原因,我认为$ cipher_text是用Hex编码的,但它是错误的,它是纯文本,另一个原因是mcrypt_decrypt由于某种原因没有使用64位但8位块中的标准块。
毕竟答案将是, 首先,使用CFB8:
desCipherDecrypt = Cipher.getInstance("DES/CFB8/NoPadding");
第二个读取结果字节,如纯文本
yte[] cryptByte = desCipherDecrypt.doFinal(encodedByte);
for (int i = 0; i < cryptByte.length; i++ ){
sResult += (char)(cryptByte[i]);
}