拍爱

encrypt_views.py 1.2KB

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