python中的Blowfish解密javax.cryp

2024-10-01 17:39:17 发布

您现在位置:Python中文网/ 问答频道 /正文

使用在https://raw.github.com/usefulfor/usefulfor/master/security/JBoss.java找到的代码,我做了以下操作:

bash-3.2$ java -cp . JBoss -e testpython
-27038292d345798947e2852756afcf0a
bash-3.2$ java -cp . JBoss -d -27038292d345798947e2852756afcf0a
testpython

然而,我一辈子都无法想出如何在python中使用pycrypto解密字符串“27038292d345798947e2852756afcf0a”。我的理解是Java代码使用的是Blowfish,而短语“jaas is the way”是密码的密钥。但我无法理解如何在python中实现这一点。以下是无法打印的垃圾结果:

^{pr2}$

我错过了什么?在

谢谢。在


Tags: 字符串代码httpsgithubmastercombashraw
2条回答

这对我有帮助

private byte[] encrypt(String key, String plainText) throws GeneralSecurityException {

    SecretKey secret_key = new SecretKeySpec(key.getBytes(), ALGORITM);

    Cipher cipher = Cipher.getInstance(ALGORITM);
    cipher.init(Cipher.ENCRYPT_MODE, secret_key);

    return cipher.doFinal(plainText.getBytes());
}

希望这对你有用,更多http://dexxtr.com/post/57145943236/blowfish-encrypt-and-decrypt-in-java-android

首先,Java示例代码非常糟糕。它将密文输出为整数,而密文应保持为二进制字符串。原因是整数可以用无限多个二进制编码来表示。例如,数字1可以是“0x01”(1字节)、“0x0001”(2字节)等等。当你处理密码函数时,你必须非常精确的表示。在

此外,该示例使用javax.cryptoAPI的默认值,在任何地方都没有描述。所以这真的是试错。在

对于解决方案,您必须知道how to convert negative integers to hex strings in Python。在本例中,您不需要十六进制字符串,而是需要它的字节表示形式。但概念是一样的。我使用PyCrypto的long_to_bytes将正整数(任意长度)转换为字节字符串。在

from Crypto.Cipher import Blowfish
from Crypto.Util.number import long_to_bytes

def tobytestring(val, nbits):
    """Convert an integer (val, even negative) to its byte string representation.
    Parameter nbits is the length of the desired byte string (in bits).
    """
    return long_to_bytes((val + (1 << nbits)) % (1 << nbits), nbits/8)

key = b'jaas is the way'
c1  = Blowfish.new(key, Blowfish.MODE_ECB)

fromjava = b"-27038292d345798947e2852756afcf0a"
# We don't know the real length of the ciphertext, assume it is 16 bytes
ciphertext = tobytestring(int(fromjava, 16), 16*8)
print c1.decrypt(ciphertext)

输出为:

^{pr2}$

从中可以看出,javax.crypto还添加了PKCS#5填充,您需要自己删除它。不过,这是微不足道的。在

然而,real解决问题的方法是用更好的方式进行Java加密。Python代码将大大简化。在

相关问题 更多 >

    热门问题