项目作者: alpden550

项目描述 :
Encrypt and decrypt field for Django model.
高级语言: Python
项目地址: git://github.com/alpden550/django-encrypt-decrypt.git
创建时间: 2021-06-10T08:45:42Z
项目社区:https://github.com/alpden550/django-encrypt-decrypt

开源协议:MIT License

下载


ORM Encrypt Decrypt Fields

A Django and SQLAlchemy model field that encrypts your data based SHA256 algorithm and Fernet (symmetric encryption)
when saving to the model field. The fernet module guarantees that data encrypted using it cannot be further manipulated
or read without the key. It keeps data always encrypted in the database.

Also, possible to use it directly with the Crypto class.

Check

How install

  1. pip install encrypt-decrypt-fields

Usage

For Django use project secret key or own:

  1. from django.db import models
  2. from encrypt_decrypt_fields import EncryptedBinaryField
  3. class DemoModel(models.Model):
  4. password = EncryptedBinaryField(blank=True, null=True)
  1. from .models import DemoModel
  2. DemoModel.objects.create(password='password')
  3. demo = DemoModel.objects.get(id=1)
  4. print(demo.password.to_bytes())
  5. # b'gAAAAABgxGVVeTPV9i1nPNl91Ss4XVH0rD6eJCgOWIOeRwtagp12gBJg9DL_HXODTDW0WKsqc8Z9vsuHUiAr3qQVE9YQmTd3pg=='

To read bytes in postgres, use to_bytes() method of memoryview

  1. obj.password.to_bytes()

or

  1. bytes(obj.password, 'utf-8')

To decrypt value use Crypto class:

  1. from django.conf import settings
  2. from encrypt_decrypt_fields import Crypto
  3. from .models import DemoModel
  4. obj = DemoModel.objects.get(id=1)
  5. decrypted = Crypto(settings.SECRET_KEY).decrypt_token(obj.password.to_bytes())
  6. print(decrypted)
  7. # 'password'

For SQLAlchemy, it is similar:

  1. from sqlalchemy import Column, Integer, String
  2. from sqlalchemy import create_engine
  3. from sqlalchemy.orm import declarative_base, sessionmaker
  4. from encrypt_decrypt_fields import Crypto, EncryptedAlchemyBinaryField
  5. Base = declarative_base()
  6. engine = create_engine("sqlite:///:memory:", echo=True)
  7. class Demo(Base):
  8. __tablename__ = 'demo'
  9. id = Column(Integer, primary_key=True)
  10. name = Column(String)
  11. password = Column(EncryptedAlchemyBinaryField(key='secret'), nullable=True)
  12. Session = sessionmaker(bind=engine)
  13. session = Session()
  14. demo = session.query(Demo).first()
  15. Crypto('secret').decrypt_token(demo.password)