CodernityDB / docs /

#!/usr/bin/env python

from CodernityDB.hash_index import UniqueHashIndex
from import Storage
from CodernityDB.database import Database
from hashlib import sha256

import salsa20
import marshal
import os

class Salsa20Storage(Storage):

    def __init__(self, db_path, name):
        super(Salsa20Storage, self).__init__(db_path, name)
        self.enc_key = None

    def data_from(self, data):
        iv = data[:8]
        sal = salsa20.Salsa20(self.enc_key, iv, 20)
        s_data = sal.decrypt(data[8:])
        m_data = marshal.loads(s_data)
        return m_data

    def data_to(self, data):
        iv = os.urandom(8)
        m_data = marshal.dumps(data)
        sal = salsa20.Salsa20(self.enc_key, iv, 20)
        s_data = sal.encrypt(m_data)
        return iv + s_data

class EncUniqueHashIndex(UniqueHashIndex):

    __enc_key = 'a' * 32

    custom_header = """
from demo_secure_storage import Salsa20Storage
from hashlib import sha256"""

    def __init__(self, *args, **kwargs):
        super(EncUniqueHashIndex, self).__init__(*args, **kwargs)

    def enc_key(self):
        return self.__enc_key

    def enc_key(self, value):
        if len(value) != 32:
            self.__enc_key = sha256(value).digest()
            self.__enc_key = value = self.__enc_key

def main():
    db = Database('/tmp/demo_secure')
    key = 'abcdefgh'
    id_ind = EncUniqueHashIndex(db.path, 'id', storage_class='Salsa20Storage')
    db.id_ind.enc_key = key

    for x in xrange(100):
        db.insert(dict(x=x, data='testing'))

    dbr = Database('/tmp/demo_secure')
    dbr.id_ind.enc_key = key

    for curr in dbr.all('id', limit=5):
        print curr

if __name__ == "__main__":
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.