我有下面的Java代码,我想在Python中复制它。
public class AESDecryption {
protected SecretKeySpec getPublicKey() {
try {
byte[] key = "MuidKeibimbtjph9".getBytes("UTF-8");
key = MessageDigest.getInstance("SHA-256").digest(key);
key = Arrays.copyOf(key, 32);
return new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public String decrypt(byte[] data) {
Cipher cipher = null;
try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(2, new SecretKeySpec(getPublicKey().getEncoded(), "AES"), new IvParameterSpec(new byte[cipher.getBlockSize()]));
byte decryptedBytes[] = cipher.doFinal(data);
return new String(Arrays.copyOf(decryptedBytes, decryptedBytes.length - decryptedBytes[-1 + decryptedBytes.length]));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (InvalidAlgorithmParameterException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
try {
byte[] content = Files.readAllBytes(Paths.get("/tmp/dump.gzip"));
AESDecryption aesDecryption = new AESDecryption();
System.out.println(aesDecryption.decrypt(content));
} catch (IOException e) {
e.printStackTrace();
}
}
}
此代码来自客户端应用程序。在生成加密内容的服务器端,我没有电源。对于这个问题,我更改了对称密钥和内容的检索方式(在本例中,是从文件中检索的,但实际上是从https响应中检索的)。
我希望使用PyCrypto库在python脚本中复制此功能。我的初始代码是这样的:
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
BLOCK_SIZE = 16
unpad = lambda s: s[0:-ord(s[-1])]
hash = SHA256.new()
hash.update('MuidKeibimbtjph9')
symmetric_key = hash.digest()
symmetric_key = symmetric_key[:32]
bytes_store = None
with open('/tmp/dump.gzip','r') as f:
bytes_store = f.read()
rndfile = Random.new()
aes_decryptor = AES.new(symmetric_key, AES.MODE_CBC, rndfile.read(BLOCK_SIZE))
print unpad(aes_decryptor.decrypt(bytes_store))
在加密的文件上运行java代码工作得很好。结果看上去有点像:
{"code":200,"status":"ok","api_version":"0.0.0","data":[.....],"notifications":{}}
然而,python复制转储一个“半解密”文本。嗯,有点..。
=c�q[A�$�dl�tus":"ok","api_version":"0.0.0","data":[.....],"notifications":{}}
我什么都做不出来。查看Java代码,可以清楚地看到cipter块中没有填充,所以我认为服务器端的数据可能已经是密码块大小的倍数。在python输出的末尾也有很多▯▯▯字符,但是我很快就通过取消解密数据来消除它们。尽管如此,我还是不知道我做错了什么,载荷的第一部分被加错了。我对数据加密的知识是相当基础的,因此我正在向您寻求知识:)
发布于 2014-12-27 11:05:13
问题是服务器代码使用了一个固定的IV (这很糟糕),其中包含了零,但是在您的python代码中,您将一个新的随机生成的IV传递给AES.new
。
您可以用rndfile.read(BLOCK_SIZE)
替换"\x00"*BLOCK_SIZE
。
https://stackoverflow.com/questions/27670368
复制