BVB Source Codes

DeDRM_tools Show ignobleepub.py Source code

Return Download DeDRM_tools: download ignobleepub.py Source code - Download DeDRM_tools Source code - Type:.py
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from __future__ import with_statement
  5.  
  6. # ignobleepub.pyw, version 3.8
  7. # Copyright 漏 2009-2010 by i鈾abbages
  8.  
  9. # Released under the terms of the GNU General Public Licence, version 3
  10. # <http://www.gnu.org/licenses/>
  11.  
  12. # Modified 2010鈥?013 by some_updates, DiapDealer and Apprentice Alf
  13.  
  14. # Windows users: Before running this program, you must first install Python 2.6
  15. #   from <http://www.python.org/download/> and PyCrypto from
  16. #   <http://www.voidspace.org.uk/python/modules.shtml#pycrypto> (make sure to
  17. #   install the version for Python 2.6).  Save this script file as
  18. #   ineptepub.pyw and double-click on it to run it.
  19. #
  20. # Mac OS X users: Save this script file as ineptepub.pyw.  You can run this
  21. #   program from the command line (pythonw ineptepub.pyw) or by double-clicking
  22. #   it when it has been associated with PythonLauncher.
  23.  
  24. # Revision history:
  25. #   1 - Initial release
  26. #   2 - Added OS X support by using OpenSSL when available
  27. #   3 - screen out improper key lengths to prevent segfaults on Linux
  28. #   3.1 - Allow Windows versions of libcrypto to be found
  29. #   3.2 - add support for encoding to 'utf-8' when building up list of files to decrypt from encryption.xml
  30. #   3.3 - On Windows try PyCrypto first, OpenSSL next
  31. #   3.4 - Modify interface to allow use with import
  32. #   3.5 - Fix for potential problem with PyCrypto
  33. #   3.6 - Revised to allow use in calibre plugins to eliminate need for duplicate code
  34. #   3.7 - Tweaked to match ineptepub more closely
  35. #   3.8 - Fixed to retain zip file metadata (e.g. file modification date)
  36. #   3.9 - moved unicode_argv call inside main for Windows DeDRM compatibility
  37. #   4.0 - Work if TkInter is missing
  38.  
  39. """
  40. Decrypt Barnes & Noble encrypted ePub books.
  41. """
  42.  
  43. __license__ = 'GPL v3'
  44. __version__ = "4.0"
  45.  
  46. import sys
  47. import os
  48. import traceback
  49. import zlib
  50. import zipfile
  51. from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
  52. from contextlib import closing
  53. import xml.etree.ElementTree as etree
  54.  
  55. # Wrap a stream so that output gets flushed immediately
  56. # and also make sure that any unicode strings get
  57. # encoded using "replace" before writing them.
  58. class SafeUnbuffered:
  59.     def __init__(self, stream):
  60.         self.stream = stream
  61.         self.encoding = stream.encoding
  62.         if self.encoding == None:
  63.             self.encoding = "utf-8"
  64.     def write(self, data):
  65.         if isinstance(data,unicode):
  66.             data = data.encode(self.encoding,"replace")
  67.         self.stream.write(data)
  68.         self.stream.flush()
  69.     def __getattr__(self, attr):
  70.         return getattr(self.stream, attr)
  71.  
  72. try:
  73.     from calibre.constants import iswindows, isosx
  74. except:
  75.     iswindows = sys.platform.startswith('win')
  76.     isosx = sys.platform.startswith('darwin')
  77.  
  78. def unicode_argv():
  79.     if iswindows:
  80.         # Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
  81.         # strings.
  82.  
  83.         # Versions 2.x of Python don't support Unicode in sys.argv on
  84.         # Windows, with the underlying Windows API instead replacing multi-byte
  85.         # characters with '?'.
  86.  
  87.  
  88.         from ctypes import POINTER, byref, cdll, c_int, windll
  89.         from ctypes.wintypes import LPCWSTR, LPWSTR
  90.  
  91.         GetCommandLineW = cdll.kernel32.GetCommandLineW
  92.         GetCommandLineW.argtypes = []
  93.         GetCommandLineW.restype = LPCWSTR
  94.  
  95.         CommandLineToArgvW = windll.shell32.CommandLineToArgvW
  96.         CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
  97.         CommandLineToArgvW.restype = POINTER(LPWSTR)
  98.  
  99.         cmd = GetCommandLineW()
  100.         argc = c_int(0)
  101.         argv = CommandLineToArgvW(cmd, byref(argc))
  102.         if argc.value > 0:
  103.             # Remove Python executable and commands if present
  104.             start = argc.value - len(sys.argv)
  105.             return [argv[i] for i in
  106.                     xrange(start, argc.value)]
  107.         return [u"ineptepub.py"]
  108.     else:
  109.         argvencoding = sys.stdin.encoding
  110.         if argvencoding == None:
  111.             argvencoding = "utf-8"
  112.         return [arg if (type(arg) == unicode) else unicode(arg,argvencoding) for arg in sys.argv]
  113.  
  114.  
  115. class IGNOBLEError(Exception):
  116.     pass
  117.  
  118. def _load_crypto_libcrypto():
  119.     from ctypes import CDLL, POINTER, c_void_p, c_char_p, c_int, c_long, \
  120.         Structure, c_ulong, create_string_buffer, cast
  121.     from ctypes.util import find_library
  122.  
  123.     if iswindows:
  124.         libcrypto = find_library('libeay32')
  125.     else:
  126.         libcrypto = find_library('crypto')
  127.  
  128.     if libcrypto is None:
  129.         raise IGNOBLEError('libcrypto not found')
  130.     libcrypto = CDLL(libcrypto)
  131.  
  132.     AES_MAXNR = 14
  133.  
  134.     c_char_pp = POINTER(c_char_p)
  135.     c_int_p = POINTER(c_int)
  136.  
  137.     class AES_KEY(Structure):
  138.         _fields_ = [('rd_key', c_long * (4 * (AES_MAXNR + 1))),
  139.                     ('rounds', c_int)]
  140.     AES_KEY_p = POINTER(AES_KEY)
  141.  
  142.     def F(restype, name, argtypes):
  143.         func = getattr(libcrypto, name)
  144.         func.restype = restype
  145.         func.argtypes = argtypes
  146.         return func
  147.  
  148.     AES_set_decrypt_key = F(c_int, 'AES_set_decrypt_key',
  149.                             [c_char_p, c_int, AES_KEY_p])
  150.     AES_cbc_encrypt = F(None, 'AES_cbc_encrypt',
  151.                         [c_char_p, c_char_p, c_ulong, AES_KEY_p, c_char_p,
  152.                          c_int])
  153.  
  154.     class AES(object):
  155.         def __init__(self, userkey):
  156.             self._blocksize = len(userkey)
  157.             if (self._blocksize != 16) and (self._blocksize != 24) and (self._blocksize != 32) :
  158.                 raise IGNOBLEError('AES improper key used')
  159.                 return
  160.             key = self._key = AES_KEY()
  161.             rv = AES_set_decrypt_key(userkey, len(userkey) * 8, key)
  162.             if rv < 0:
  163.                 raise IGNOBLEError('Failed to initialize AES key')
  164.  
  165.         def decrypt(self, data):
  166.             out = create_string_buffer(len(data))
  167.             iv = ("\x00" * self._blocksize)
  168.             rv = AES_cbc_encrypt(data, out, len(data), self._key, iv, 0)
  169.             if rv == 0:
  170.                 raise IGNOBLEError('AES decryption failed')
  171.             return out.raw
  172.  
  173.     return AES
  174.  
  175. def _load_crypto_pycrypto():
  176.     from Crypto.Cipher import AES as _AES
  177.  
  178.     class AES(object):
  179.         def __init__(self, key):
  180.             self._aes = _AES.new(key, _AES.MODE_CBC, '\x00'*16)
  181.  
  182.         def decrypt(self, data):
  183.             return self._aes.decrypt(data)
  184.  
  185.     return AES
  186.  
  187. def _load_crypto():
  188.     AES = None
  189.     cryptolist = (_load_crypto_libcrypto, _load_crypto_pycrypto)
  190.     if sys.platform.startswith('win'):
  191.         cryptolist = (_load_crypto_pycrypto, _load_crypto_libcrypto)
  192.     for loader in cryptolist:
  193.         try:
  194.             AES = loader()
  195.             break
  196.         except (ImportError, IGNOBLEError):
  197.             pass
  198.     return AES
  199.  
  200. AES = _load_crypto()
  201.  
  202. META_NAMES = ('mimetype', 'META-INF/rights.xml', 'META-INF/encryption.xml')
  203. NSMAP = {'adept': 'http://ns.adobe.com/adept',
  204.          'enc': 'http://www.w3.org/2001/04/xmlenc#'}
  205.  
  206. class Decryptor(object):
  207.     def __init__(self, bookkey, encryption):
  208.         enc = lambda tag: '{%s}%s' % (NSMAP['enc'], tag)
  209.         self._aes = AES(bookkey)
  210.         encryption = etree.fromstring(encryption)
  211.         self._encrypted = encrypted = set()
  212.         expr = './%s/%s/%s' % (enc('EncryptedData'), enc('CipherData'),
  213.                                enc('CipherReference'))
  214.         for elem in encryption.findall(expr):
  215.             path = elem.get('URI', None)
  216.             if path is not None:
  217.                 path = path.encode('utf-8')
  218.                 encrypted.add(path)
  219.  
  220.     def decompress(self, bytes):
  221.         dc = zlib.decompressobj(-15)
  222.         bytes = dc.decompress(bytes)
  223.         ex = dc.decompress('Z') + dc.flush()
  224.         if ex:
  225.             bytes = bytes + ex
  226.         return bytes
  227.  
  228.     def decrypt(self, path, data):
  229.         if path in self._encrypted:
  230.             data = self._aes.decrypt(data)[16:]
  231.             data = data[:-ord(data[-1])]
  232.             data = self.decompress(data)
  233.         return data
  234.  
  235. # check file to make check whether it's probably an Adobe Adept encrypted ePub
  236. def ignobleBook(inpath):
  237.     with closing(ZipFile(open(inpath, 'rb'))) as inf:
  238.         namelist = set(inf.namelist())
  239.         if 'META-INF/rights.xml' not in namelist or \
  240.            'META-INF/encryption.xml' not in namelist:
  241.             return False
  242.         try:
  243.             rights = etree.fromstring(inf.read('META-INF/rights.xml'))
  244.             adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
  245.             expr = './/%s' % (adept('encryptedKey'),)
  246.             bookkey = ''.join(rights.findtext(expr))
  247.             if len(bookkey) == 64:
  248.                 return True
  249.         except:
  250.             # if we couldn't check, assume it is
  251.             return True
  252.     return False
  253.  
  254. def decryptBook(keyb64, inpath, outpath):
  255.     if AES is None:
  256.         raise IGNOBLEError(u"PyCrypto or OpenSSL must be installed.")
  257.     key = keyb64.decode('base64')[:16]
  258.     aes = AES(key)
  259.     with closing(ZipFile(open(inpath, 'rb'))) as inf:
  260.         namelist = set(inf.namelist())
  261.         if 'META-INF/rights.xml' not in namelist or \
  262.            'META-INF/encryption.xml' not in namelist:
  263.             print u"{0:s} is DRM-free.".format(os.path.basename(inpath))
  264.             return 1
  265.         for name in META_NAMES:
  266.             namelist.remove(name)
  267.         try:
  268.             rights = etree.fromstring(inf.read('META-INF/rights.xml'))
  269.             adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
  270.             expr = './/%s' % (adept('encryptedKey'),)
  271.             bookkey = ''.join(rights.findtext(expr))
  272.             if len(bookkey) != 64:
  273.                 print u"{0:s} is not a secure Barnes & Noble ePub.".format(os.path.basename(inpath))
  274.                 return 1
  275.             bookkey = aes.decrypt(bookkey.decode('base64'))
  276.             bookkey = bookkey[:-ord(bookkey[-1])]
  277.             encryption = inf.read('META-INF/encryption.xml')
  278.             decryptor = Decryptor(bookkey[-16:], encryption)
  279.             kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
  280.             with closing(ZipFile(open(outpath, 'wb'), 'w', **kwds)) as outf:
  281.                 zi = ZipInfo('mimetype')
  282.                 zi.compress_type=ZIP_STORED
  283.                 try:
  284.                     # if the mimetype is present, get its info, including time-stamp
  285.                     oldzi = inf.getinfo('mimetype')
  286.                     # copy across fields to be preserved
  287.                     zi.date_time = oldzi.date_time
  288.                     zi.comment = oldzi.comment
  289.                     zi.extra = oldzi.extra
  290.                     zi.internal_attr = oldzi.internal_attr
  291.                     # external attributes are dependent on the create system, so copy both.
  292.                     zi.external_attr = oldzi.external_attr
  293.                     zi.create_system = oldzi.create_system
  294.                 except:
  295.                     pass
  296.                 outf.writestr(zi, inf.read('mimetype'))
  297.                 for path in namelist:
  298.                     data = inf.read(path)
  299.                     zi = ZipInfo(path)
  300.                     zi.compress_type=ZIP_DEFLATED
  301.                     try:
  302.                         # get the file info, including time-stamp
  303.                         oldzi = inf.getinfo(path)
  304.                         # copy across useful fields
  305.                         zi.date_time = oldzi.date_time
  306.                         zi.comment = oldzi.comment
  307.                         zi.extra = oldzi.extra
  308.                         zi.internal_attr = oldzi.internal_attr
  309.                         # external attributes are dependent on the create system, so copy both.
  310.                         zi.external_attr = oldzi.external_attr
  311.                         zi.create_system = oldzi.create_system
  312.                     except:
  313.                         pass
  314.                     outf.writestr(zi, decryptor.decrypt(path, data))
  315.         except:
  316.             print u"Could not decrypt {0:s} because of an exception:\n{1:s}".format(os.path.basename(inpath), traceback.format_exc())
  317.             return 2
  318.     return 0
  319.  
  320.  
  321. def cli_main():
  322.     sys.stdout=SafeUnbuffered(sys.stdout)
  323.     sys.stderr=SafeUnbuffered(sys.stderr)
  324.     argv=unicode_argv()
  325.     progname = os.path.basename(argv[0])
  326.     if len(argv) != 4:
  327.         print u"usage: {0} <keyfile.b64> <inbook.epub> <outbook.epub>".format(progname)
  328.         return 1
  329.     keypath, inpath, outpath = argv[1:]
  330.     userkey = open(keypath,'rb').read()
  331.     result = decryptBook(userkey, inpath, outpath)
  332.     if result == 0:
  333.         print u"Successfully decrypted {0:s} as {1:s}".format(os.path.basename(inpath),os.path.basename(outpath))
  334.     return result
  335.  
  336. def gui_main():
  337.     try:
  338.         import Tkinter
  339.         import Tkconstants
  340.         import tkMessageBox
  341.         import traceback
  342.     except:
  343.         return cli_main()
  344.  
  345.     class DecryptionDialog(Tkinter.Frame):
  346.         def __init__(self, root):
  347.             Tkinter.Frame.__init__(self, root, border=5)
  348.             self.status = Tkinter.Label(self, text=u"Select files for decryption")
  349.             self.status.pack(fill=Tkconstants.X, expand=1)
  350.             body = Tkinter.Frame(self)
  351.             body.pack(fill=Tkconstants.X, expand=1)
  352.             sticky = Tkconstants.E + Tkconstants.W
  353.             body.grid_columnconfigure(1, weight=2)
  354.             Tkinter.Label(body, text=u"Key file").grid(row=0)
  355.             self.keypath = Tkinter.Entry(body, width=30)
  356.             self.keypath.grid(row=0, column=1, sticky=sticky)
  357.             if os.path.exists(u"bnepubkey.b64"):
  358.                 self.keypath.insert(0, u"bnepubkey.b64")
  359.             button = Tkinter.Button(body, text=u"...", command=self.get_keypath)
  360.             button.grid(row=0, column=2)
  361.             Tkinter.Label(body, text=u"Input file").grid(row=1)
  362.             self.inpath = Tkinter.Entry(body, width=30)
  363.             self.inpath.grid(row=1, column=1, sticky=sticky)
  364.             button = Tkinter.Button(body, text=u"...", command=self.get_inpath)
  365.             button.grid(row=1, column=2)
  366.             Tkinter.Label(body, text=u"Output file").grid(row=2)
  367.             self.outpath = Tkinter.Entry(body, width=30)
  368.             self.outpath.grid(row=2, column=1, sticky=sticky)
  369.             button = Tkinter.Button(body, text=u"...", command=self.get_outpath)
  370.             button.grid(row=2, column=2)
  371.             buttons = Tkinter.Frame(self)
  372.             buttons.pack()
  373.             botton = Tkinter.Button(
  374.                 buttons, text=u"Decrypt", width=10, command=self.decrypt)
  375.             botton.pack(side=Tkconstants.LEFT)
  376.             Tkinter.Frame(buttons, width=10).pack(side=Tkconstants.LEFT)
  377.             button = Tkinter.Button(
  378.                 buttons, text=u"Quit", width=10, command=self.quit)
  379.             button.pack(side=Tkconstants.RIGHT)
  380.  
  381.         def get_keypath(self):
  382.             keypath = tkFileDialog.askopenfilename(
  383.                 parent=None, title=u"Select Barnes & Noble \'.b64\' key file",
  384.                 defaultextension=u".b64",
  385.                 filetypes=[('base64-encoded files', '.b64'),
  386.                            ('All Files', '.*')])
  387.             if keypath:
  388.                 keypath = os.path.normpath(keypath)
  389.                 self.keypath.delete(0, Tkconstants.END)
  390.                 self.keypath.insert(0, keypath)
  391.             return
  392.  
  393.         def get_inpath(self):
  394.             inpath = tkFileDialog.askopenfilename(
  395.                 parent=None, title=u"Select B&N-encrypted ePub file to decrypt",
  396.                 defaultextension=u".epub", filetypes=[('ePub files', '.epub')])
  397.             if inpath:
  398.                 inpath = os.path.normpath(inpath)
  399.                 self.inpath.delete(0, Tkconstants.END)
  400.                 self.inpath.insert(0, inpath)
  401.             return
  402.  
  403.         def get_outpath(self):
  404.             outpath = tkFileDialog.asksaveasfilename(
  405.                 parent=None, title=u"Select unencrypted ePub file to produce",
  406.                 defaultextension=u".epub", filetypes=[('ePub files', '.epub')])
  407.             if outpath:
  408.                 outpath = os.path.normpath(outpath)
  409.                 self.outpath.delete(0, Tkconstants.END)
  410.                 self.outpath.insert(0, outpath)
  411.             return
  412.  
  413.         def decrypt(self):
  414.             keypath = self.keypath.get()
  415.             inpath = self.inpath.get()
  416.             outpath = self.outpath.get()
  417.             if not keypath or not os.path.exists(keypath):
  418.                 self.status['text'] = u"Specified key file does not exist"
  419.                 return
  420.             if not inpath or not os.path.exists(inpath):
  421.                 self.status['text'] = u"Specified input file does not exist"
  422.                 return
  423.             if not outpath:
  424.                 self.status['text'] = u"Output file not specified"
  425.                 return
  426.             if inpath == outpath:
  427.                 self.status['text'] = u"Must have different input and output files"
  428.                 return
  429.             userkey = open(keypath,'rb').read()
  430.             self.status['text'] = u"Decrypting..."
  431.             try:
  432.                 decrypt_status = decryptBook(userkey, inpath, outpath)
  433.             except Exception, e:
  434.                 self.status['text'] = u"Error: {0}".format(e.args[0])
  435.                 return
  436.             if decrypt_status == 0:
  437.                 self.status['text'] = u"File successfully decrypted"
  438.             else:
  439.                 self.status['text'] = u"The was an error decrypting the file."
  440.  
  441.     root = Tkinter.Tk()
  442.     root.title(u"Barnes & Noble ePub Decrypter v.{0}".format(__version__))
  443.     root.resizable(True, False)
  444.     root.minsize(300, 0)
  445.     DecryptionDialog(root).pack(fill=Tkconstants.X, expand=1)
  446.     root.mainloop()
  447.     return 0
  448.  
  449. if __name__ == '__main__':
  450.     if len(sys.argv) > 1:
  451.         sys.exit(cli_main())
  452.     sys.exit(gui_main())
  453.  
