2013-08-30 280 views
0

我使用此代码来加密plist文件,但我发现无论关键是什么,通过AES的值不会改变,有人可以帮助我吗?M2Crypto的AES密钥

import hashlib 
import os 
import subprocess 
from M2Crypto import EVP 

proj_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../')) 

def encrypt_plist(source_dir, name): 
    source_file = os.path.join(source_dir, name+'.plist') 
    target_file = os.path.join(source_dir, name) 
    hash_file = os.path.join(source_dir, name+'.md5') 
    tmp_file = os.path.join('/tmp', name+'.plist') 
    assert os.path.isfile(source_file) 
    assert not os.path.isfile(tmp_file), 'Cannot create %s which should be removed first' % tmp_file 
    subprocess.check_call(["cp", source_file, tmp_file]) 
    subprocess.check_call(["plutil", '-convert', 'binary1', tmp_file]) 
    cipher = EVP.Cipher(alg='aes_256_cbc', 
       key='\x00System/Library/Frameworks/GameKit.framework/GameK', 
       iv=chr(0)*32, 
       op=1) # 1:encode 0:decode 
    m = hashlib.md5() 
    with open(tmp_file, 'rb') as source: 
     with open(target_file, 'wb') as target: 
      while True: 
       buf = source.read() 
       if not buf: 
        break 
       target.write(cipher.update(buf)) 
       m.update(buf) 
      target.write(cipher.final()) 
    subprocess.check_call(["rm", tmp_file]) 
    content_hash = m.hexdigest().upper() 
    try: 
     with open(hash_file, 'r') as _hash: 
      if _hash.read() == content_hash: 
       return 
    except IOError: 
     pass 
    with open(hash_file, 'w') as _hash: 
     _hash.write(content_hash) 
    print ' ', target_file, 'changed\n\tmd5:', content_hash 
+0

欢迎来到Stackoverflow,熊。请看看你的问题的编辑(谢谢你们)。 –

回答

1

你在这里所指的键可能不是一个文件,但一个字符的字符串:

key='\x00System/Library/Frameworks/GameKit.framework/GameK', 

不幸的是键没有字符串,则定义为比特,通常由一个固定长度的阵列表示的字节。

某些库通过不正确地接受任何东西作为关键字而不是拒绝任何不是正确长度的字节数组的东西而使它变得更容易。常用策略是添加零值字节或忽略末尾的任何虚假字节。我认为你只是改变了上面的字符串的末尾,这是丢弃的部分。

现在,要正确加密任何东西,请制作由随机字节组成的AES 128,192或256位密钥并使用它(可能使用十六进制编码)。然后使用随机IV(16字节,AES的块大小)。如果您需要使用秘密字符串或密码,请使用PBKDF2从密码中导出密钥(使用64位随机盐和大量迭代)。

+0

bravo!我真的只是删除字符串的结尾。最后,我使用一个32字节的密钥来制作AES。在需求方面,另外,我对加密过程一直存在误解。 –

+0

很高兴你能工作,熊林。如果这有助于解决您的原始问题,请不要忘记接受我的回答。 –