コード例 #1
0
ファイル: task.py プロジェクト: xiaguangme/candle
def send_to_kindle(book_id, book_data_str, to_email):
    need_generate = True
    book_dir = 'data/%s' % book_id
    book_mobi_path = '%s/%s.mobi' % (book_dir, book_id)
    book_data = parse_book_data(book_data_str)

    # 是不是不需要新生成
    if not book_data['is_sample'] and os.path.exists(book_mobi_path):
        with open('%s/data.txt' % book_dir) as fp:
            old_book_data_str = fp.read()
        old_book_content_md5 = old_book_data_str.split(':', 2)[0]
        if md5(book_data['encrypted_content']).hexdigest() == old_book_content_md5:
            need_generate = False

    logger.info('book %s need generate? : %s', book_id, need_generate)

    if need_generate:
        if not os.path.isdir(book_dir):
            os.mkdir(book_dir)
        with open('%s/data.txt' % book_dir, 'w') as fp:
            fp.write(md5(book_data['encrypted_content']).hexdigest() + ':' + book_data_str.encode('utf-8'))
        logger.info('decrypting %s', book_id)
        book_content_data_str = decrypt(book_data['encrypted_content'])
        book_content_data = json.loads(book_content_data_str)
        logger.info('decrypt successful for %s', book_id)
        book_title = book_data['title']
        try:
            book_mobi_path = generate_book(book_id, book_title, book_content_data)
        except RuntimeError:
            book_mobi_path = None

    if book_mobi_path:
        subject = book_data.get('title', '') if to_email.endswith('@iduokan.com') else 'Convert'
        send_queue.enqueue(send_file_via_email, to_email, book_mobi_path, subject)
コード例 #2
0
ファイル: test_crypt.py プロジェクト: ihoover/crypto
 def test_point_encryption(self):
     
     m = ec.point(1,2,priv.A, priv.B, priv.prime)
     cipher = encrypt.encrypt(m, priv.base_point, priv.pub_raised_point)
     m2 = decrypt.decrypt(cipher, priv.exponent)
     
     self.assertEqual(m, m2)
コード例 #3
0
ファイル: local_decrypt.py プロジェクト: dyan0123/Utils
def handler_one_wav(file_path):
	is_decryptted = True
	one_wav = wav_data()
	dest_path = os.path.join(temp_path, file_path.split("/")[-1]) + ".enc"
	if one_wav.read_wav(file_path): #un-decryptted
		encrypt(file_path, dest_path)
		is_decryptted = False 
		pass
	else: #decryptted
		wav_file = os.path.join(temp_path, file_path.split("/")[-1][:-4])
		decrypter = decrypt.decrypt("key")
		decrypter.decrypt(file_path, wav_file)
		one_wav = wav_data()
		one_wav.read_wav(wav_file)
	if one_wav.wav_channels != 1:
		return
	if one_wav.wav_sample_rate != 16000:
		return

	tmp_list = dest_path.split("/")[-1].split("_")
	task_id = tmp_list[1]
	azure_file_name = "_".join([tmp_list[1], tmp_list[2]]) + "/" + dest_path.split("/")[-1]
	print(azure_file_name)
	if is_decryptted:
		#upload file_path
		print("decryptted")
		azure.upload(task_id, azure_file_name, file_path)
	else:
		#upload dest_path
		print("un-decryptted")
		azure.upload(task_id, azure_file_name, dest_path)
コード例 #4
0
def decrypt_if_not_db_file(file_name, key, extension=None):
    if is_funf_database(file_name):
        print "Already decrypted: '%s'" % file_name
        return True
    else:
        print ("Attempting to decrypt: '%s'..." % file_name),
        decrypt.decrypt([file_name], key, extension)
        if is_funf_database(file_name):
            print "Success!"
            os.remove(file_name+'.orig')
            return True
        else:
            print "FAILED!!!!"
            os.remove(file_name)
            os.remove(file_name+'.orig')
            return False
コード例 #5
0
    def decrypt(self, encyptedFile):
        if len(self.key) != 0:
            rsaDecrypt(self.key);
            return decrypt(self.key, encyptedFile);

        else:
            return
