BVB Source Codes

DeDRM_tools Show ignoblekeygen.py Source code

Return Download DeDRM_tools: download ignoblekeygen.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. # ignoblekeygen.pyw, version 2.5
  7. # Copyright 漏 2009-2010 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.
  15. #   We recommend ActiveState Python 2.7.X for Windows (x86) from
  16. #   http://www.activestate.com/activepython/downloads.
  17. #   You must also install PyCrypto from
  18. #   http://www.voidspace.org.uk/python/modules.shtml#pycrypto
  19. #   (make certain to install the version for Python 2.7).
  20. #   Then save this script file as ignoblekeygen.pyw and double-click on it to run it.
  21. #
  22. # Mac OS X users: Save this script file as ignoblekeygen.pyw.  You can run this
  23. #   program from the command line (python ignoblekeygen.pyw) or by double-clicking
  24. #   it when it has been associated with PythonLauncher.
  25.  
  26. # Revision history:
  27. #   1 - Initial release
  28. #   2 - Add OS X support by using OpenSSL when available (taken/modified from ineptepub v5)
  29. #   2.1 - Allow Windows versions of libcrypto to be found
  30. #   2.2 - On Windows try PyCrypto first and then OpenSSL next
  31. #   2.3 - Modify interface to allow use of import
  32. #   2.4 - Improvements to UI and now works in plugins
  33. #   2.5 - Additional improvement for unicode and plugin support
  34. #   2.6 - moved unicode_argv call inside main for Windows DeDRM compatibility
  35. #   2.7 - Work if TkInter is missing
  36. #   2.8 - Fix bug in stand-alone use (import tkFileDialog)
  37.  
  38. """
  39. Generate Barnes & Noble EPUB user key from name and credit card number.
  40. """
  41.  
  42. __license__ = 'GPL v3'
  43. __version__ = "2.8"
  44.  
  45. import sys
  46. import os
  47. import hashlib
  48.  
  49. # Wrap a stream so that output gets flushed immediately
  50. # and also make sure that any unicode strings get
  51. # encoded using "replace" before writing them.
  52. class SafeUnbuffered:
  53.     def __init__(self, stream):
  54.         self.stream = stream
  55.         self.encoding = stream.encoding
  56.         if self.encoding == None:
  57.             self.encoding = "utf-8"
  58.     def write(self, data):
  59.         if isinstance(data,unicode):
  60.             data = data.encode(self.encoding,"replace")
  61.         self.stream.write(data)
  62.         self.stream.flush()
  63.     def __getattr__(self, attr):
  64.         return getattr(self.stream, attr)
  65.  
  66. try:
  67.     from calibre.constants import iswindows, isosx
  68. except:
  69.     iswindows = sys.platform.startswith('win')
  70.     isosx = sys.platform.startswith('darwin')
  71.  
  72. def unicode_argv():
  73.     if iswindows:
  74.         # Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
  75.         # strings.
  76.  
  77.         # Versions 2.x of Python don't support Unicode in sys.argv on
  78.         # Windows, with the underlying Windows API instead replacing multi-byte
  79.         # characters with '?'.  So use shell32.GetCommandLineArgvW to get sys.argv
  80.         # as a list of Unicode strings and encode them as utf-8
  81.  
  82.         from ctypes import POINTER, byref, cdll, c_int, windll
  83.         from ctypes.wintypes import LPCWSTR, LPWSTR
  84.  
  85.         GetCommandLineW = cdll.kernel32.GetCommandLineW
  86.         GetCommandLineW.argtypes = []
  87.         GetCommandLineW.restype = LPCWSTR
  88.  
  89.         CommandLineToArgvW = windll.shell32.CommandLineToArgvW
  90.         CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
  91.         CommandLineToArgvW.restype = POINTER(LPWSTR)
  92.  
  93.         cmd = GetCommandLineW()
  94.         argc = c_int(0)
  95.         argv = CommandLineToArgvW(cmd, byref(argc))
  96.         if argc.value > 0:
  97.             # Remove Python executable and commands if present
  98.             start = argc.value - len(sys.argv)
  99.             return [argv[i] for i in
  100.                     xrange(start, argc.value)]
  101.         # if we don't have any arguments at all, just pass back script name
  102.         # this should never happen
  103.         return [u"ignoblekeygen.py"]
  104.     else:
  105.         argvencoding = sys.stdin.encoding
  106.         if argvencoding == None:
  107.             argvencoding = "utf-8"
  108.         return [arg if (type(arg) == unicode) else unicode(arg,argvencoding) for arg in sys.argv]
  109.  
  110.  
  111. class IGNOBLEError(Exception):
  112.     pass
  113.  
  114. def _load_crypto_libcrypto():
  115.     from ctypes import CDLL, POINTER, c_void_p, c_char_p, c_int, c_long, \
  116.         Structure, c_ulong, create_string_buffer, cast
  117.     from ctypes.util import find_library
  118.  
  119.     if iswindows:
  120.         libcrypto = find_library('libeay32')
  121.     else:
  122.         libcrypto = find_library('crypto')
  123.  
  124.     if libcrypto is None:
  125.         raise IGNOBLEError('libcrypto not found')
  126.     libcrypto = CDLL(libcrypto)
  127.  
  128.     AES_MAXNR = 14
  129.  
  130.     c_char_pp = POINTER(c_char_p)
  131.     c_int_p = POINTER(c_int)
  132.  
  133.     class AES_KEY(Structure):
  134.         _fields_ = [('rd_key', c_long * (4 * (AES_MAXNR + 1))),
  135.                     ('rounds', c_int)]
  136.     AES_KEY_p = POINTER(AES_KEY)
  137.  
  138.     def F(restype, name, argtypes):
  139.         func = getattr(libcrypto, name)
  140.         func.restype = restype
  141.         func.argtypes = argtypes
  142.         return func
  143.  
  144.     AES_set_encrypt_key = F(c_int, 'AES_set_encrypt_key',
  145.                             [c_char_p, c_int, AES_KEY_p])
  146.     AES_cbc_encrypt = F(None, 'AES_cbc_encrypt',
  147.                         [c_char_p, c_char_p, c_ulong, AES_KEY_p, c_char_p,
  148.                          c_int])
  149.  
  150.     class AES(object):
  151.         def __init__(self, userkey, iv):
  152.             self._blocksize = len(userkey)
  153.             self._iv = iv
  154.             key = self._key = AES_KEY()
  155.             rv = AES_set_encrypt_key(userkey, len(userkey) * 8, key)
  156.             if rv < 0:
  157.                 raise IGNOBLEError('Failed to initialize AES Encrypt key')
  158.  
  159.         def encrypt(self, data):
  160.             out = create_string_buffer(len(data))
  161.             rv = AES_cbc_encrypt(data, out, len(data), self._key, self._iv, 1)
  162.             if rv == 0:
  163.                 raise IGNOBLEError('AES encryption failed')
  164.             return out.raw
  165.  
  166.     return AES
  167.  
  168. def _load_crypto_pycrypto():
  169.     from Crypto.Cipher import AES as _AES
  170.  
  171.     class AES(object):
  172.         def __init__(self, key, iv):
  173.             self._aes = _AES.new(key, _AES.MODE_CBC, iv)
  174.  
  175.         def encrypt(self, data):
  176.             return self._aes.encrypt(data)
  177.  
  178.     return AES
  179.  
  180. def _load_crypto():
  181.     AES = None
  182.     cryptolist = (_load_crypto_libcrypto, _load_crypto_pycrypto)
  183.     if sys.platform.startswith('win'):
  184.         cryptolist = (_load_crypto_pycrypto, _load_crypto_libcrypto)
  185.     for loader in cryptolist:
  186.         try:
  187.             AES = loader()
  188.             break
  189.         except (ImportError, IGNOBLEError):
  190.             pass
  191.     return AES
  192.  
  193. AES = _load_crypto()
  194.  
  195. def normalize_name(name):
  196.     return ''.join(x for x in name.lower() if x != ' ')
  197.  
  198.  
  199. def generate_key(name, ccn):
  200.     # remove spaces and case from name and CC numbers.
  201.     if type(name)==unicode:
  202.         name = name.encode('utf-8')
  203.     if type(ccn)==unicode:
  204.         ccn = ccn.encode('utf-8')
  205.  
  206.     name = normalize_name(name) + '\x00'
  207.     ccn = normalize_name(ccn) + '\x00'
  208.  
  209.     name_sha = hashlib.sha1(name).digest()[:16]
  210.     ccn_sha = hashlib.sha1(ccn).digest()[:16]
  211.     both_sha = hashlib.sha1(name + ccn).digest()
  212.     aes = AES(ccn_sha, name_sha)
  213.     crypt = aes.encrypt(both_sha + ('\x0c' * 0x0c))
  214.     userkey = hashlib.sha1(crypt).digest()
  215.     return userkey.encode('base64')
  216.  
  217.  
  218.  
  219.  
  220. def cli_main():
  221.     sys.stdout=SafeUnbuffered(sys.stdout)
  222.     sys.stderr=SafeUnbuffered(sys.stderr)
  223.     argv=unicode_argv()
  224.     progname = os.path.basename(argv[0])
  225.     if AES is None:
  226.         print "%s: This script requires OpenSSL or PyCrypto, which must be installed " \
  227.               "separately.  Read the top-of-script comment for details." % \
  228.               (progname,)
  229.         return 1
  230.     if len(argv) != 4:
  231.         print u"usage: {0} <Name> <CC#> <keyfileout.b64>".format(progname)
  232.         return 1
  233.     name, ccn, keypath = argv[1:]
  234.     userkey = generate_key(name, ccn)
  235.     open(keypath,'wb').write(userkey)
  236.     return 0
  237.  
  238.  
  239. def gui_main():
  240.     try:
  241.         import Tkinter
  242.         import Tkconstants
  243.         import tkMessageBox
  244.         import tkFileDialog
  245.         import traceback
  246.     except:
  247.         return cli_main()
  248.  
  249.     class DecryptionDialog(Tkinter.Frame):
  250.         def __init__(self, root):
  251.             Tkinter.Frame.__init__(self, root, border=5)
  252.             self.status = Tkinter.Label(self, text=u"Enter parameters")
  253.             self.status.pack(fill=Tkconstants.X, expand=1)
  254.             body = Tkinter.Frame(self)
  255.             body.pack(fill=Tkconstants.X, expand=1)
  256.             sticky = Tkconstants.E + Tkconstants.W
  257.             body.grid_columnconfigure(1, weight=2)
  258.             Tkinter.Label(body, text=u"Account Name").grid(row=0)
  259.             self.name = Tkinter.Entry(body, width=40)
  260.             self.name.grid(row=0, column=1, sticky=sticky)
  261.             Tkinter.Label(body, text=u"CC#").grid(row=1)
  262.             self.ccn = Tkinter.Entry(body, width=40)
  263.             self.ccn.grid(row=1, column=1, sticky=sticky)
  264.             Tkinter.Label(body, text=u"Output file").grid(row=2)
  265.             self.keypath = Tkinter.Entry(body, width=40)
  266.             self.keypath.grid(row=2, column=1, sticky=sticky)
  267.             self.keypath.insert(2, u"bnepubkey.b64")
  268.             button = Tkinter.Button(body, text=u"...", command=self.get_keypath)
  269.             button.grid(row=2, column=2)
  270.             buttons = Tkinter.Frame(self)
  271.             buttons.pack()
  272.             botton = Tkinter.Button(
  273.                 buttons, text=u"Generate", width=10, command=self.generate)
  274.             botton.pack(side=Tkconstants.LEFT)
  275.             Tkinter.Frame(buttons, width=10).pack(side=Tkconstants.LEFT)
  276.             button = Tkinter.Button(
  277.                 buttons, text=u"Quit", width=10, command=self.quit)
  278.             button.pack(side=Tkconstants.RIGHT)
  279.  
  280.         def get_keypath(self):
  281.             keypath = tkFileDialog.asksaveasfilename(
  282.                 parent=None, title=u"Select B&N ePub key file to produce",
  283.                 defaultextension=u".b64",
  284.                 filetypes=[('base64-encoded files', '.b64'),
  285.                            ('All Files', '.*')])
  286.             if keypath:
  287.                 keypath = os.path.normpath(keypath)
  288.                 self.keypath.delete(0, Tkconstants.END)
  289.                 self.keypath.insert(0, keypath)
  290.             return
  291.  
  292.         def generate(self):
  293.             name = self.name.get()
  294.             ccn = self.ccn.get()
  295.             keypath = self.keypath.get()
  296.             if not name:
  297.                 self.status['text'] = u"Name not specified"
  298.                 return
  299.             if not ccn:
  300.                 self.status['text'] = u"Credit card number not specified"
  301.                 return
  302.             if not keypath:
  303.                 self.status['text'] = u"Output keyfile path not specified"
  304.                 return
  305.             self.status['text'] = u"Generating..."
  306.             try:
  307.                 userkey = generate_key(name, ccn)
  308.             except Exception, e:
  309.                 self.status['text'] = u"Error: (0}".format(e.args[0])
  310.                 return
  311.             open(keypath,'wb').write(userkey)
  312.             self.status['text'] = u"Keyfile successfully generated"
  313.  
  314.     root = Tkinter.Tk()
  315.     if AES is None:
  316.         root.withdraw()
  317.         tkMessageBox.showerror(
  318.             "Ignoble EPUB Keyfile Generator",
  319.             "This script requires OpenSSL or PyCrypto, which must be installed "
  320.             "separately.  Read the top-of-script comment for details.")
  321.         return 1
  322.     root.title(u"Barnes & Noble ePub Keyfile Generator v.{0}".format(__version__))
  323.     root.resizable(True, False)
  324.     root.minsize(300, 0)
  325.     DecryptionDialog(root).pack(fill=Tkconstants.X, expand=1)
  326.     root.mainloop()
  327.     return 0
  328.  
  329. if __name__ == '__main__':
  330.     if len(sys.argv) > 1:
  331.         sys.exit(cli_main())
  332.     sys.exit(gui_main())
  333.  
downloadignoblekeygen.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