【问题标题】:Rijndael encryption in pythonpython中的Rijndael加密
【发布时间】:2018-07-31 18:13:32
【问题描述】:

我想在 python 中使用带有密钥和块 256 位大小的 Rijndael 加密,填充应该是 PKCS7。要么使用 utf-8 编码。 我搜索了很多,最后写了这段代码,我不知道这是一个好方法,但我知道的就这么多。运行代码时出现此错误:

Traceback (most recent call last):
File "testForRijndael.py", line 1, in <module>
  from rijndael.cipher import crypt
File "/opt/odoo/odoo11-venv/lib/python3.6/site- 
  packages/rijndael/cipher/crypt.py", line 1, in <module>
  from rijndael.cipher.blockcipher import *
File "/opt/odoo/odoo11-venv/lib/python3.6/site- 
  packages/rijndael/cipher/blockcipher.py", line 64
    raise Exception,"the IV length should be %i bytes"%self.blocksize
               ^
SyntaxError: invalid syntax

如果有人可以帮助我,我会很感激他/她

这是我的代码:

from rijndael.cipher import crypt
from rijndael.cipher.blockcipher import MODE_CBC
from pkcs7 import PKCS7Encoder


class Rijndael():
    def __init__(self, key, iv):
       self.KEY = key
       self.IV = iv
       self.BLOCKSIZE = 32

   def encrypt(self, plain_text):
        rjn = crypt.new(self.KEY, MODE_CBC , self.IV, 
blocksize=self.BLOCKSIZE)
        pad_text = PKCS7Encoder.encode(plain_text)
        return rjn.encrypt(pad_text).encode()

   def decrypt(self, cipher_text):
       rjn = crypt.new(self.KEY, MODE_CBC , self.IV, 
                       blocksize=self.BLOCKSIZE)
       cipher_text = cipher_text.decode()
       return rjn.decrypt(cipher_text)


  r = Rijndael('abcdefghijklmnopqrstuvwxyz123456', 
  'abcdefghijklmnopqrstuvwxyzgh3456')
  test_text = "this is a test :)"
  encrypt = r.encrypt(test_text)
  decrypt = r.decrypt(encrypt)
  print(test_text)
  print(encrypt)
  print(decrypt)

【问题讨论】:

    标签: python encryption aes rijndael


    【解决方案1】:

    您从中导入的 rijndael 库是为 python 2 编写的,但您使用 python 3 运行它。请参阅下面的语法,了解适用于 python 2 但不适用于 python 3 的语法。

    $ cat raise.py
      raise Exception,"text"
    $ python2 raise.py
    Traceback (most recent call last):
      File "raise.py", line 1, in <module>
        raise Exception,"text"
    Exception: text
    $ python3 raise.py
      File "raise.py", line 1
        raise Exception,"text"
                       ^
    SyntaxError: invalid syntax
    

    你可以尝试自己迁移,使用2to3工具,看看有没有人写过port,或者用python 2编写并执行你的程序。

    尝试pip2 install rijndael,然后尝试python2 testForRijndael.py

    要在本地代码上运行2to3(不是很推荐,但它可能会起作用),运行2to3 -w /opt/odoo/odoo11-venv/lib/python3.6/site-packages/rijndael/**/*.py

    【讨论】:

    • 我必须用 python 3 运行我的代码,python3 有没有 rijndael 库?我用谷歌搜索但没有找到任何东西,似乎没有 python3 的库:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多