No Description

encrypt_views.py 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # -*- coding: utf-8 -*-
  2. from __future__ import division
  3. import random
  4. from django_logit import logit
  5. from django_response import response
  6. from mch.models import BrandInfo, ModelImageInfo, ModelInfo
  7. from utils.algorithm.b64 import b64_decrypt, b64_encrypt
  8. from utils.algorithm.caesar import caesar_decrypt, caesar_encrypt
  9. from utils.algorithm.rsalg import rsa_decrypt, rsa_encrypt
  10. # CIPHER_ALGORITHM = ('CAESAR', 'B64', 'RSA')
  11. CIPHER_ALGORITHM = ('CAESAR', )
  12. CIPHER_PREFIX = {
  13. 'CAESAR': '0',
  14. 'B64': '1',
  15. 'RSA': '2',
  16. }
  17. @logit(res=True)
  18. def encrypt(request):
  19. plaintext = request.POST.get('plaintext', '')
  20. alg = random.choice(CIPHER_ALGORITHM)
  21. if alg == 'CAESAR':
  22. ciphertext = caesar_encrypt(plaintext)
  23. elif alg == 'B64':
  24. ciphertext = b64_encrypt(plaintext)
  25. elif alg == 'RSA':
  26. ciphertext = rsa_encrypt(plaintext)
  27. else:
  28. ciphertext = plaintext
  29. return response(200, data={
  30. 'ciphertext': u'{prefix}+{cipherlen}+{ciphertext}'.format(
  31. prefix=CIPHER_PREFIX.get(alg, ''),
  32. cipherlen=len(ciphertext),
  33. ciphertext=ciphertext,
  34. ),
  35. })
  36. @logit(res=True)
  37. def decrypt(request):
  38. ciphertext = request.POST.get('ciphertext', '')
  39. prefix, cipherlen, ciphertext = ciphertext.split('+', 2)
  40. ciphertext = ciphertext[:int(cipherlen)]
  41. if prefix == CIPHER_PREFIX['CAESAR']:
  42. plaintext = caesar_decrypt(ciphertext)
  43. elif prefix == CIPHER_PREFIX['B64']:
  44. plaintext = b64_decrypt(ciphertext)
  45. elif prefix == CIPHER_PREFIX['RSA']:
  46. plaintext = rsa_decrypt(ciphertext)
  47. else:
  48. plaintext = ciphertext
  49. # brand_id#model_id#distributor_id#sn#time
  50. # AAAA#AAAAAA#AAAAA#AAAAAAAAAAAAAA#180224
  51. brand_pk, model_pk, distributor_pk, sn, time = plaintext.split('#')
  52. try:
  53. brand = BrandInfo.objects.get(pk=brand_pk)
  54. except BrandInfo.DoesNotExist:
  55. brand = None
  56. try:
  57. model = ModelInfo.objects.get(pk=model_pk)
  58. except ModelInfo.DoesNotExist:
  59. model = None
  60. return response(200, data={
  61. 'plaintext': plaintext,
  62. 'logo_url': brand.brand_logo_url if brand else '',
  63. 'model_imgs': model.images if model else [],
  64. 'goodsInfo': {
  65. 'Brand': brand.brand_name if brand else '',
  66. 'ModelID': model_pk,
  67. 'Model': model.model_name if model else '',
  68. 'SerialNo': sn,
  69. }
  70. })