[Cryptography-dev] Getting Error when updating field on DB with encoded base64 string
Salvador Munguia
sm5149 at yahoo.com
Thu Feb 23 16:56:56 EST 2017
It works when I encrypt and decode from string in same script, but when sent to DB looks like error with base64 encoding.
Error:
Traceback (most recent call last):
File "tmp2.py", line 82, in <module>
main(1)
File "tmp2.py", line 73, in main
string = getCode(id,'ev_details')
File "tmp2.py", line 23, in getCode
result = base64.b64decode(row[0])
File "/usr/lib/python2.7/base64.py", line 76, in b64decode
raise TypeError(msg)
TypeError: Incorrect padding
Script:
#!/usr/bin/python
import zlib,MySQLdb,os,sys,urllib,re
import os,hashlib,base64
from cryptography.fernet import Fernet
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from Crypto.Cipher import AES
from pbkdf2 import PBKDF2
conn = MySQLdb.connect (host = "localhost",
user = "root",
passwd = "pass",
db = "db")
def getCode(id,tbl):
sql = "SELECT `details` FROM %s WHERE `id` = %s;" % (tbl,id)
# print sql
cursor = conn.cursor ()
cursor.execute (sql)
row = cursor.fetchone ()
result = base64.b64decode(row[0])
# return row[0]
return result
def getEncrypt(id,tbl):
sql = "SELECT `encrypted` FROM %s WHERE `id` = %s;" % (tbl,id)
# print sql
cursor = conn.cursor ()
cursor.execute (sql)
row = cursor.fetchone ()
result = base64.b64decode(row[0])
# result = row[0]
return result
def encryptMAIN(data,fun):
password = b"This is the password!"
# salt = os.urandom(16)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt='42$ahasdkjfha',
iterations=100000,
backend=default_backend()
)
key = base64.urlsafe_b64encode(kdf.derive(password))
f = Fernet(key)
if(fun == 'encrypt'):
return f.encrypt(b"%s" % (data))
else:
return f.decrypt(data)
def encryptDATA(data):
cipher = encryptMAIN(data,'encrypt')
return cipher
def decryptDATA(data):
decoded = encryptMAIN(data,'')
return decoded
def insertBin(id,data):
data = '%s' % (data)
sql = "UPDATE `sec_details` set `encrypted` = '%s' WHERE `id` = %s;" % (data, id)
# print sql
cursor = conn.cursor ()
cursor.execute (sql)
conn.commit()
return 1
def main(id):
string = getCode(id,'ev_details')
e_out = encryptMAIN(string,'encrypt')
insertBin(id,e_out)
print "Original Data: " + string
string = getEncrypt(id,'sec_details')
print "Encrypted Data: " + string
dout = encryptMAIN(string,'')
print "Decrypted Data: " + dout
main(1)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cryptography-dev/attachments/20170223/ffc85655/attachment.html>
More information about the Cryptography-dev
mailing list