Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rijndael encryption in python

I wanna use Rijndael encryption with key and block 256bit size in python and padding should be PKCS7. either with utf-8 encode. I have searched a lot and finally wrote this code, I don't know this is a good way but that's all I know. when run the code I got this Error:

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

If anybody can help me, I'll be appreciate him/her

This is my code:

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)
like image 849
Amor Avatar asked Aug 24 '26 18:08

Amor


1 Answers

The rijndael library you're importing from is written for python 2, but you're running it with python 3. See below for the syntax that works in python 2, but not 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

You can try to migrate it yourself, using the 2to3 tool, see if someone has written a port, or write and execute your program with python 2.

Try pip2 install rijndael and then python2 testForRijndael.py.

To run 2to3 on the local code (not really recommended but it might work), run 2to3 -w /opt/odoo/odoo11-venv/lib/python3.6/site-packages/rijndael/**/*.py

like image 195
Riley Martine Avatar answered Aug 26 '26 08:08

Riley Martine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!