拍爱

encrypt_views.py 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # -*- coding: utf-8 -*-
  2. from __future__ import division
  3. import random
  4. from utils.algorithm.b64 import b64_decrypt, b64_encrypt
  5. from utils.algorithm.rsalg import rsa_decrypt, rsa_encrypt
  6. from utils.error.response_utils import response
  7. CIPHER_ALGORITHM = ('B64', 'RSA')
  8. CIPHER_PREFIX = {
  9. 'B64': 'alg1',
  10. 'RSA': 'alg2',
  11. }
  12. def encrypt(request):
  13. plaintext = request.POST.get('plaintext', '')
  14. alg = random.choice(CIPHER_ALGORITHM)
  15. if alg == 'B64':
  16. ciphertext = b64_encrypt(plaintext)
  17. elif alg == 'RSA':
  18. ciphertext = rsa_encrypt(plaintext)
  19. else:
  20. ciphertext = plaintext
  21. return response(200, data={
  22. 'ciphertext': u'%s+%s' % (CIPHER_PREFIX.get(alg, ''), ciphertext),
  23. })
  24. def decrypt(request):
  25. ciphertext = request.POST.get('ciphertext', '')
  26. alg, ciphertext = ciphertext.split('+', 1)
  27. if alg == CIPHER_PREFIX['B64']:
  28. plaintext = b64_decrypt(ciphertext)
  29. elif alg == CIPHER_PREFIX['RSA']:
  30. plaintext = rsa_decrypt(ciphertext)
  31. else:
  32. plaintext = ciphertext
  33. return response(200, data={
  34. 'plaintext': plaintext,
  35. })