|
# -*- coding: utf-8 -*-
from __future__ import division
import random
from django_logit import logit
from django_response import response
from mch.models import BrandInfo, ModelImageInfo, ModelInfo
from utils.algorithm.b64 import b64_decrypt, b64_encrypt
from utils.algorithm.caesar import caesar_decrypt, caesar_encrypt
from utils.algorithm.rsalg import rsa_decrypt, rsa_encrypt
# CIPHER_ALGORITHM = ('CAESAR', 'B64', 'RSA')
CIPHER_ALGORITHM = ('CAESAR', )
CIPHER_PREFIX = {
'CAESAR': '0',
'B64': '1',
'RSA': '2',
}
@logit(res=True)
def encrypt(request):
plaintext = request.POST.get('plaintext', '')
alg = random.choice(CIPHER_ALGORITHM)
if alg == 'CAESAR':
ciphertext = caesar_encrypt(plaintext)
elif alg == 'B64':
ciphertext = b64_encrypt(plaintext)
elif alg == 'RSA':
ciphertext = rsa_encrypt(plaintext)
else:
ciphertext = plaintext
return response(200, data={
'ciphertext': u'{prefix}+{cipherlen}+{ciphertext}'.format(
prefix=CIPHER_PREFIX.get(alg, ''),
cipherlen=len(ciphertext),
ciphertext=ciphertext,
),
})
@logit(res=True)
def decrypt(request):
ciphertext = request.POST.get('ciphertext', '')
prefix, cipherlen, ciphertext = ciphertext.split('+', 2)
ciphertext = ciphertext[:int(cipherlen)]
if prefix == CIPHER_PREFIX['CAESAR']:
plaintext = caesar_decrypt(ciphertext)
elif prefix == CIPHER_PREFIX['B64']:
plaintext = b64_decrypt(ciphertext)
elif prefix == CIPHER_PREFIX['RSA']:
plaintext = rsa_decrypt(ciphertext)
else:
plaintext = ciphertext
# brand_id#model_id#distributor_id#sn#time
# AAAA#AAAAAA#AAAAA#AAAAAAAAAAAAAA#180224
brand_pk, model_pk, distributor_pk, sn, time = plaintext.split('#')
try:
brand = BrandInfo.objects.get(pk=brand_pk)
except BrandInfo.DoesNotExist:
brand = None
try:
model = ModelInfo.objects.get(pk=model_pk)
except ModelInfo.DoesNotExist:
model = None
return response(200, data={
'plaintext': plaintext,
'logo_url': brand.brand_logo_url if brand else '',
'model_imgs': model.images if model else [],
'goodsInfo': {
'Brand': brand.brand_name if brand else '',
'Model': model.model_name if model else '',
'SerialNo': sn,
}
})
|