コード例 #6
0
ファイル: dbdecrypt.py プロジェクト: Versec/trafficsense
def decrypt_if_not_db_file(file_name, key, extension=None):
    if is_funf_database(file_name):
        print "Already decrypted: '%s'" % file_name
        return True
    else:
        print ("Attempting to decrypt: '%s'..." % file_name),
        decrypt.decrypt([file_name], key, extension)
        if is_funf_database(file_name):
            print "Success!"
            return True
        else:
            print "FAILED!!!!"
            print "File is either encrypted with another method, another key, or is not a valid sqlite3 db file."
            print "Keeping original file."
            shutil.move(decrypt.backup_file(file_name, extension), file_name)
            return False
コード例 #7
0
ファイル: decrypt_files.py プロジェクト: dyan0123/Utils
	def __init__(self):
		self.sqlserver = db_handler.sqlserver_handler()
		self.log = log.my_log.instance()
		self.downloader = download.download()
		self.decrypter = decrypt.decrypt("key")
		self.azure = azure_util.azure_handler()
		for queue in configure.queue_list:
			self.azure.create_queue(queue)
コード例 #8
0
def resetText(text_id, decryptor_id, decryptor_key_json):
    key = ndb.Key(model.Text, text_id)
    text = key.get()
    if not text:
        text = model.Text(key=key)
    text.content = open('texts/%s.txt' % text_id, 'rU').read()
    decryptor = {'id': decryptor_id, 'key':json.loads(decryptor_key_json)}
    text.encrypted = decrypt.decrypt(text.content, decryptor)
    text.put()
コード例 #9
0
ファイル: brute.py プロジェクト: nkman/Messi-crypt
def main():
	msg = raw_input('Encrypted Text : ')
	for i in range(0,len(msg)):
		print 'Trying with key #%s' % i
		word = decrypt(i,msg)
		if(CountWords(word) > 0.2): #Assuming 20 percenteg of words
			print word
			sys.exit()
	print 'Sorry Could not find the type of encryption'
	sys.exit()
コード例 #10
0
ファイル: client.py プロジェクト: nickedes/Crypteda
def decryption(cipher, key):
    dt = []
    key = to_hex(pad(key))[0]

    for block in cipher:
        dt.append(decrypt(block, key))
    final = ""
    for block in dt:
        final += to_str(block)
    return rmpad(final)
コード例 #11
0
ファイル: wwwirc.py プロジェクト: PSJoshi/botnet-lab
 def privmsg(self, user, channel, mesg):
     ##print mesg
     ##DECRYPT MESSAGE
     mesg = decrypt.decrypt(mesg)
     ##print mesg
     if self.factory.websocket:
         self.factory.websocket.write_message({"type": "chat",
                                               "user": user.split("!")[0],
                                               "message": mesg})
     else:
         print ("websocket not open")
コード例 #12
0
ファイル: cut_wav_proc.py プロジェクト: dyan0123/Utils
	def __init__(self):
		self.sqlserver = db_handler.sqlserver_handler()
		self.log = log.my_log.instance()
		self.cut_audio = cut_audio.audio_cut()
		self.azure = azure_util.azure_handler()
		self.decrypter = decrypt.decrypt("key")
		self.BloomFilter = BloomFilter.BloomFilter(0.001,3000000) 
		self.azure.create_queue(configure.cutted_queue)
		self.azure.create_blob(configure.cutted_blob)
		self.tag_task_list = configure.tag_task_list
		self.data_cnt = 0
コード例 #13
0
    def post(self):
        payload = self.request.body
        data = json.loads(payload)
        text = ndb.Key(urlsafe=data['text_key']).get()
        level_key = ndb.Key(urlsafe=data['level_key'])

        # TODO verify input (text must exist, decryptor valid etc.)
        
        decrypted = decrypt.decrypt(text.encrypted, data['decryptor']);
        win = decrypt.check_result(text, decrypted)
        self.response.out.write(
                json.dumps({'win':win, 'text':decrypted}))
        user = users.get_current_user()
        if user and win:
            # if the user is signed in, record they passed this level
            self.getUserTracker().recordWin(level_key)
コード例 #14
0
 def getfile(self):
     items=self.listView.selectedIndexes()
     r=req.get(address+"/receive/get/"+str(items[0].row()+1),auth=creds,verify=False)
     filename=self.files[items[0].row()]
     ver=req.get(address+"/receive/verify/"+str(items[0].row()+1),auth=creds,verify=False)
     signature=binascii.unhexlify(ver.json()["sign"])
     keycall=req.get(address+"/send/"+ver.json()["user"],auth=creds,verify=False)
     key=RsaPublicKey.Read(keycall.json()["key"])
     if key.Verify(r.content,signature):
         QMessageBox.about(self,"Info","File verified to be from "+ver.json()["user"])
     else:
         QMessageBox.about(self,"Info","Verification failed")
     decrypt_file(hashlib.sha256(str(creds[1])).digest(),creds[0]+"key.enc")
     open(filename,"w").write(decrypt(r.content,creds[0]+"key"))
     QMessageBox.about(self,"Info","File written to "+filename)
     os.remove(creds[0]+"key")
     os.system("gnome-open "+filename)
