2011-10-27 43 views
3

我想使用公/私鑰來保護我的UserInfo數據。我是PyCrypto和PostgreSQL的新手。如何使用pycrypto將RSA加密數據存儲到postgresql?

我有一些項目澄清:

  1. 是公共密鑰和私有密鑰的恆定值?
  2. 如果它是恆定的,我該如何妥善保存它?
  3. 最後但最重要的是,我如何將加密數據存儲到PostgreSQL?並檢索它進行驗證?

你能指導我如何處理Crypto.PublicKey.RSA作爲保護我的數據的方法。

環境:Python 2.5中,PyCrypto 2.3時,PostgreSQL 8.3 UTF-8編碼

的UserInfo模型:

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) 

UPDATES1 tests.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) 
+0

任何人的想法都歡迎。 – eros

+0

變量'簽名'和可能'enc [0]'是字節。爲了使它們更「可讀」,使用'enc [0] .encode('base64')'來存儲和'enc [0] .decode('base64')'來檢索。 – KitKat

回答

0

你的問題是,你正試圖將二進制數據存儲在一個文本文件。嘗試鎧裝數據或使用bytea(使用正確的編碼/解碼)。

相關問題