Как хранить зашифрованные данные RSA в postgresql с помощью pycrypto?

Я хочу использовать открытый/закрытый ключ для защиты моих данных UserInfo. Я новичок в PyCrypto и PostgreSQL.

У меня есть некоторые моменты для уточнения:

  1. Являются ли открытый ключ и закрытый ключ постоянными значениями?
  2. Если он постоянный, как я могу его правильно хранить?
  3. И последнее, но самое важное, как я могу хранить свои зашифрованные данные в PostgreSQL? и получить его для проверки?

Не могли бы вы рассказать мне, как обращаться с Crypto.PublicKey.RSA как с методом защиты моих данных.

Среда: Python 2.5, PyCrypto 2.3, PostgreSQL 8.3, кодировка UTF-8

Модель информации о пользователе:

class UserInfo(models.Model):

    userid = models.TextField(primary_key = True)
    password = models.TextField(null = True)
    keyword = models.TextField(null = True)
    key = models.TextField(null = True, blank = True)
    date = models.DateTimeField(null = True, blank = True)

ОБНОВЛЕНИЯ1 test.py:

# -*- encoding:utf-8 -*-
import os
from os.path import abspath, dirname
import sys
from py23.service.models import UserInfo
from Crypto import Random

# Set up django
project_dir = abspath(dirname(dirname(__file__)))
sys.path.insert(0, project_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'py23.settings'
from django.test.testcases import TestCase

class AuthenticationTestCase(TestCase):

    def test_001_registerUserInfo(self):
        import Crypto.PublicKey.RSA
        import Crypto.Util.randpool

        #pool = Crypto.Util.randpool.RandomPool()
        rng = Random.new().read

        # craete RSA object by random key
        # 1024bit
        #rsa = Crypto.PublicKey.RSA.generate(1024, pool.get_bytes)
        rsa = Crypto.PublicKey.RSA.generate(1024, rng)

        # retrieve public key
        pub_rsa = rsa.publickey()

        # create RSA object by tuple
        # rsa.n is public key?, rsa.d is private key?
        priv_rsa = Crypto.PublicKey.RSA.construct((rsa.n, rsa.e, rsa.d))

        # encryption
        enc = pub_rsa.encrypt("hello", "")

        # decryption
        dec = priv_rsa.decrypt(enc)

        print "private: n=%d, e=%d, d=%d, p=%d, q=%d, u=%d" % (rsa.n, rsa.e, rsa.d, rsa.p, rsa.q, rsa.u)
        print "public: n=%d, e=%d" % (pub_rsa.n, pub_rsa.e)
        print "encrypt:", enc
        print "decrypt:", dec

        # text to be signed
        text = "hello"
        signature = priv_rsa.sign(text, "")
        # check if the text has not changed
        print pub_rsa.verify(text, signature)
        print pub_rsa.verify(text+"a", signature)

#        userid = models.TextField(primary_key = True)
#        password = models.TextField(null = True)
#        keyword = models.TextField(null = True)
#        key = models.TextField(null = True, blank = True)    is it correct to store the public key here?
#        date = models.DateTimeField(null = True, blank = True)
        userInfo = UserInfo(userid='test1', password=enc[0], key=pub_rsa.n)
        userInfo.save()
        print "ok"

результат здесь (не удалось):

======================================================================
ERROR: test_001_registerUserInfo (py23.service.auth.tests.AuthenticationTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\PIDevelopment\workspace37_pydev\pyh23\py23\service\auth\tests.py", line 64, in test_001_registerUserInfo
    userInfo.save()
  File "C:\Python25\lib\site-packages\django\db\models\base.py", line 458, in save
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  File "C:\Python25\lib\site-packages\django\db\models\base.py", line 551, in save_base
    result = manager._insert(values, return_id=update_pk, using=using)
  File "C:\Python25\Lib\site-packages\django\db\models\manager.py", line 195, in _insert
    return insert_query(self.model, values, **kwargs)
  File "C:\Python25\lib\site-packages\django\db\models\query.py", line 1524, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Python25\lib\site-packages\django\db\models\sql\compiler.py", line 788, in execute_sql
    cursor = super(SQLInsertCompiler, self).execute_sql(None)
  File "C:\Python25\lib\site-packages\django\db\models\sql\compiler.py", line 732, in execute_sql
    cursor.execute(sql, params)
  File "C:\Python25\lib\site-packages\django\db\backends\util.py", line 15, in execute
    return self.cursor.execute(sql, params)
  File "C:\Python25\lib\site-packages\django\db\backends\postgresql_psycopg2\base.py", line 44, in execute
    return self.cursor.execute(query, args)
DatabaseError: invalid byte sequence for encoding "UTF8": 0x97
HINT:  This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".


----------------------------------------------------------------------
Ran 1 test in 90.047s

FAILED (errors=1)

person eros    schedule 27.10.2011    source источник
comment
Переменные signature и, возможно, enc[0] являются байтами. Чтобы сделать их более читабельными, используйте enc[0].encode('base64') для хранения и enc[0].decode('base64') для извлечения.   -  person KitKat    schedule 19.01.2014


Ответы (1)


Ваша проблема в том, что вы пытаетесь сохранить двоичные данные в текстовом файле. Попробуйте защитить данные или используйте bytea (с правильным кодированием/декодированием).

person Chris Travers    schedule 22.03.2013