コード例 #15
0
ファイル: encrypt.py プロジェクト: matthewcummings/utils
      log.error('The input file, encryption password and/or output file were not specified\n%s' % usage)
      sys.exit(1)

   try:
      #Encrypt a copy of the input file
      in_file = file(orig_bfile,'rb')
      enc_bfile = '%s.enc' % orig_bfile
      out_file = file(enc_bfile,'wb')
      encrypt(enc_pw,in_file,out_file)
      log.info('Created %s, an encrypted copy of %s' % (enc_bfile,orig_bfile))

      #Decrypt and binary diff the encrypted copy against the original
      bfile_dec = '%s.dec' % orig_bfile
      in_file = file(enc_bfile,'rb')
      out_file = file(bfile_dec,'wb')
      decrypt(enc_pw,in_file,out_file)      

      #if binary_diff(bfile_dec,orig_bfile):
      if binary_diff(bfile_dec,orig_bfile):         
         log.info('Decrypted version %s, diffs successfully against original %s' % (bfile_dec,orig_bfile))
      else:
         log.info('BAD ENCRYPTION COPY: decrypted version %s and original %s DIFFER' % (bfile_dec,orig_bfile))
      log.info('Encryption job complete')
   except Exception, e:
      log.exception(e)
      sys.exit(1)


   

コード例 #16
0
import utils
import encrypt
import decrypt

words = utils.word_set
letters = utils.letter_set

on_loop = 0

print "Welcome to the Navajo Code Talkers Encryption / Decryption tool."

while on_loop == 0:
        print "Enter 1 to Encrypt a message"
        print "Enter 2 to Decrypt a message"
        print "Enter 3 to Quit"
        while True:
                try:
                        choice = int(raw_input("Your choice:  "))
                        break
                except ValueError:
                        print "That's not a valid choice. Please try again."
        if choice == 1:
                print "Time to encrypt"
                encrypt.encrypt(words,letters)
        elif choice == 2:
                print "Time to decrypt"
                decrypt.decrypt(words,letters)
        elif choice == 3:
                print "Thank you, have a nice day."
                sys.exit()
コード例 #17
0
ファイル: main.py プロジェクト: htadg/Encryptor
import encrypt
import decrypt
import datetime
import msvcrt

while True:
    encrypted = encrypt.encrypt(raw_input("\n\n\nEnter message to encrypt -- "))
    print "\nEncrypted Message -- \n"
    print encrypted
    print "\nDecrypted Message -- \n"
    msg = decrypt.decrypt(encrypted, str(datetime.datetime.now()))
    print msg
    print "\n\n\nPress Enter to try once again or any other key to quit......"
    if ord(msvcrt.getch()) != 13:
        exit(0)
コード例 #18
0
ファイル: download.py プロジェクト: dyan0123/Utils
	def __init__(self):
		self.log = log.my_log.instance()
		self.decrypter = decrypt.decrypt("key")
コード例 #19
0
ファイル: crypter.py プロジェクト: iFDVCS/spy-cy
def run_decrypt():
    form = DecryptionForm(request.form)
    if request.method == 'POST' and form.validate():
        enter_key_input = form.enter_key
        encrypted_DNA_input = form.encrypted_DNA
        return render_template('decrypt_result.html', title="Decrypt", form=form, result = decrypt(enter_key_input, encrypted_DNA_input))
    else:
        return render_template('decrypt.html', title="Decrypt", form=form)
コード例 #20
0
ファイル: run.py プロジェクト: alyakhtar/Crypteda
inp = to_hex(pad(plain))
key = to_hex(pad(key))[0]

ct = []
for block in inp:
    ct.append(encrypt(block, key))

encrypted_text = ""
for block in ct:
    encrypted_text += to_str(block)

print("\n")
print("Encrypted Text: ", encrypted_text)
print("\n")

print("\n-------------------- Decryption ----------------------\n")