downloadignobleepub.py Source code - Download DeDRM_tools Source code
Related Source Codes/Software:
kcp - KCP - A Fast and Reliable ARQ Protocol 2017-04-08
cloc - cloc counts blank lines, comment lines, and physic... 2017-04-08
nvidia-docker - Build and run Docker containers leveraging NVIDIA ... 2017-04-08
quickstart - Angular 2 QuickStart - source from the documentati... 2017-04-08
jQuery-Autocomplete - Ajax Autocomplete for jQuery allows you to easily ... 2017-04-08
fuckitjs - The Original Javascript Error Steamroller 2017-04-09
eslint-plugin-react - React specific linting rules for ESLint 2017-04-09
husky - 2017-04-09
electron-builder - A complete solution to package and build a ready f... 2017-04-09
jsfeat - JavaScript Computer Vision library. 2017-04-16
flakes - Flakes is an Admin Template Framework. A combinati... 2017-04-15
capstone - Capstone disassembly/disassembler framework: Core ... 2017-04-15
nginx-resources - A collection of resources covering Nginx, Nginx + ... 2017-04-15
utron - A lightweight MVC framework for Go(Golang) 2017-04-15
cfssl - CFSSL: Cloudflare's PKI and TLS toolkit ... 2017-04-15
HandBrake - HandBrake's main development repository ... 2017-04-15
Awesome-Networking - A curated list of awesome networking libraries, re... 2017-04-15
react-sortable-hoc - A set of higher-order components to turn any list ... 2017-04-15
jugglingdb - Multi-database ORM for nodejs: redis, mongodb, mys... 2017-04-15

 Back to top