我正在尝试使用 PyCrypto 解密数据。数据使用 javax.crypto 包用 Java 进行编码。加密方式为 Triple DES(在 Java 中称为“DESede”)。据我所知,一切都使用默认设置。但是,当我用Python解密数据时,数据总是有问题。
这是执行加密/解密的 Java 代码:
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.security.spec.KeySpec;
public final class Encrypter
{
public static final String DESEDE_ENCRYPTION = "DESede";
private KeySpec keySpec;
private SecretKeyFactory keyFactory;
private Cipher cipher;
private static final String UNICODE_FORMAT = "UTF8";
public Encrypter(String encryptionKey)
throws Exception
{
byte[] keyAsBytes = encryptionKey.getBytes(UNICODE_FORMAT);
keySpec = new DESedeKeySpec(keyAsBytes);
keyFactory = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION);
cipher = Cipher.getInstance(DESEDE_ENCRYPTION);
}
public String encryptString(String unencryptedString)
{
SecretKey key = keyFactory.generateSecret(keySpec);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cleartext = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] ciphertext = cipher.doFinal(cleartext);
BASE64Encoder base64encoder = new BASE64Encoder();
return base64encoder.encode(ciphertext);
}
public String decryptString(String encryptedString)
{
SecretKey key = keyFactory.generateSecret(keySpec);
cipher.init(Cipher.DECRYPT_MODE, key);
BASE64Decoder base64decoder = new BASE64Decoder();
byte[] ciphertext = base64decoder.decodeBuffer(encryptedString);
byte[] cleartext = cipher.doFinal(ciphertext);
return bytesToString(cleartext);
}
private static String bytesToString(byte[] bytes)
{
StringBuilder sb = new StringBuilder();
for (byte aByte : bytes)
{
sb.append((char) aByte);
}
return sb.toString();
}
}
但是当我获取此代码生成的 Base64 编码字符串之一时,我无法对其进行解码。下面是我尝试过的一些 Python 代码的示例:
from Crypto.Cipher import DES3
import array
key = <value of the key, as a hex string>
encryptedvalue = <the value that's encrypted, as a string>
keyarray = array.array('B', key.decode("hex"))
des = DES3.new(keyarray)
value = des.decrypt(encryptedvalue.decode('base64'))
value.decode('utf-8') # Gives me an error
我遇到的错误看起来类似于
UnicodeDecodeError: 'utf8' codec can't decode byte 0xa7 in position 6: invalid start byte
这意味着在这个过程中的某个地方,我还没有正确设置一些东西。我已经为此工作了几个小时,甚至试图研究 SunJCE source code ,其中 implements DESede ,查看他们使用的默认值,但无济于事。我将使用它作为自动运行的脚本的一部分,所以我真的不想使用 Java 来进行解密。有谁知道我需要做什么才能正确解密我的数据?
最佳答案
要使其工作,我所要做的就是更改此行
keyarray = array.array('B', key.decode("hex"))
对此:
keyarray = array.array('B', key.encode("utf-8"))
这与 java 编码 key 的方式相匹配,使我能够拥有正确的加密 key 。
如果您来到这里希望从这个问题中学到一些东西,这里有一些一般性建议:
- 仔细检查您的假设: key 字符串是十六进制字符串,因此我假设它是这样使用的。
- 确保您知道您的假设是什么:我没有有意识地思考我是如何对 key 的使用方式做出假设的。这往往是编程和生活中非常常见的问题。
- 一路检查所有值(尤其当你有 Oracle 时):查看字节数组中的值让我意识到我的想法问题。
关于java - 在 Python 中解密由 Java 以 3DES 加密的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16203619/