dt = []
for block in ct:
    dt.append(decrypt(block, key))
    print()

print("\n---------------------- Result ------------------------\n")

final = ""
for block in dt:
    final += to_str(block)

print("Decrypted Text: ", rmpad(final))
コード例 #21
0
    keyMask = unpack('L', header[0x10:0x14])[0] ^ 0x43DE7C19
    header[0x10:0x14] = array('B' , pack('L', keyMask))
    
with open(cpzFilename, 'rb') as cpz:
    fullHeader = array('B')
    fullHeader.fromfile(cpz, indexLength + 4)
    
    fullHeader[4:8] = array('B' , pack('L', indexCount))
    fullHeader[0x8:0xC] = array('B' , pack('L', indexLength))
    fullHeader[0x10:0x14] = array('B' , pack('L', keyMask))

keyMask = keyMask ^ 0x7BF4A539
#解密index
delta = 12 - 20

decrypt(fullHeader, 0x14, indexLength + 4, delta, keyMask)

#循环提取文件

i = 0
pos = 0x14
while i < indexCount:
    itemIndexLength = unpack('L', fullHeader[pos:pos + 4])[0]
    itemLength = unpack('L', fullHeader[pos + 4:pos + 8])[0]
    itemOffset = unpack('L', fullHeader[pos + 8:pos + 0x0C])[0]
    itemFilename = fullHeader[pos + 0x18:pos + itemIndexLength].tostring().strip('\0')
#    if itemFilename != 'config02_chip.pb3':
#        i += 1
#        pos += itemIndexLength
#        continue
    itemKeyMask = unpack('L', fullHeader[pos + 0x14:pos + 0x18])[0]
コード例 #22
0
ファイル: imgclient.py プロジェクト: manavsharma22/NetStag
        # print "payload: {}".format(packet.getlayer(ICMP).payload)
        if packet.haslayer(ICMP) and str(packet.getlayer(ICMP).type) == "8":

            raw = packet.getlayer(ICMP).seq

            #if raw not in download:
            count +=1
            ans.append(chr(raw))
            #download.append(raw)
            print "Total packets recieved: {}".format(count)

ans1 = []
for i in range(0,len(ans),2):
    ans1.append(ans[i])

text = "".join(ans1)
#print "Recieved Data: " + text
ans = []

for i in range(0,len(text),20):
	data = decrypt.decrypt(text[i:i+20])
	#print "DATA: " + str(data)
	ans.append(data)
#print "FINAL ANS: " + "".join(ans)	
image = Image.open(io.BytesIO("".join(ans)))
image.save("testresult.png")
#data = decrypt.decrypt(text)
f.write("".join(ans))

