title: How to store RSA encrypted data to postgresql by using pycrypto?
body: <p>I want to use Public/Private key to secure my UserInfo data. I'm new with PyCrypto and PostgreSQL.</p>
  
  <p>I have some items to clarify:</p>
  
  <ol>
  <li>Are Public Key and Private Key constant values?</li>
  <li>If it is constant, how can I store it properly?</li>
  <li>Lastly but the most important, how can I store my encrypted data to PostgreSQL? and retrieve it for verification?</li>
  </ol>
  
  <p>Would you guide me on how to dealt with Crypto.PublicKey.RSA as method to secure my data.</p>
  
  <p>Environment: Python 2.5, PyCrypto 2.3, PostgreSQL 8.3 UTF-8 encoding</p>
  
  <p>UserInfo model:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p><strong>UPDATES1</strong>
  tests.py:</p>
  
  <pre><code># -*- 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"
  </code></pre>
  
  <p>result here (failed):</p>
  
  <pre><code>======================================================================
  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)
  </code></pre>