拍爱

encrypt_views.py 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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_ALGORITHM = ('B64', )
  9. CIPHER_PREFIX = {
  10. 'B64': 'alg1',
  11. 'RSA': 'alg2',
  12. }
  13. def encrypt(request):
  14. plaintext = request.POST.get('plaintext', '')
  15. alg = random.choice(CIPHER_ALGORITHM)
  16. if alg == 'B64':
  17. ciphertext = b64_encrypt(plaintext)
  18. elif alg == 'RSA':
  19. ciphertext = rsa_encrypt(plaintext)
  20. else:
  21. ciphertext = plaintext
  22. return response(200, data={
  23. 'ciphertext': u'%s+%s' % (CIPHER_PREFIX.get(alg, ''), ciphertext),
  24. })
  25. def decrypt(request):
  26. ciphertext = request.POST.get('ciphertext', '')
  27. alg, ciphertext = ciphertext.split('+', 1)
  28. if alg == CIPHER_PREFIX['B64']:
  29. plaintext = b64_decrypt(ciphertext)
  30. elif alg == CIPHER_PREFIX['RSA']:
  31. plaintext = rsa_decrypt(ciphertext)
  32. else:
  33. plaintext = ciphertext
  34. return response(200, data={
  35. 'plaintext': plaintext,
  36. })