f.close()
コード例 #23
0
ファイル: packcpz3.py プロジェクト: nsmr0604/cpz3unpack
def main(): 
    from struct import unpack, pack
    from array import array
    from decrypt import decrypt, encrypt, decryptPs2, encryptPs2
    from lzss import decode, encode
    import codecs
    from scriptgetter import ScriptGetter
    
    cpzFilename = ur"D:\eroge\明日の君と逢うために\data\pack\scriptback.cpz"
    newFilename = ur"D:\eroge\明日の君と逢うために\data\pack\script.cpz"
    
    relation_filename = ur"D:\data\workspace\asutame_text\etc\relation.txt"
    source_path = ur"D:\data\workspace\asutame_text\source" + u"\\"
    translated_path = ur"D:\data\workspace\asutame_text\已译" + u"\\"
    source_encoding = "shift-jis"
    translated_encoding = "gb18030"
    
    #解密文件头
    with open(cpzFilename, 'rb') as cpz:
        header = array('B')
        header.fromfile(cpz, 0x18)
        
        indexCount = unpack('L', header[4:8])[0] ^ 0x5E9C4F37
        header[4:8] = array('B' , pack('L', indexCount))
        
        indexLength = unpack('L', header[0x8:0xC])[0] ^ 0xF32AED17
        header[0x8:0xC] = array('B' , pack('L', indexLength))
                                
        keyMask = unpack('L', header[0x10:0x14])[0] ^ 0xDDDDDDDD
        header[0x10:0x14] = array('B' , pack('L', keyMask))
        
    with open(cpzFilename, 'rb') as cpz:
        fullHeader = array('B')
        fullHeader.fromfile(cpz, indexLength + 0x14)
        
        fullHeader[4:8] = array('B' , pack('L', indexCount))
        fullHeader[0x8:0xC] = array('B' , pack('L', indexLength))
        fullHeader[0x10:0x14] = array('B' , pack('L', keyMask))
    
    keyMask = keyMask ^ 0x7BF4A539
    #解密index
    delta = 12 - 20
    
    decrypt(fullHeader, 0x14, indexLength + 0x14, delta, keyMask)
    
    #循环提取文件
    newCpzHeader = array('B', fullHeader.tostring())
    newCpzContent = array('B')
    i = 0
    pos = 0x14
    while i < indexCount:
        itemIndexLength = unpack('L', fullHeader[pos:pos + 4])[0]
        itemLength = unpack('L', fullHeader[pos + 4:pos + 8])[0]
        itemOffset = unpack('L', fullHeader[pos + 8:pos + 0x0C])[0]
        itemFilename = fullHeader[pos + 0x18:pos + itemIndexLength].tostring().strip('\0')
            
        itemKeyMask = unpack('L', fullHeader[pos + 0x14:pos + 0x18])[0]
        itemKeyMask = itemKeyMask ^ 0xC7F5DA63
        with open(cpzFilename, 'rb') as cpz:
            cpz.seek(itemOffset + indexLength + 0x14, 0)
            item = array('B')
            item.fromfile(cpz, itemLength)
            
            getter = ScriptGetter(itemFilename + '.txt', relation_filename, source_path, translated_path, source_encoding, translated_encoding)
            
            #只封包relation中定义的文本
            if hasattr(getter, 'start_id'):
                skipcount = getter.start_id
                decrypt(item, 0, itemLength, 12, itemKeyMask)
                
                #解密&解压ps2
                
                decryptPs2(item, 0x30, itemLength - 0x30, unpack('L', item[0x0c:0x10])[0])
                itemHeader = item[0:0x30]
                itemContent = decode(item, 0x30, itemLength - 0x30)
                
                scriptLength = unpack('L', itemHeader[0x1C:0x20])[0]
                scriptOffset = len(itemContent) - scriptLength
                
                #读取txt文件,封入封包
                txtOffset = 0
                
                #新文本的偏移和长度
                textOffset = {}
                text = ''
                count = 1
                #<则不动的文本的序号297
    #            skipcount = 297
                #不跳过的第一条文本的原偏移。从这个位置开始放入新文本
                skipoffset = 0
                    
                with open(source_path + itemFilename + '.txt', 'rb') as inputTxtFile:
                    for t in inputTxtFile:
                        if t.startswith(';'):
                            continue
                        if len(t.strip()) == 0:
                            continue
                        if count < skipcount and t.find('=') >= 0:
                            count += 1
                            continue
                        eq = t.find('=')
                        line = t[eq + 1:].strip('\r\n') + '\0'
                        newline = getter.get_script(codecs.decode(t.split('=')[0], source_encoding))
                        if newline:
                            try:
    #                                temp = codecs.decode(t[eq + 1:].strip('\r\n'), 'shift-jis')
                                line = codecs.encode(newline, translated_encoding) + '\0'
                                pass
                            except UnicodeEncodeError:
                                print "ERROR: can't encode " + newline
                        
                        textOffset[count] = (len(text), len(line))
                        text += line
                        count += 1
                count = 1
                lastOffset = (0, 0)
                j = 0
                itemContentString = itemContent.tostring()
                scriptEnd = scriptOffset - 8
                while j < scriptEnd:
                    findJ = itemContentString.find('\x01\x02\x20\x01', j + 1)
                    if findJ >= 0:
                        j = findJ
                    else:
                        break
#                for j in xrange(0, scriptOffset - 8):
#                    if itemContent[j]+(itemContent[j + 1]<<8)+(itemContent[j + 2]<<16)+(itemContent[j + 3]<<24) == 0x01200201: #unpack 太慢
#                    if (itemContent[j] == 0x01) and (itemContent[j + 1] == 0x02) and (itemContent[j + 2] == 0x20) and (itemContent[j + 3] == 0x01): #上一行太慢
                        
                    sentenceOffset = unpack('L', itemContent[j + 4:j + 8])[0]
