Python AES解密

我在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脚本中复制此function。 这是我的初始代码的样子:

 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输出结束时还有很多▯▯▯字符,但我很快就通过解密数据解除了它们。 尽管如此,我无法弄清楚我在做错了有效载荷的第一部分是否已被扰乱。 我对数据加密的了解非常基础,因此我会向您提供知识:)

问题是服务器代码使用了一个带有零的固定IV(这是坏的),但在你的python代码中,你将一个新的随机生成的IV传递给AES.new

您可以使用"\x00"*BLOCK_SIZE替换rndfile.read(BLOCK_SIZE)