#                    sentence = itemContentString[scriptOffset + sentenceOffset:scriptOffset + sentenceOffset + 255].split('\0')[0]  #slow
                    sentenceEnd = itemContentString.find('\0', scriptOffset + sentenceOffset)
                    sentence = itemContentString[scriptOffset + sentenceOffset:sentenceEnd]
                    
                    if sentence == '':
                        if lastOffset[0] + lastOffset[1] - 1 + skipoffset>0:
                            itemContent[j + 4:j + 8] = array('B', pack('L', lastOffset[0] + lastOffset[1] - 1 + skipoffset))
                        #itemContent[j + 4:j + 8] = array('B', pack('L', 0))
                        continue
                    if count < skipcount:
                        count += 1
                        continue
                    if count == skipcount:
                        skipoffset = sentenceOffset
                    
                    itemContent[j + 4:j + 8] = array('B', pack('L', textOffset[count][0] + skipoffset))
                    lastOffset = textOffset[count]
                    count += 1
                        
                
                textArray = array('B', text)
                itemHeader[0x1C:0x20] = array('B', pack('L', len(textArray)))
                #itemHeader[0x28:0x2C] = array('B', pack('L', scriptOffset + skipoffset + len(textArray)))
                itemHeader[0x28:0x2C] = array('B', pack('L', scriptOffset * 2 + skipoffset + len(textArray)))
    
                #itemContent = itemContent[0:scriptOffset] + textArray
                itemContent = itemContent[0:scriptOffset + skipoffset] + textArray
        
                #压缩
                itemContent = encode(itemContent, 0, len(itemContent))
                item = itemHeader + itemContent
                encryptPs2(item, 0x30, len(itemContent), unpack('L', item[0x0c:0x10])[0])
                
                #加密
                encrypt(item, 0, len(itemContent) + 0x30, 12, itemKeyMask)
            
            itemOffset = len(newCpzContent)
            newCpzHeader[pos + 8:pos + 0x0C] = array('B', pack('L', itemOffset))
            
            itemLength = len(item)
            newCpzHeader[pos + 4:pos + 8] = array('B', pack('L', itemLength))
            
            #将此内容加入
            newCpzContent.fromstring(item.tostring())
            
            print itemFilename + ' added'
            
        pos += itemIndexLength
        i += 1
    
    
    delta = 12 - 20
    
    encrypt(newCpzHeader, 0x14, indexLength + 0x14, delta, keyMask)
    
    indexCount = unpack('L', newCpzHeader[4:8])[0] ^ 0x5E9C4F37
    newCpzHeader[4:8] = array('B' , pack('L', indexCount))
    
    indexLength = unpack('L', newCpzHeader[0x8:0xC])[0] ^ 0xF32AED17
    newCpzHeader[0x8:0xC] = array('B' , pack('L', indexLength))
                            
    keyMask = unpack('L', newCpzHeader[0x10:0x14])[0] ^ 0xDDDDDDDD
    newCpzHeader[0x10:0x14] = array('B' , pack('L', keyMask))
    
    with open(newFilename, 'wb') as newCpz:
        newCpzHeader.tofile(newCpz)
    #    for i in (0x33 ,0x25 ,0xAD ,0xBA ,0xA5 ,0x22 ,0x31 ,0xF1 ,0x08 ,0x69 ,0x82 ,0xC2 ,0xFE ,0xCC ,0x16 ,0x47):
    #        newCpz.write(chr(i))
        newCpzContent.tofile(newCpz) 
コード例 #24
0
ファイル: datahandle.py プロジェクト: CleyFaye/FOS_View
 def __init__(self, srcFile):
     jsonStr = decrypt(srcFile)
     jsonObj = json.loads(jsonStr)
     super(Vault, self).__init__(jsonObj)
     self.mergeDwellers()
     self.mergeRooms()
コード例 #25
0
ファイル: render.py プロジェクト: bigfool/candle
        if text_align in ['left', 'right', 'center']:
            classes.append('p_align_' + text_align)

    text = data.get('text')

    render_data = {
        'text': text,
        'classes': ' '.join(classes)
    }

    # image
    if content_type == 'illus':
        render_data['image'] = data['size']['orig']['src']

    if content_type == 'headline':
        render_data['toc_anchor'] = add_to_table_of_contens(text)

    return render(content_type, render_data)


if __name__ == '__main__':
    import json
    from decrypt import decrypt
    book_id = 'e1531222'
    with open('data/' + book_id + '/data.txt') as fp:
        file_content = fp.read()
    _, title, content = file_content.split(':')[:3]
    json_str = decrypt(content)
    data = json.loads(json_str)
    generate_book(book_id, title.decode('utf-8'), data)