mirror of
https://github.com/noDRM/DeDRM_tools.git
synced 2025-10-23 23:07:47 -04:00
Compare commits
No commits in common. "master" and "v6.6.3" have entirely different histories.
170 changed files with 12340 additions and 18079 deletions
17
.gitattributes
vendored
Normal file
17
.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
|
||||
# Custom for Visual Studio
|
||||
*.cs diff=csharp
|
||||
|
||||
# Standard to msysgit
|
||||
*.doc diff=astextplain
|
||||
*.DOC diff=astextplain
|
||||
*.docx diff=astextplain
|
||||
*.DOCX diff=astextplain
|
||||
*.dot diff=astextplain
|
||||
*.DOT diff=astextplain
|
||||
*.pdf diff=astextplain
|
||||
*.PDF diff=astextplain
|
||||
*.rtf diff=astextplain
|
||||
*.RTF diff=astextplain
|
||||
41
.github/ISSUE_TEMPLATE/QUESTION.yml
vendored
41
.github/ISSUE_TEMPLATE/QUESTION.yml
vendored
|
|
@ -1,41 +0,0 @@
|
|||
name: Question
|
||||
description: Questions for DeDRM Project
|
||||
body:
|
||||
- type: textarea
|
||||
id: question
|
||||
attributes:
|
||||
label: Question / bug report
|
||||
description: Please enter your question / your bug report.
|
||||
- type: input
|
||||
id: calibre-version
|
||||
attributes:
|
||||
label: Which version of Calibre are you running?
|
||||
description: "Example: 6.23"
|
||||
placeholder: "6.23"
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: plugin-version
|
||||
attributes:
|
||||
label: Which version of the DeDRM plugin are you running?
|
||||
description: "Example: v10.0.2"
|
||||
placeholder: "v10.0.2"
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: kindle-version
|
||||
attributes:
|
||||
label: If applicable, which version of the Kindle software are you running?
|
||||
description: "Example: 1.24"
|
||||
placeholder: "Leave empty if unrelated to Kindle books"
|
||||
validations:
|
||||
required: false
|
||||
- type: textarea
|
||||
id: log
|
||||
attributes:
|
||||
label: Log output
|
||||
description: If applicable, please post your log output here - into the code block.
|
||||
value: |
|
||||
```log
|
||||
Paste log output here.
|
||||
```
|
||||
52
.github/workflows/main.yml
vendored
52
.github/workflows/main.yml
vendored
|
|
@ -1,52 +0,0 @@
|
|||
name: Package plugin
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
package:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
|
||||
- name: Package
|
||||
run: python3 make_release.py
|
||||
|
||||
- name: Upload
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: plugin
|
||||
path: |
|
||||
DeDRM_tools_*.zip
|
||||
DeDRM_tools.zip
|
||||
|
||||
- name: Prepare release
|
||||
run: cp DeDRM_tools.zip DeDRM_alpha_${{ github.sha }}.zip
|
||||
|
||||
|
||||
- uses: dev-drprasad/delete-older-releases@v0.2.1
|
||||
with:
|
||||
repo: noDRM/DeDRM_tools_autorelease
|
||||
keep_latest: 0
|
||||
delete_tags: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.AUTORELEASE_KEY }}
|
||||
|
||||
- name: Auto-release
|
||||
id: autorelease
|
||||
uses: softprops/action-gh-release@v1
|
||||
with:
|
||||
tag_name: autorelease_${{ github.sha }}
|
||||
repository: noDRM/DeDRM_tools_autorelease
|
||||
token: ${{ secrets.AUTORELEASE_KEY }}
|
||||
name: Automatic alpha release with latest changes
|
||||
body: |
|
||||
This release is automatically generated by Github for each commit.
|
||||
|
||||
This means, every time a change is made to the repo, a release with an untested copy of the plugin at that stage will be created. This will contain the most up-to-date code, but it's not tested at all and may be broken.
|
||||
|
||||
Last update based on Git commit [${{ github.sha }}](https://github.com/noDRM/DeDRM_tools/commit/${{ github.sha }}).
|
||||
prerelease: true
|
||||
draft: false
|
||||
files: DeDRM_alpha_${{ github.sha }}.zip
|
||||
99
.gitignore
vendored
99
.gitignore
vendored
|
|
@ -1,9 +1,96 @@
|
|||
# Mac files
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
env/
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.coverage
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
|
||||
# Translations
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# =========================
|
||||
# Operating System Files
|
||||
# =========================
|
||||
|
||||
# OSX
|
||||
# =========================
|
||||
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# local test data
|
||||
/user_data/
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Cache
|
||||
/DeDRM_plugin/__pycache__
|
||||
/DeDRM_plugin/standalone/__pycache__
|
||||
# Files that might appear on external disk
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
# Windows
|
||||
# =========================
|
||||
|
||||
# Windows image file caches
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
|
||||
# Folder config file
|
||||
Desktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
|
|
|||
|
|
@ -13,21 +13,21 @@ platforms.
|
|||
|
||||
#### Install plugins
|
||||
- Download the DeDRM `.zip` archive from DeDRM_tools'
|
||||
[latest release](https://github.com/noDRM/DeDRM_tools/releases/latest).
|
||||
[latest release](https://github.com/apprenticeharper/DeDRM_tools/releases/latest).
|
||||
Then unzip it.
|
||||
- Add the DeDRM plugin to Calibre:
|
||||
```
|
||||
cd *the unzipped DeDRM_tools folder*
|
||||
calibre-customize --add DeDRM_plugin.zip
|
||||
calibre-customize --add DeDRM_calibre_plugin/DeDRM_plugin.zip
|
||||
```
|
||||
- Add the Obok plugin:
|
||||
```
|
||||
calibre-customize --add Obok_plugin.zip
|
||||
calibre-customize --add Obok_calibre_plugin/obok_plugin.zip
|
||||
```
|
||||
|
||||
#### Enter your keys
|
||||
- Figure out what format DeDRM wants your key in by looking in
|
||||
[the code that handles that](DeDRM_plugin/prefs.py).
|
||||
[the code that handles that](src/prefs.py).
|
||||
- For Kindle eInk devices, DeDRM expects you to put a list of serial
|
||||
numbers in the `serials` field: `"serials": ["012345689abcdef"]` or
|
||||
`"serials": ["1111111111111111", "2222222222222222"]`.
|
||||
|
|
|
|||
113
CHANGELOG.md
113
CHANGELOG.md
|
|
@ -1,113 +0,0 @@
|
|||
# Changelog
|
||||
|
||||
List of changes since the fork of Apprentice Harper's repository:
|
||||
|
||||
## Fixes in v10.0.0 (2021-11-17):
|
||||
|
||||
- CI testing / linting removed as that always failed anyways. The CI now "just" packages the plugin.
|
||||
- ~Support for the Readium LCP DRM (also known as "CARE DRM" or "TEA DRM"). This supports EPUB and PDF files. It does not yet support Readium LCPDF/LPF/LCPA/LCPAU/LCPDI files, as I don't have access to any of these. If you have an LCP-protected file in one of these formats that this plugin does not work with, please open [an issue](https://github.com/noDRM/DeDRM_tools/issues) and attach the file to the report.~ (removed due to a DMCA request, see #18 )
|
||||
- Add new Github issue report form which forces the user to include stuff like their Calibre version to hopefully increase the quality of bug reports.
|
||||
- Issues with PDF files in Calibre 5 should be fixed (merged [apprenticeharper/DeDRM_tools#1689](https://github.com/apprenticeharper/DeDRM_tools/pull/1689) ).
|
||||
- Fixed tons of issues with the B&N PDF DRM removal script ignoblepdf.py. It looks like that has never been tested since the move to Python3. I have integrated the B&N-specific code into ineptpdf.py, the original ignoblepdf.py is now unused. Fairly untested as I don't have any PDFs with B&N DRM.
|
||||
- Issues with Obok key retrieval fixed (merged [apprenticeharper/DeDRM_tools#1691](https://github.com/apprenticeharper/DeDRM_tools/pull/1691) ).
|
||||
- Issues with obfuscated Adobe fonts fixed (fixes [apprenticeharper/DeDRM_tools#1828](https://github.com/apprenticeharper/DeDRM_tools/issues/1828) ).
|
||||
- Deobfuscate font files in EPUBs by default (can be disabled in the plugin settings).
|
||||
- The standalone adobekey.py script now includes the account UUID in the key file name.
|
||||
- When extracting the default key from an ADE install, include the account UUID in the key name.
|
||||
- Adobe key management window size increased to account for longer key names due to the UUID.
|
||||
- Verify that the decrypted book key has the correct format. This makes it way less likely for issue [apprenticeharper/DeDRM_tools#1862](https://github.com/apprenticeharper/DeDRM_tools/issues/1862) to cause trouble.
|
||||
- If the Adobe owner UUID of a book being imported happens to be included in a particular key's name, try this key first before trying all the others. This completely fixes [apprenticeharper/DeDRM_tools#1862](https://github.com/apprenticeharper/DeDRM_tools/issues/1862), but only if the key name contains the correct UUID (not always the case, especially for keys imported with older versions of the plugin). It also makes DRM removal faster as the plugin no longer has to attempt all possible keys.
|
||||
- Remove some additional DRM remnants in Amazon MOBI files (merged [apprenticeharper/DeDRM_tools#23](https://github.com/apprenticeharper/DeDRM_tools/pull/23) ).
|
||||
- Just in case it's necessary, added a setting to the B&N key generation script to optionally allow the user to select the old key generation algorithm. Who knows, they might want to remove DRM from old books with the old key scheme.
|
||||
- Add a more verbose error message when trying to remove DRM from a book with the new, not-yet-cracked version of the Adobe ADEPT DRM.
|
||||
- Added back support for Python2 (Calibre 2.0+). Only tested with ADEPT (PDF & EPUB) and Readium LCP so far, please open an issue if there's errors with other book types.
|
||||
- Begin work on removing some kinds of watermarks from files after DRM removal. This isn't tested a lot, and is disabled by default. You can enable it in the plugin settings.
|
||||
- If you're using the [ACSM Input Plugin / DeACSM](https://www.mobileread.com/forums/showthread.php?t=341975), the encryption key will automatically be extracted from that plugin if necessary.
|
||||
|
||||
## Fixes in v10.0.1 (2021-11-19):
|
||||
|
||||
- Hotfix update to fix broken EPUB DRM removal due to a typo.
|
||||
|
||||
## Fixes in v10.0.2 (2021-11-29):
|
||||
|
||||
- Fix Kindle for Mac key retrieval (merged [apprenticeharper/DeDRM_tools#1936](https://github.com/apprenticeharper/DeDRM_tools/pull/1936) ), fixing #1.
|
||||
- Fix Adobe key retrieval in case the username has been changed (merged [apprenticeharper/DeDRM_tools#1946](https://github.com/apprenticeharper/DeDRM_tools/pull/1946) ). This should fix the error "failed to decrypt user key key".
|
||||
- Fix small issue with elibri watermark removal.
|
||||
- Adobe key name will now contain account email.
|
||||
|
||||
## Fixes in v10.0.3 (2022-07-13):
|
||||
|
||||
- Fix issue where importing a key from Adobe Digital Editions would fail in Python2 (Calibre < 5) if there were non-ASCII characters in the username.
|
||||
- Add code to support importing multiple decryption keys from ADE.
|
||||
- Improve epubtest.py to also detect Kobo & Apple DRM.
|
||||
- ~Small updates to the LCP DRM error messages.~ (removed due to a DMCA request, see #18 ).
|
||||
- Merge ignobleepub into ineptepub so there's no duplicate code.
|
||||
- Support extracting the B&N / Nook key from the NOOK Microsoft Store application (based on [this script](https://github.com/noDRM/DeDRM_tools/discussions/9) by fesiwi).
|
||||
- Support extracting the B&N / Nook key from a data dump of the NOOK Android application.
|
||||
- Support adding an existing PassHash / B&N key base64 string without having to write it to a file first.
|
||||
- Support extracting PassHash keys from Adobe Digital Editions.
|
||||
- Fix a bug that might have stopped the eReader PDB DRM removal from working (untested, I don't have any PDB books)
|
||||
- Fix a bug where the watermark removal code wouldn't run for DRM-free files.
|
||||
- ineptpdf: Add code to plugin to support "Standard" (tested) and "Adobe.APS" (untested) encrypted PDFs using the ineptpdf implementation (PDF passwords can be entered in the plugin settings)
|
||||
- ineptpdf: Support for decrypting PDF with owner password instead of user password.
|
||||
- ineptpdf: Add function to return Filter name.
|
||||
- ineptpdf: Support for V=5, R=5 and R=6 PDF files, and for AES256-encrypted PDFs.
|
||||
- ineptpdf: Disable cross-reference streams in the output file. This may make PDFs slightly larger, but the current code for cross-reference streams seems to be buggy and sometimes creates corrupted PDFs.
|
||||
- Drop support for importing key data from the ancient, pre "DeDRM" Calibre plugins ("Ignoble Epub DeDRM", "eReader PDB 2 PML" and "K4MobiDeDRM"). These are from 2011, I doubt anyone still has these installed, I can't even find a working link for these to test them. If you still have encryption keys in one of these plugins, you will need to update to DeDRM v10.0.2 or older (to convert the keys) before updating to DeDRM v10.0.3 or newer.
|
||||
- Some Python3 bugfixes for Amazon books (merged #10 by ableeker).
|
||||
- Fix a bug where extracting an Adobe key from ADE on Linux through Wine did fail when using the OpenSSL backend (instead of PyCrypto). See #13 and #14 for details, thanks acaloiaro for the bugfix.
|
||||
- Fix IndexError when DeDRMing some Amazon eBooks.
|
||||
- Add support for books with the new ADE3.0+ DRM by merging #48 by a980e066a01. Thanks a lot! (Also fixes #96 on MacOS)
|
||||
- Remove OpenSSL support, now the plugin will always use the Python crypto libraries.
|
||||
- Obok: Fix issues with invalid UTF-8 characters by merging #26 by baby-bell.
|
||||
- ineptpdf: Fix broken V=3 key obfuscation algorithm.
|
||||
- ineptpdf: (Hopefully) fix issues with some B&N PDF files.
|
||||
- Fix broken Amazon K4PC key retrieval (fixes #38)
|
||||
- Fix bug that corrupts output file for Print-Replica Amazon books (fixes #30).
|
||||
- Fix Nook Study key retrieval code (partially fixes #50).
|
||||
- Make the plugin work on Calibre 6 (Qt 6). (fixes #54 and #98) If you're running Calibre 6 and you notice any issues, please open a bug report.
|
||||
|
||||
## Fixes in v10.0.9 (RC for v10.1.0, 2023-08-02):
|
||||
|
||||
Note that versions v10.0.4(s), v10.0.5(s) and v10.0.6(s) were released by other people in various forks, so I have decided to make a larger version jump so there are no conflicting version numbers / different builds with the same version number.
|
||||
|
||||
This is v10.0.9, a release candidate for v10.1.0. I don't expect there to be major issues / bugs, but since a lot of code has changed in the last year I wanted to get some "extended testing" before this becomes v10.1.0.
|
||||
|
||||
- Fix a bug introduced with #48 that breaks DeDRM'ing on Calibre 4 (fixes #101).
|
||||
- Fix some more Calibre-6 bugs in the Obok plugin (should fix #114).
|
||||
- Fix a bug where invalid Adobe keys could cause the plugin to stop trying subsequent keys (partially fixes #109).
|
||||
- Fix DRM removal sometimes resetting the ZIP's internal "external_attr" value on Calibre 5 and newer.
|
||||
- Fix tons of PDF decryption issues (hopefully fixes #104 and other PDF-related issues).
|
||||
- Small Python 2 / Calibre 4 bugfix for Obok.
|
||||
- Removing ancient AlfCrypto machine code libraries, moving all encryption / decryption to Python code.
|
||||
- General cleanup and removal of dead code.
|
||||
- Fix a bug where ADE account keys weren't automatically imported from the DeACSM plugin when importing a PDF file.
|
||||
- Re-enable Xrefs in exported PDF files since the file corruption bug is hopefully fixed. Please open bug reports if you encounter new issues with PDF files.
|
||||
- Fix a bug that would sometimes cause corrupted keys to be added when adding them through the config dialog (fixes #145, #134, #119, #116, #115, #109).
|
||||
- Update the README (fixes #136) to indicate that Apprentice Harper's version is no longer being updated.
|
||||
- Fix a bug where PDFs with empty arrays (`<>`) in a PDF object failed to decrypt, fixes #183.
|
||||
- Automatically strip whitespace from entered Amazon Kindle serial numbers, should fix #158.
|
||||
- Obok: Add new setting option "Add new entry" for duplicate books to always add them to the Calibre database as a new book. Fixes #148.
|
||||
- Obok: Fix where changing the Calibre UI language to some languages would cause the "duplicate book" setting to reset.
|
||||
- Fix Python3 bug in stylexml2css.php script, fixes #232.
|
||||
- PDF: Ignore invalid PDF objids unless the script is running in strict mode. Fixes some PDFs, apparently. Fixes #233.
|
||||
- Bugfix: EPUBs with remaining content in the encryption.xml after decryption weren't written correctly.
|
||||
- Support for Adobe's 'aes128-cbc-uncompressed' encryption method (fixes #242).
|
||||
- Two bugfixes for Amazon DeDRM from Satuoni ( https://github.com/noDRM/DeDRM_tools/issues/315#issuecomment-1508305428 ) and andrewc12 ( https://github.com/andrewc12/DeDRM_tools/commit/d9233d61f00d4484235863969919059f4d0b2057 ) that might make the plugin work with newer versions.
|
||||
- Fix font decryption not working with some books (fixes #347), thanks for the patch @bydioeds.
|
||||
- Fix a couple unicode errors for Python2 in Kindle and Nook code.
|
||||
|
||||
## Fixes on master (not yet released):
|
||||
|
||||
- Fix a bug where decrypting a 40-bit RC4 pdf with R=2 didn't work.
|
||||
- Fix a bug where decrypting a 256-bit AES pdf with V=5 didn't work.
|
||||
- Fix bugs in kgenpids.py, alfcrypto.py, mobidedrm.py and kindlekey.py that caused it to fail on Python 2 (#380).
|
||||
- Fix some bugs (Python 2 and Python 3) in erdr2pml.py (untested).
|
||||
- Fix file lock bug in androidkindlekey.py on Windows with Calibre >= 7 (untested).
|
||||
- A bunch of updates to the external FileOpen ineptpdf script, might fix #442 (untested).
|
||||
- Fix exception handling on decrypt in ion.py (#662, thanks @C0rn3j).
|
||||
- Fix SHA1 hash function for erdr2pml.py script (#608, thanks @unwiredben).
|
||||
- Make Kobo DRM removal not fail when there are undownloaded ebooks (#384, thanks @precondition).
|
||||
- Fix Obok import failing in Calibre flatpak due to missing ip command (#586 and #585, thanks @jcotton42).
|
||||
- Don't re-pack EPUB if there's no DRM to remove and no postprocessing done (fixes #555).
|
||||
|
||||
|
|
@ -1,68 +0,0 @@
|
|||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
|
||||
"http://www.w3.org/TR/html4/strict.dtd">
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
||||
<title>Managing Adobe PassHash (B&N) Keys</title>
|
||||
<style type="text/css">
|
||||
span.version {font-size: 50%}
|
||||
span.bold {font-weight: bold}
|
||||
h3 {margin-bottom: 0}
|
||||
p {margin-top: 0}
|
||||
li {margin-top: 0.5em}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<h1>Managing Adobe PassHash Keys</h1>
|
||||
|
||||
<p>Adobe PassHash is a variant of the Adobe DRM which is used by retailers like Barnes and Noble. Instead of using certificates and device-based authorization, this uses a username and password combination. In B&&Ns implementation however, the user never gets access to these credentials, just to the credential hash.</p>
|
||||
|
||||
<h3>Changes at Barnes & Noble</h3>
|
||||
|
||||
<p>Since 2014, Barnes & Noble is no longer using the default Adobe key generation algorithm, which used to be the full name as "username" and the full credit card number as "password" for the PassHash algorithm.
|
||||
Instead, they started generating a random key on their server and send that to the reading application during login. This means that the old method to decrypt these books will no longer work. </p>
|
||||
|
||||
<p>There used to be a way to use the Android app's API to simulate a login to the Barnes and Noble servers, but that API has been shut down a while ago, too, and so far nobody has reverse-engineered the new one.</p>
|
||||
|
||||
<h3>Importing PassHash / B&N keys</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a green plus sign (+). Clicking this button will open a new dialog for entering the necessary data to generate a new key.</p>
|
||||
<p>Currently, the only known ways to access the key are the following:</p>
|
||||
<ul>
|
||||
<li>B&N: The encryption key can be extracted from the NOOK reading application available in the Microsoft store, or from the old "Nook Study" application. To do that, click on the "Extract key from Nook Windows application" option.</li>
|
||||
<li>B&N: The encryption key can also be extracted from a data backup of the NOOK Android application. To do that, you'll need to have a rooted Android device, a hacked / modified Nook APK file, or an Android emulator to be able to access the app data. If you have that, click on "Extract key from Nook Android application" and follow the instructions.</li>
|
||||
<li>B&N: The NOOK Android application supports / accepts user-added CA certificates, so you can set up something like mitmproxy on your computer, tunnel your phone's traffic through that, and extract the ccHash key data from the server response. You can then add that hash through the "Base64-encoded PassHash key string" option.</li>
|
||||
<li>If you already have a copy of the Nook ccHash key string (or, more general, the PassHash key string) in base64 encoding, you can either click on "Import existing keyfiles" if it's a file in b64 format, or you click on the "Base64-encoded PassHash key string" option while adding a new PassHash key.</li>
|
||||
<li>For retailers other than B&N that are using the PassHash algorihm as intended, you can click on "Adobe PassHash username & password" to enter your credentials while adding a key. This is the same algorihm as the original credit card number based key generation for B&N.</li>
|
||||
<li>Windows only: If you've successfully opened a PassHash-encrypted book in Adobe Digital Editions by entering username and password, you can dump the stored credentials from ADE.</li>
|
||||
</ul>
|
||||
|
||||
|
||||
<p>After you've selected a key retrieval method from the settings, the dialog may change and request some additional information depending on the key retrieval method. Enter that, then click the OK button to create and store the generated key. Or Cancel if you don’t want to create a key.</p>
|
||||
<p>New keys are checked against the current list of keys before being added, and duplicates are discarded.</p>
|
||||
|
||||
<h3>Deleting Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a red "X". Clicking this button will delete the highlighted key in the list. You will be prompted once to be sure that’s what you truly mean to do. Once gone, it’s permanently gone.</p>
|
||||
|
||||
<h3>Renaming Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a sheet of paper. Clicking this button will prompt you to enter a new name for the highlighted key in the list. Enter the new name for the encryption key and click the OK button to use the new name, or Cancel to revert to the old name..</p>
|
||||
|
||||
<h3>Exporting Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a computer’s hard-drive. Use this button to export the highlighted key to a file (with a ‘.b64’ file name extension). Used for backup purposes or to migrate key data to other computers/calibre installations. The dialog will prompt you for a place to save the file.</p>
|
||||
|
||||
<h3>Importing Existing Keyfiles:</h3>
|
||||
|
||||
<p>At the bottom-left of the plugin’s customization dialog, you will see a button labeled "Import Existing Keyfiles". Use this button to import existing ‘.b64’ key files. Key files might come from being exported from this or older plugins, or may have been generated using the original i♥cabbages script, or you may have made it by following the instructions above.</p>
|
||||
|
||||
<p>Once done creating/deleting/renaming/importing decryption keys, click Close to exit the customization dialogue. Your changes will only be saved permanently when you click OK in the main configuration dialog.</p>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -1,39 +0,0 @@
|
|||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
|
||||
"http://www.w3.org/TR/html4/strict.dtd">
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
||||
<title>Managing PDF passwords</title>
|
||||
<style type="text/css">
|
||||
span.version {font-size: 50%}
|
||||
span.bold {font-weight: bold}
|
||||
h3 {margin-bottom: 0}
|
||||
p {margin-top: 0}
|
||||
li {margin-top: 0.5em}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<h1>Managing PDF passwords</h1>
|
||||
|
||||
<p>PDF files can be protected with a password / passphrase that will be required to open the PDF file. Enter your passphrases in the plugin settings to have the plugin automatically remove this encryption / restriction from PDF files you import. </p>
|
||||
|
||||
|
||||
<h3>Entering a passphrase:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a green plus sign (+). Clicking this button will open a new dialog for entering a new passphrase.</p>
|
||||
|
||||
<p>Just enter your passphrase for the PDF file, then click the OK button to save the passphrase. </p>
|
||||
|
||||
<h3>Deleting a passphrase:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a red "X". Clicking this button will delete the highlighted passphrase from the list. You will be prompted once to be sure that’s what you truly mean to do. Once gone, it’s permanently gone.</p>
|
||||
|
||||
<p>Once done entering/deleting passphrases, click Close to exit the customization dialogue. Your changes will only be saved permanently when you click OK in the main configuration dialog.</p>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -1,42 +0,0 @@
|
|||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
|
||||
"http://www.w3.org/TR/html4/strict.dtd">
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
||||
<title>Managing Readium LCP passphrases</title>
|
||||
<style type="text/css">
|
||||
span.version {font-size: 50%}
|
||||
span.bold {font-weight: bold}
|
||||
h3 {margin-bottom: 0}
|
||||
p {margin-top: 0}
|
||||
li {margin-top: 0.5em}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<h1>Managing Readium LCP passphrases</h1>
|
||||
|
||||
<p>Readium LCP is a relatively new eBook DRM. It's also known under the names "CARE DRM" or "TEA DRM". It does not rely on any accounts or key data that's difficult to acquire. All you need to open (or decrypt) LCP eBooks is the account passphrase given to you by the eBook provider - the very same passphrase you'd have to enter into your eBook reader device (once) to read LCP-encrypted books.</p>
|
||||
|
||||
<p>This plugin no longer supports removing the Readium LCP DRM due to a DMCA takedown request issued by Readium. Please read the <a href="https://github.com/github/dmca/blob/master/2022/01/2022-01-04-readium.md">takedown notice</a> or <a href="https://github.com/noDRM/DeDRM_tools/issues/18">this bug report</a> for more information.</p>
|
||||
|
||||
<h3>Entering an LCP passphrase:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a green plus sign (+). Clicking this button will open a new dialog for entering a new passphrase.</p>
|
||||
|
||||
<p>Just enter your passphrase as provided with the book, then click the OK button to save the passphrase. </p>
|
||||
|
||||
<p>Usually, passphrases are identical for all books bought with the same account. So if you buy multiple LCP-protected eBooks, they'll usually all have the same passphrase if they've all been bought at the same store with the same account. </p>
|
||||
|
||||
<h3>Deleting an LCP passphrase:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a red "X". Clicking this button will delete the highlighted passphrase from the list. You will be prompted once to be sure that’s what you truly mean to do. Once gone, it’s permanently gone.</p>
|
||||
|
||||
<p>Once done entering/deleting passphrases, click Close to exit the customization dialogue. Your changes will only be saved permanently when you click OK in the main configuration dialog.</p>
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
|
||||
#@@CALIBRE_COMPAT_CODE_START@@
|
||||
import sys, os
|
||||
|
||||
# Explicitly allow importing everything ...
|
||||
if os.path.dirname(os.path.dirname(os.path.abspath(__file__))) not in sys.path:
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
if os.path.dirname(os.path.abspath(__file__)) not in sys.path:
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# Bugfix for Calibre < 5:
|
||||
if "calibre" in sys.modules and sys.version_info[0] == 2:
|
||||
from calibre.utils.config import config_dir
|
||||
if os.path.join(config_dir, "plugins", "DeDRM.zip") not in sys.path:
|
||||
sys.path.insert(0, os.path.join(config_dir, "plugins", "DeDRM.zip"))
|
||||
|
||||
if "calibre" in sys.modules:
|
||||
# Explicitly set the package identifier so we are allowed to import stuff ...
|
||||
__package__ = "calibre_plugins.dedrm"
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE_END@@
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,34 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# __main__.py for DeDRM_plugin
|
||||
# (CLI interface without Calibre)
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
"""
|
||||
|
||||
NOTE: This code is not functional (yet). I started working on it a while ago
|
||||
to make a standalone version of the plugins that could work without Calibre,
|
||||
too, but for now there's only a rough code structure and no working code yet.
|
||||
|
||||
Currently, to use these plugins, you will need to use Calibre. Hopwfully that'll
|
||||
change in the future.
|
||||
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
# For revision history see CHANGELOG.md
|
||||
|
||||
"""
|
||||
Run DeDRM plugin without Calibre.
|
||||
"""
|
||||
|
||||
# Import __init__.py from the standalone folder so we can have all the
|
||||
# standalone / non-Calibre code in that subfolder.
|
||||
|
||||
import standalone.__init__ as mdata
|
||||
import sys
|
||||
|
||||
mdata.main(sys.argv)
|
||||
|
|
@ -1,12 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
PLUGIN_NAME = "DeDRM"
|
||||
__version__ = '10.0.9'
|
||||
|
||||
PLUGIN_VERSION_TUPLE = tuple([int(x) for x in __version__.split(".")])
|
||||
PLUGIN_VERSION = ".".join([str(x)for x in PLUGIN_VERSION_TUPLE])
|
||||
# Include an html helpfile in the plugin's zipfile with the following name.
|
||||
RESOURCE_NAME = PLUGIN_NAME + '_Help.htm'
|
||||
|
|
@ -1,179 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# adobekey_get_passhash.py, version 1
|
||||
# based on adobekey.pyw, version 7.2
|
||||
# Copyright © 2009-2021 i♥cabbages, Apprentice Harper et al.
|
||||
# Copyright © 2021 noDRM
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
# Revision history:
|
||||
# 1 - Initial release
|
||||
|
||||
"""
|
||||
Retrieve Adobe ADEPT user passhash keys
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = '1'
|
||||
|
||||
import sys, os, time
|
||||
import base64, hashlib
|
||||
try:
|
||||
from Cryptodome.Cipher import AES
|
||||
except ImportError:
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
|
||||
def unpad(data, padding=16):
|
||||
if sys.version_info[0] == 2:
|
||||
pad_len = ord(data[-1])
|
||||
else:
|
||||
pad_len = data[-1]
|
||||
|
||||
return data[:-pad_len]
|
||||
|
||||
PASS_HASH_SECRET = "9ca588496a1bc4394553d9e018d70b9e"
|
||||
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
except:
|
||||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
||||
|
||||
class ADEPTError(Exception):
|
||||
pass
|
||||
|
||||
def decrypt_passhash(passhash, fp):
|
||||
|
||||
serial_number = base64.b64decode(fp).hex()
|
||||
|
||||
hash_key = hashlib.sha1(bytearray.fromhex(serial_number + PASS_HASH_SECRET)).digest()[:16]
|
||||
|
||||
encrypted_cc_hash = base64.b64decode(passhash)
|
||||
cc_hash = unpad(AES.new(hash_key, AES.MODE_CBC, encrypted_cc_hash[:16]).decrypt(encrypted_cc_hash[16:]))
|
||||
return base64.b64encode(cc_hash).decode("ascii")
|
||||
|
||||
|
||||
if iswindows:
|
||||
try:
|
||||
import winreg
|
||||
except ImportError:
|
||||
import _winreg as winreg
|
||||
|
||||
PRIVATE_LICENCE_KEY_PATH = r'Software\Adobe\Adept\Activation'
|
||||
|
||||
def passhash_keys():
|
||||
cuser = winreg.HKEY_CURRENT_USER
|
||||
keys = []
|
||||
names = []
|
||||
try:
|
||||
plkroot = winreg.OpenKey(cuser, PRIVATE_LICENCE_KEY_PATH)
|
||||
except WindowsError:
|
||||
raise ADEPTError("Could not locate ADE activation")
|
||||
except FileNotFoundError:
|
||||
raise ADEPTError("Could not locate ADE activation")
|
||||
|
||||
idx = 1
|
||||
|
||||
fp = None
|
||||
|
||||
i = -1
|
||||
while True:
|
||||
i = i + 1 # start with 0
|
||||
try:
|
||||
plkparent = winreg.OpenKey(plkroot, "%04d" % (i,))
|
||||
except:
|
||||
# No more keys
|
||||
break
|
||||
|
||||
ktype = winreg.QueryValueEx(plkparent, None)[0]
|
||||
|
||||
if ktype == "activationToken":
|
||||
# find fingerprint for hash decryption
|
||||
j = -1
|
||||
while True:
|
||||
j = j + 1 # start with 0
|
||||
try:
|
||||
plkkey = winreg.OpenKey(plkparent, "%04d" % (j,))
|
||||
except WindowsError:
|
||||
break
|
||||
except FileNotFoundError:
|
||||
break
|
||||
ktype = winreg.QueryValueEx(plkkey, None)[0]
|
||||
if ktype == 'fingerprint':
|
||||
fp = winreg.QueryValueEx(plkkey, 'value')[0]
|
||||
#print("Found fingerprint: " + fp)
|
||||
|
||||
|
||||
# Note: There can be multiple lists, with multiple entries each.
|
||||
if ktype == 'passHashList':
|
||||
|
||||
# Find operator (used in key name)
|
||||
j = -1
|
||||
lastOperator = "Unknown"
|
||||
while True:
|
||||
j = j + 1 # start with 0
|
||||
try:
|
||||
plkkey = winreg.OpenKey(plkparent, "%04d" % (j,))
|
||||
except WindowsError:
|
||||
break
|
||||
except FileNotFoundError:
|
||||
break
|
||||
ktype = winreg.QueryValueEx(plkkey, None)[0]
|
||||
if ktype == 'operatorURL':
|
||||
operatorURL = winreg.QueryValueEx(plkkey, 'value')[0]
|
||||
try:
|
||||
lastOperator = operatorURL.split('//')[1].split('/')[0]
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
# Find hashes
|
||||
j = -1
|
||||
while True:
|
||||
j = j + 1 # start with 0
|
||||
try:
|
||||
plkkey = winreg.OpenKey(plkparent, "%04d" % (j,))
|
||||
except WindowsError:
|
||||
break
|
||||
except FileNotFoundError:
|
||||
break
|
||||
ktype = winreg.QueryValueEx(plkkey, None)[0]
|
||||
|
||||
if ktype == "passHash":
|
||||
passhash_encrypted = winreg.QueryValueEx(plkkey, 'value')[0]
|
||||
names.append("ADE_key_" + lastOperator + "_" + str(int(time.time())) + "_" + str(idx))
|
||||
idx = idx + 1
|
||||
keys.append(passhash_encrypted)
|
||||
|
||||
if fp is None:
|
||||
#print("Didn't find fingerprint for decryption ...")
|
||||
return [], []
|
||||
|
||||
print("Found {0:d} passhashes".format(len(keys)), file=sys.stderr)
|
||||
|
||||
keys_decrypted = []
|
||||
|
||||
for key in keys:
|
||||
decrypted = decrypt_passhash(key, fp)
|
||||
#print("Input key: " + key)
|
||||
#print("Output key: " + decrypted)
|
||||
keys_decrypted.append(decrypted)
|
||||
|
||||
return keys_decrypted, names
|
||||
|
||||
|
||||
else:
|
||||
def passhash_keys():
|
||||
raise ADEPTError("This script only supports Windows.")
|
||||
#TODO: Add MacOS support by parsing the activation.xml file.
|
||||
return [], []
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("This is a python calibre plugin. It can't be directly executed.")
|
||||
|
|
@ -1,271 +0,0 @@
|
|||
# This is based on https://github.com/DanielStutzbach/winreg_unicode
|
||||
# The original _winreg in Python2 doesn't support unicode.
|
||||
# This causes issues if there's unicode chars in the username needed to decrypt the key.
|
||||
|
||||
'''
|
||||
Copyright 2010 Stutzbach Enterprises, LLC (daniel@stutzbachenterprises.com)
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided
|
||||
with the distribution.
|
||||
3. The name of the author may not be used to endorse or promote
|
||||
products derived from this software without specific prior written
|
||||
permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
|
||||
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
|
||||
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
|
||||
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
|
||||
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
|
||||
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
'''
|
||||
|
||||
import ctypes, ctypes.wintypes
|
||||
|
||||
ERROR_SUCCESS = 0
|
||||
ERROR_MORE_DATA = 234
|
||||
|
||||
KEY_READ = 0x20019
|
||||
|
||||
REG_NONE = 0
|
||||
REG_SZ = 1
|
||||
REG_EXPAND_SZ = 2
|
||||
REG_BINARY = 3
|
||||
REG_DWORD = 4
|
||||
REG_DWORD_BIG_ENDIAN = 5
|
||||
REG_DWORD_LITTLE_ENDIAN = 4
|
||||
REG_LINK = 6
|
||||
REG_MULTI_SZ = 7
|
||||
REG_RESOURCE_LIST = 8
|
||||
REG_FULL_RESOURCE_DESCRIPTOR = 9
|
||||
REG_RESOURCE_REQUIREMENTS_LIST = 10
|
||||
|
||||
c_HKEY = ctypes.c_void_p
|
||||
DWORD = ctypes.wintypes.DWORD
|
||||
BYTE = ctypes.wintypes.BYTE
|
||||
LPDWORD = ctypes.POINTER(DWORD)
|
||||
LPBYTE = ctypes.POINTER(BYTE)
|
||||
|
||||
advapi32 = ctypes.windll.advapi32
|
||||
|
||||
class FILETIME(ctypes.Structure):
|
||||
_fields_ = [("dwLowDateTime", DWORD),
|
||||
("dwHighDateTime", DWORD)]
|
||||
|
||||
RegCloseKey = advapi32.RegCloseKey
|
||||
RegCloseKey.restype = ctypes.c_long
|
||||
RegCloseKey.argtypes = [c_HKEY]
|
||||
|
||||
RegOpenKeyEx = advapi32.RegOpenKeyExW
|
||||
RegOpenKeyEx.restype = ctypes.c_long
|
||||
RegOpenKeyEx.argtypes = [c_HKEY, ctypes.c_wchar_p, ctypes.c_ulong,
|
||||
ctypes.c_ulong, ctypes.POINTER(c_HKEY)]
|
||||
|
||||
RegQueryInfoKey = advapi32.RegQueryInfoKeyW
|
||||
RegQueryInfoKey.restype = ctypes.c_long
|
||||
RegQueryInfoKey.argtypes = [c_HKEY, ctypes.c_wchar_p, LPDWORD, LPDWORD,
|
||||
LPDWORD, LPDWORD, LPDWORD, LPDWORD,
|
||||
LPDWORD, LPDWORD, LPDWORD,
|
||||
ctypes.POINTER(FILETIME)]
|
||||
|
||||
RegEnumValue = advapi32.RegEnumValueW
|
||||
RegEnumValue.restype = ctypes.c_long
|
||||
RegEnumValue.argtypes = [c_HKEY, DWORD, ctypes.c_wchar_p, LPDWORD,
|
||||
LPDWORD, LPDWORD, LPBYTE, LPDWORD]
|
||||
|
||||
RegEnumKeyEx = advapi32.RegEnumKeyExW
|
||||
RegEnumKeyEx.restype = ctypes.c_long
|
||||
RegEnumKeyEx.argtypes = [c_HKEY, DWORD, ctypes.c_wchar_p, LPDWORD,
|
||||
LPDWORD, ctypes.c_wchar_p, LPDWORD,
|
||||
ctypes.POINTER(FILETIME)]
|
||||
|
||||
RegQueryValueEx = advapi32.RegQueryValueExW
|
||||
RegQueryValueEx.restype = ctypes.c_long
|
||||
RegQueryValueEx.argtypes = [c_HKEY, ctypes.c_wchar_p, LPDWORD, LPDWORD,
|
||||
LPBYTE, LPDWORD]
|
||||
|
||||
def check_code(code):
|
||||
if code == ERROR_SUCCESS:
|
||||
return
|
||||
raise ctypes.WinError(2)
|
||||
|
||||
class HKEY(object):
|
||||
def __init__(self):
|
||||
self.hkey = c_HKEY()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
|
||||
self.Close()
|
||||
return False
|
||||
|
||||
def Detach(self):
|
||||
rv = self.cast(self.hkey, self.c_ulong).value
|
||||
self.hkey = c_HKEY()
|
||||
return rv
|
||||
|
||||
def __nonzero__(self):
|
||||
return bool(self.hkey)
|
||||
|
||||
def Close(self):
|
||||
if not self.hkey:
|
||||
return
|
||||
if RegCloseKey is None or check_code is None or c_HKEY is None:
|
||||
return # globals become None during exit
|
||||
rc = RegCloseKey(self.hkey)
|
||||
self.hkey = c_HKEY()
|
||||
check_code(rc)
|
||||
|
||||
def __del__(self):
|
||||
self.Close()
|
||||
|
||||
class RootHKEY(ctypes.Structure):
|
||||
def __init__(self, value):
|
||||
self.hkey = c_HKEY(value)
|
||||
|
||||
def Close(self):
|
||||
pass
|
||||
|
||||
HKEY_CLASSES_ROOT = RootHKEY(0x80000000)
|
||||
HKEY_CURRENT_USER = RootHKEY(0x80000001)
|
||||
HKEY_LOCAL_MACHINE = RootHKEY(0x80000002)
|
||||
HKEY_USERS = RootHKEY(0x80000003)
|
||||
HKEY_PERFORMANCE_DATA = RootHKEY(0x80000004)
|
||||
HKEY_CURRENT_CONFIG = RootHKEY(0x80000005)
|
||||
HKEY_DYN_DATA = RootHKEY(0x80000006)
|
||||
|
||||
def OpenKey(key, sub_key):
|
||||
new_key = HKEY()
|
||||
rc = RegOpenKeyEx(key.hkey, sub_key, 0, KEY_READ,
|
||||
ctypes.cast(ctypes.byref(new_key.hkey),
|
||||
ctypes.POINTER(c_HKEY)))
|
||||
check_code(rc)
|
||||
return new_key
|
||||
|
||||
def QueryInfoKey(key):
|
||||
null = LPDWORD()
|
||||
num_sub_keys = DWORD()
|
||||
num_values = DWORD()
|
||||
ft = FILETIME()
|
||||
rc = RegQueryInfoKey(key.hkey, ctypes.c_wchar_p(), null, null,
|
||||
ctypes.byref(num_sub_keys), null, null,
|
||||
ctypes.byref(num_values), null, null, null,
|
||||
ctypes.byref(ft))
|
||||
check_code(rc)
|
||||
return (num_sub_keys.value, num_values.value,
|
||||
ft.dwLowDateTime | (ft.dwHighDateTime << 32))
|
||||
|
||||
def EnumValue(key, index):
|
||||
null = LPDWORD()
|
||||
value_size = DWORD()
|
||||
data_size = DWORD()
|
||||
rc = RegQueryInfoKey(key.hkey, ctypes.c_wchar_p(), null, null, null,
|
||||
null, null, null,
|
||||
ctypes.byref(value_size), ctypes.byref(data_size),
|
||||
null, ctypes.POINTER(FILETIME)())
|
||||
check_code(rc)
|
||||
value_size.value += 1
|
||||
data_size.value += 1
|
||||
|
||||
value = ctypes.create_unicode_buffer(value_size.value)
|
||||
|
||||
while True:
|
||||
data = ctypes.create_string_buffer(data_size.value)
|
||||
|
||||
tmp_value_size = DWORD(value_size.value)
|
||||
tmp_data_size = DWORD(data_size.value)
|
||||
typ = DWORD()
|
||||
rc = RegEnumValue(key.hkey, index,
|
||||
ctypes.cast(value, ctypes.c_wchar_p),
|
||||
ctypes.byref(tmp_value_size), null,
|
||||
ctypes.byref(typ),
|
||||
ctypes.cast(data, LPBYTE),
|
||||
ctypes.byref(tmp_data_size))
|
||||
|
||||
if rc != ERROR_MORE_DATA:
|
||||
break
|
||||
|
||||
data_size.value *= 2
|
||||
|
||||
check_code(rc)
|
||||
return (value.value, Reg2Py(data, tmp_data_size.value, typ.value),
|
||||
typ.value)
|
||||
|
||||
def split_multi_sz(data, size):
|
||||
if size == 0:
|
||||
return []
|
||||
Q = size
|
||||
P = 0
|
||||
rv = []
|
||||
while P < Q and data[P].value != u'\0':
|
||||
rv.append[P]
|
||||
while P < Q and data[P].value != u'\0':
|
||||
P += 1
|
||||
P += 1
|
||||
rv.append(size)
|
||||
return [ctypes.wstring_at(ctypes.pointer(data[rv[i]]),
|
||||
rv[i+1] - rv[i]).rstrip(u'\x00')
|
||||
for i in range(len(rv)-1)]
|
||||
|
||||
def Reg2Py(data, size, typ):
|
||||
if typ == REG_DWORD:
|
||||
if size == 0:
|
||||
return 0
|
||||
return ctypes.cast(data, ctypes.POINTER(ctypes.c_int)).contents.value
|
||||
elif typ == REG_SZ or typ == REG_EXPAND_SZ:
|
||||
return ctypes.wstring_at(data, size // 2).rstrip(u'\x00')
|
||||
elif typ == REG_MULTI_SZ:
|
||||
return split_multi_sz(ctypes.cast(data, ctypes.c_wchar_p), size // 2)
|
||||
else:
|
||||
if size == 0:
|
||||
return None
|
||||
return ctypes.string_at(data, size)
|
||||
|
||||
def EnumKey(key, index):
|
||||
tmpbuf = ctypes.create_unicode_buffer(257)
|
||||
length = DWORD(257)
|
||||
rc = RegEnumKeyEx(key.hkey, index,
|
||||
ctypes.cast(tmpbuf, ctypes.c_wchar_p),
|
||||
ctypes.byref(length),
|
||||
LPDWORD(), ctypes.c_wchar_p(), LPDWORD(),
|
||||
ctypes.POINTER(FILETIME)())
|
||||
check_code(rc)
|
||||
return ctypes.wstring_at(tmpbuf, length.value).rstrip(u'\x00')
|
||||
|
||||
def QueryValueEx(key, value_name):
|
||||
size = 256
|
||||
typ = DWORD()
|
||||
while True:
|
||||
tmp_size = DWORD(size)
|
||||
buf = ctypes.create_string_buffer(size)
|
||||
rc = RegQueryValueEx(key.hkey, value_name, LPDWORD(),
|
||||
ctypes.byref(typ),
|
||||
ctypes.cast(buf, LPBYTE), ctypes.byref(tmp_size))
|
||||
if rc != ERROR_MORE_DATA:
|
||||
break
|
||||
|
||||
size *= 2
|
||||
check_code(rc)
|
||||
return (Reg2Py(buf, tmp_size.value, typ.value), typ.value)
|
||||
|
||||
__all__ = ['OpenKey', 'QueryInfoKey', 'EnumValue', 'EnumKey', 'QueryValueEx',
|
||||
'HKEY_CLASSES_ROOT', 'HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE',
|
||||
'HKEY_USERS', 'HKEY_PERFORMANCE_DATA', 'HKEY_CURRENT_CONFIG',
|
||||
'HKEY_DYN_DATA', 'REG_NONE', 'REG_SZ', 'REG_EXPAND_SZ',
|
||||
'REG_BINARY', 'REG_DWORD', 'REG_DWORD_BIG_ENDIAN',
|
||||
'REG_DWORD_LITTLE_ENDIAN', 'REG_LINK', 'REG_MULTI_SZ',
|
||||
'REG_RESOURCE_LIST', 'REG_FULL_RESOURCE_DESCRIPTOR',
|
||||
'REG_RESOURCE_REQUIREMENTS_LIST']
|
||||
|
|
@ -1,147 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# crypto library mainly by some_updates
|
||||
|
||||
# pbkdf2.py pbkdf2 code taken from pbkdf2.py
|
||||
# pbkdf2.py Copyright © 2004 Matt Johnston <matt @ ucc asn au>
|
||||
# pbkdf2.py Copyright © 2009 Daniel Holth <dholth@fastmail.fm>
|
||||
# pbkdf2.py This code may be freely used and modified for any purpose.
|
||||
|
||||
import sys
|
||||
import hmac
|
||||
from struct import pack
|
||||
import hashlib
|
||||
import aescbc
|
||||
|
||||
class Pukall_Cipher(object):
|
||||
def __init__(self):
|
||||
self.key = None
|
||||
|
||||
def PC1(self, key, src, decryption=True):
|
||||
sum1 = 0;
|
||||
sum2 = 0;
|
||||
keyXorVal = 0;
|
||||
if len(key)!=16:
|
||||
raise Exception("PC1: Bad key length")
|
||||
wkey = []
|
||||
for i in range(8):
|
||||
if sys.version_info[0] == 2:
|
||||
wkey.append(ord(key[i*2])<<8 | ord(key[i*2+1]))
|
||||
else:
|
||||
wkey.append(key[i*2]<<8 | key[i*2+1])
|
||||
dst = bytearray(len(src))
|
||||
for i in range(len(src)):
|
||||
temp1 = 0;
|
||||
byteXorVal = 0;
|
||||
for j in range(8):
|
||||
temp1 ^= wkey[j]
|
||||
sum2 = (sum2+j)*20021 + sum1
|
||||
sum1 = (temp1*346)&0xFFFF
|
||||
sum2 = (sum2+sum1)&0xFFFF
|
||||
temp1 = (temp1*20021+1)&0xFFFF
|
||||
byteXorVal ^= temp1 ^ sum2
|
||||
|
||||
if sys.version_info[0] == 2:
|
||||
curByte = ord(src[i])
|
||||
else:
|
||||
curByte = src[i]
|
||||
|
||||
if not decryption:
|
||||
keyXorVal = curByte * 257;
|
||||
curByte = ((curByte ^ (byteXorVal >> 8)) ^ byteXorVal) & 0xFF
|
||||
if decryption:
|
||||
keyXorVal = curByte * 257;
|
||||
for j in range(8):
|
||||
wkey[j] ^= keyXorVal;
|
||||
|
||||
if sys.version_info[0] == 2:
|
||||
dst[i] = chr(curByte)
|
||||
else:
|
||||
dst[i] = curByte
|
||||
|
||||
return bytes(dst)
|
||||
|
||||
class Topaz_Cipher(object):
|
||||
def __init__(self):
|
||||
self._ctx = None
|
||||
|
||||
def ctx_init(self, key):
|
||||
ctx1 = 0x0CAFFE19E
|
||||
if isinstance(key, str):
|
||||
key = key.encode('latin-1')
|
||||
for keyByte in key:
|
||||
ctx2 = ctx1
|
||||
ctx1 = ((((ctx1 >>2) * (ctx1 >>7))&0xFFFFFFFF) ^ (keyByte * keyByte * 0x0F902007)& 0xFFFFFFFF )
|
||||
self._ctx = [ctx1, ctx2]
|
||||
return [ctx1,ctx2]
|
||||
|
||||
def decrypt(self, data, ctx=None):
|
||||
if ctx == None:
|
||||
ctx = self._ctx
|
||||
ctx1 = ctx[0]
|
||||
ctx2 = ctx[1]
|
||||
plainText = ""
|
||||
if isinstance(data, str):
|
||||
data = data.encode('latin-1')
|
||||
for dataByte in data:
|
||||
m = (dataByte ^ ((ctx1 >> 3) &0xFF) ^ ((ctx2<<3) & 0xFF)) &0xFF
|
||||
ctx2 = ctx1
|
||||
ctx1 = (((ctx1 >> 2) * (ctx1 >> 7)) &0xFFFFFFFF) ^((m * m * 0x0F902007) &0xFFFFFFFF)
|
||||
plainText += chr(m)
|
||||
return plainText
|
||||
|
||||
class AES_CBC(object):
|
||||
def __init__(self):
|
||||
self._key = None
|
||||
self._iv = None
|
||||
self.aes = None
|
||||
|
||||
def set_decrypt_key(self, userkey, iv):
|
||||
self._key = userkey
|
||||
self._iv = iv
|
||||
self.aes = aescbc.AES_CBC(userkey, aescbc.noPadding(), len(userkey))
|
||||
|
||||
def decrypt(self, data):
|
||||
iv = self._iv
|
||||
cleartext = self.aes.decrypt(iv + data)
|
||||
return cleartext
|
||||
|
||||
|
||||
class KeyIVGen(object):
|
||||
# this only exists in openssl so we will use pure python implementation instead
|
||||
# PKCS5_PBKDF2_HMAC_SHA1 = F(c_int, 'PKCS5_PBKDF2_HMAC_SHA1',
|
||||
# [c_char_p, c_ulong, c_char_p, c_ulong, c_ulong, c_ulong, c_char_p])
|
||||
def pbkdf2(self, passwd, salt, iter, keylen):
|
||||
|
||||
def xorbytes( a, b ):
|
||||
if len(a) != len(b):
|
||||
raise Exception("xorbytes(): lengths differ")
|
||||
return bytes(bytearray([x ^ y for x, y in zip(a, b)]))
|
||||
|
||||
def prf( h, data ):
|
||||
hm = h.copy()
|
||||
hm.update( data )
|
||||
return hm.digest()
|
||||
|
||||
def pbkdf2_F( h, salt, itercount, blocknum ):
|
||||
U = prf( h, salt + pack('>i',blocknum ) )
|
||||
T = U
|
||||
for i in range(2, itercount+1):
|
||||
U = prf( h, U )
|
||||
T = xorbytes( T, U )
|
||||
return T
|
||||
|
||||
sha = hashlib.sha1
|
||||
digest_size = sha().digest_size
|
||||
# l - number of output blocks to produce
|
||||
l = keylen // digest_size
|
||||
if keylen % digest_size != 0:
|
||||
l += 1
|
||||
h = hmac.new( passwd, None, sha )
|
||||
T = b""
|
||||
for i in range(1, l+1):
|
||||
T += pbkdf2_F( h, salt, iter, i )
|
||||
return T[0: keylen]
|
||||
|
||||
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import sys
|
||||
|
||||
# get sys.argv arguments and encode them into utf-8
|
||||
def unicode_argv(default_name):
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows
|
||||
except:
|
||||
iswindows = sys.platform.startswith('win')
|
||||
|
||||
if iswindows:
|
||||
# Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
|
||||
# strings.
|
||||
|
||||
# Versions 2.x of Python don't support Unicode in sys.argv on
|
||||
# Windows, with the underlying Windows API instead replacing multi-byte
|
||||
# characters with '?'.
|
||||
|
||||
|
||||
from ctypes import POINTER, byref, cdll, c_int, windll
|
||||
from ctypes.wintypes import LPCWSTR, LPWSTR
|
||||
|
||||
GetCommandLineW = cdll.kernel32.GetCommandLineW
|
||||
GetCommandLineW.argtypes = []
|
||||
GetCommandLineW.restype = LPCWSTR
|
||||
|
||||
CommandLineToArgvW = windll.shell32.CommandLineToArgvW
|
||||
CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
|
||||
CommandLineToArgvW.restype = POINTER(LPWSTR)
|
||||
|
||||
cmd = GetCommandLineW()
|
||||
argc = c_int(0)
|
||||
argv = CommandLineToArgvW(cmd, byref(argc))
|
||||
if argc.value > 0:
|
||||
# Remove Python executable and commands if present
|
||||
start = argc.value - len(sys.argv)
|
||||
return [argv[i] for i in
|
||||
range(start, argc.value)]
|
||||
# if we don't have any arguments at all, just pass back script name
|
||||
# this should never happen
|
||||
return [ default_name ]
|
||||
else:
|
||||
argvencoding = sys.stdin.encoding or "utf-8"
|
||||
return [arg if (isinstance(arg, str) or isinstance(arg,unicode)) else str(arg, argvencoding) for arg in sys.argv]
|
||||
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,330 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# epubfontdecrypt.py
|
||||
# Copyright © 2021-2023 by noDRM
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
|
||||
# Revision history:
|
||||
# 1 - Initial release
|
||||
# 2 - Bugfix for multiple book IDs, reported at #347
|
||||
|
||||
"""
|
||||
Decrypts / deobfuscates font files in EPUB files
|
||||
"""
|
||||
|
||||
from __future__ import print_function
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = "2"
|
||||
|
||||
import os
|
||||
import traceback
|
||||
import zlib
|
||||
import zipfile
|
||||
from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
|
||||
from zeroedzipinfo import ZeroedZipInfo
|
||||
from contextlib import closing
|
||||
from lxml import etree
|
||||
import itertools
|
||||
import hashlib
|
||||
import binascii
|
||||
|
||||
|
||||
class Decryptor(object):
|
||||
def __init__(self, obfuscationkeyIETF, obfuscationkeyAdobe, encryption):
|
||||
enc = lambda tag: '{%s}%s' % ('http://www.w3.org/2001/04/xmlenc#', tag)
|
||||
dsig = lambda tag: '{%s}%s' % ('http://www.w3.org/2000/09/xmldsig#', tag)
|
||||
self.obfuscation_key_Adobe = obfuscationkeyAdobe
|
||||
self.obfuscation_key_IETF = obfuscationkeyIETF
|
||||
|
||||
self._encryption = etree.fromstring(encryption)
|
||||
# This loops through all entries in the "encryption.xml" file
|
||||
# to figure out which files need to be decrypted.
|
||||
self._obfuscatedIETF = obfuscatedIETF = set()
|
||||
self._obfuscatedAdobe = obfuscatedAdobe = set()
|
||||
self._other = other = set()
|
||||
|
||||
self._json_elements_to_remove = json_elements_to_remove = set()
|
||||
self._has_remaining_xml = False
|
||||
expr = './%s/%s/%s' % (enc('EncryptedData'), enc('CipherData'),
|
||||
enc('CipherReference'))
|
||||
for elem in self._encryption.findall(expr):
|
||||
path = elem.get('URI', None)
|
||||
encryption_type_url = (elem.getparent().getparent().find("./%s" % (enc('EncryptionMethod'))).get('Algorithm', None))
|
||||
if path is not None:
|
||||
|
||||
if encryption_type_url == "http://www.idpf.org/2008/embedding":
|
||||
# Font files obfuscated with the IETF algorithm
|
||||
path = path.encode('utf-8')
|
||||
obfuscatedIETF.add(path)
|
||||
if (self.obfuscation_key_IETF is None):
|
||||
self._has_remaining_xml = True
|
||||
else:
|
||||
json_elements_to_remove.add(elem.getparent().getparent())
|
||||
|
||||
elif encryption_type_url == "http://ns.adobe.com/pdf/enc#RC":
|
||||
# Font files obfuscated with the Adobe algorithm.
|
||||
path = path.encode('utf-8')
|
||||
obfuscatedAdobe.add(path)
|
||||
if (self.obfuscation_key_Adobe is None):
|
||||
self._has_remaining_xml = True
|
||||
else:
|
||||
json_elements_to_remove.add(elem.getparent().getparent())
|
||||
|
||||
else:
|
||||
path = path.encode('utf-8')
|
||||
other.add(path)
|
||||
self._has_remaining_xml = True
|
||||
# Other unsupported type.
|
||||
|
||||
for elem in json_elements_to_remove:
|
||||
elem.getparent().remove(elem)
|
||||
|
||||
def check_if_remaining(self):
|
||||
return self._has_remaining_xml
|
||||
|
||||
def get_xml(self):
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + etree.tostring(self._encryption, encoding="utf-8", pretty_print=True, xml_declaration=False).decode("utf-8")
|
||||
|
||||
def decompress(self, bytes):
|
||||
dc = zlib.decompressobj(-15)
|
||||
try:
|
||||
decompressed_bytes = dc.decompress(bytes)
|
||||
ex = dc.decompress(b'Z') + dc.flush()
|
||||
if ex:
|
||||
decompressed_bytes = decompressed_bytes + ex
|
||||
except:
|
||||
# possibly not compressed by zip - just return bytes
|
||||
return bytes, False
|
||||
return decompressed_bytes , True
|
||||
|
||||
def decrypt(self, path, data):
|
||||
if path.encode('utf-8') in self._obfuscatedIETF and self.obfuscation_key_IETF is not None:
|
||||
# de-obfuscate according to the IETF standard
|
||||
data, was_decomp = self.decompress(data)
|
||||
|
||||
if len(data) <= 1040:
|
||||
# de-obfuscate whole file
|
||||
out = self.deobfuscate_single_data(self.obfuscation_key_IETF, data)
|
||||
else:
|
||||
out = self.deobfuscate_single_data(self.obfuscation_key_IETF, data[:1040]) + data[1040:]
|
||||
|
||||
if (not was_decomp):
|
||||
out, was_decomp = self.decompress(out)
|
||||
return out
|
||||
|
||||
elif path.encode('utf-8') in self._obfuscatedAdobe and self.obfuscation_key_Adobe is not None:
|
||||
# de-obfuscate according to the Adobe standard
|
||||
data, was_decomp = self.decompress(data)
|
||||
|
||||
if len(data) <= 1024:
|
||||
# de-obfuscate whole file
|
||||
out = self.deobfuscate_single_data(self.obfuscation_key_Adobe, data)
|
||||
else:
|
||||
out = self.deobfuscate_single_data(self.obfuscation_key_Adobe, data[:1024]) + data[1024:]
|
||||
|
||||
if (not was_decomp):
|
||||
out, was_decomp = self.decompress(out)
|
||||
return out
|
||||
|
||||
else:
|
||||
# Not encrypted or obfuscated
|
||||
return data
|
||||
|
||||
def deobfuscate_single_data(self, key, data):
|
||||
try:
|
||||
msg = bytes([c^k for c,k in zip(data, itertools.cycle(key))])
|
||||
except TypeError:
|
||||
# Python 2
|
||||
msg = ''.join(chr(ord(c)^ord(k)) for c,k in itertools.izip(data, itertools.cycle(key)))
|
||||
return msg
|
||||
|
||||
|
||||
|
||||
def decryptFontsBook(inpath, outpath):
|
||||
|
||||
with closing(ZipFile(open(inpath, 'rb'))) as inf:
|
||||
namelist = inf.namelist()
|
||||
if 'META-INF/encryption.xml' not in namelist:
|
||||
return 1
|
||||
|
||||
# Font key handling:
|
||||
|
||||
font_master_key = None
|
||||
adobe_master_encryption_key = None
|
||||
|
||||
contNS = lambda tag: '{%s}%s' % ('urn:oasis:names:tc:opendocument:xmlns:container', tag)
|
||||
path = None
|
||||
|
||||
try:
|
||||
container = etree.fromstring(inf.read("META-INF/container.xml"))
|
||||
rootfiles = container.find(contNS("rootfiles")).findall(contNS("rootfile"))
|
||||
for rootfile in rootfiles:
|
||||
path = rootfile.get("full-path", None)
|
||||
if (path is not None):
|
||||
break
|
||||
except:
|
||||
pass
|
||||
|
||||
# If path is None, we didn't find an OPF, so we probably don't have a font key.
|
||||
# If path is set, it's the path to the main content OPF file.
|
||||
|
||||
if (path is None):
|
||||
print("FontDecrypt: No OPF for font obfuscation found")
|
||||
return 1
|
||||
else:
|
||||
packageNS = lambda tag: '{%s}%s' % ('http://www.idpf.org/2007/opf', tag)
|
||||
metadataDCNS = lambda tag: '{%s}%s' % ('http://purl.org/dc/elements/1.1/', tag)
|
||||
|
||||
try:
|
||||
container = etree.fromstring(inf.read(path))
|
||||
except:
|
||||
container = []
|
||||
|
||||
## IETF font key algorithm:
|
||||
print("FontDecrypt: Checking {0} for IETF font obfuscation keys ... ".format(path), end='')
|
||||
secret_key_name = None
|
||||
try:
|
||||
secret_key_name = container.get("unique-identifier")
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
identify_elements = container.find(packageNS("metadata")).findall(metadataDCNS("identifier"))
|
||||
for element in identify_elements:
|
||||
if (secret_key_name is None or secret_key_name == element.get("id")):
|
||||
font_master_key = element.text
|
||||
except:
|
||||
pass
|
||||
|
||||
if (font_master_key is not None):
|
||||
if (secret_key_name is None):
|
||||
print("found '%s'" % (font_master_key))
|
||||
else:
|
||||
print("found '%s' (%s)" % (font_master_key, secret_key_name))
|
||||
|
||||
# Trim / remove forbidden characters from the key, then hash it:
|
||||
font_master_key = font_master_key.replace(' ', '')
|
||||
font_master_key = font_master_key.replace('\t', '')
|
||||
font_master_key = font_master_key.replace('\r', '')
|
||||
font_master_key = font_master_key.replace('\n', '')
|
||||
font_master_key = font_master_key.encode('utf-8')
|
||||
font_master_key = hashlib.sha1(font_master_key).digest()
|
||||
else:
|
||||
print("not found")
|
||||
|
||||
## Adobe font key algorithm
|
||||
print("FontDecrypt: Checking {0} for Adobe font obfuscation keys ... ".format(path), end='')
|
||||
|
||||
try:
|
||||
metadata = container.find(packageNS("metadata"))
|
||||
identifiers = metadata.findall(metadataDCNS("identifier"))
|
||||
|
||||
uid = None
|
||||
uidMalformed = False
|
||||
|
||||
for identifier in identifiers:
|
||||
if identifier.get(packageNS("scheme")) == "UUID":
|
||||
if identifier.text[:9] == "urn:uuid:":
|
||||
uid = identifier.text[9:]
|
||||
else:
|
||||
uid = identifier.text
|
||||
break
|
||||
if identifier.text[:9] == "urn:uuid:":
|
||||
uid = identifier.text[9:]
|
||||
break
|
||||
|
||||
|
||||
if uid is not None:
|
||||
uid = uid.replace(chr(0x20),'').replace(chr(0x09),'')
|
||||
uid = uid.replace(chr(0x0D),'').replace(chr(0x0A),'').replace('-','')
|
||||
|
||||
if len(uid) < 16:
|
||||
uidMalformed = True
|
||||
if not all(c in "0123456789abcdefABCDEF" for c in uid):
|
||||
uidMalformed = True
|
||||
|
||||
|
||||
if not uidMalformed:
|
||||
print("found '{0}'".format(uid))
|
||||
uid = uid + uid
|
||||
adobe_master_encryption_key = binascii.unhexlify(uid[:32])
|
||||
|
||||
if adobe_master_encryption_key is None:
|
||||
print("not found")
|
||||
|
||||
except:
|
||||
print("exception")
|
||||
pass
|
||||
|
||||
# Begin decrypting.
|
||||
|
||||
try:
|
||||
encryption = inf.read('META-INF/encryption.xml')
|
||||
decryptor = Decryptor(font_master_key, adobe_master_encryption_key, encryption)
|
||||
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
||||
with closing(ZipFile(open(outpath, 'wb'), 'w', **kwds)) as outf:
|
||||
|
||||
# Mimetype needs to be the first entry, so remove it from the list
|
||||
# whereever it is, then add it at the beginning.
|
||||
namelist.remove("mimetype")
|
||||
|
||||
for path in (["mimetype"] + namelist):
|
||||
data = inf.read(path)
|
||||
zi = ZipInfo(path)
|
||||
zi.compress_type=ZIP_DEFLATED
|
||||
|
||||
if path == "mimetype":
|
||||
# mimetype must not be compressed
|
||||
zi.compress_type = ZIP_STORED
|
||||
|
||||
elif path == "META-INF/encryption.xml":
|
||||
# Check if there's still other entries not related to fonts
|
||||
if (decryptor.check_if_remaining()):
|
||||
data = decryptor.get_xml()
|
||||
print("FontDecrypt: There's remaining entries in encryption.xml, adding file ...")
|
||||
else:
|
||||
# No remaining entries, no need for that file.
|
||||
continue
|
||||
|
||||
try:
|
||||
# get the file info, including time-stamp
|
||||
oldzi = inf.getinfo(path)
|
||||
# copy across useful fields
|
||||
zi.date_time = oldzi.date_time
|
||||
zi.comment = oldzi.comment
|
||||
zi.extra = oldzi.extra
|
||||
zi.internal_attr = oldzi.internal_attr
|
||||
# external attributes are dependent on the create system, so copy both.
|
||||
zi.external_attr = oldzi.external_attr
|
||||
zi.volume = oldzi.volume
|
||||
zi.create_system = oldzi.create_system
|
||||
zi.create_version = oldzi.create_version
|
||||
|
||||
if any(ord(c) >= 128 for c in path) or any(ord(c) >= 128 for c in zi.comment):
|
||||
# If the file name or the comment contains any non-ASCII char, set the UTF8-flag
|
||||
zi.flag_bits |= 0x800
|
||||
except:
|
||||
pass
|
||||
|
||||
# Python 3 has a bug where the external_attr is reset to `0o600 << 16`
|
||||
# if it's NULL, so we need a workaround:
|
||||
if zi.external_attr == 0:
|
||||
zi = ZeroedZipInfo(zi)
|
||||
|
||||
if path == "mimetype":
|
||||
outf.writestr(zi, inf.read('mimetype'))
|
||||
elif path == "META-INF/encryption.xml":
|
||||
outf.writestr(zi, data)
|
||||
else:
|
||||
outf.writestr(zi, decryptor.decrypt(path, data))
|
||||
except:
|
||||
print("FontDecrypt: Could not decrypt fonts in {0:s} because of an exception:\n{1:s}".format(os.path.basename(inpath), traceback.format_exc()))
|
||||
traceback.print_exc()
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
|
@ -1,344 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# epubwatermark.py
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
# Revision history:
|
||||
# 1.0 - Initial version
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
"""
|
||||
Removes various watermarks from EPUB files
|
||||
"""
|
||||
|
||||
import traceback
|
||||
from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
|
||||
from zeroedzipinfo import ZeroedZipInfo
|
||||
from contextlib import closing
|
||||
from lxml import etree
|
||||
import re
|
||||
|
||||
# Runs a RegEx over all HTML/XHTML files to remove watermakrs.
|
||||
def removeHTMLwatermarks(object, path_to_ebook):
|
||||
try:
|
||||
inf = ZipFile(open(path_to_ebook, 'rb'))
|
||||
namelist = inf.namelist()
|
||||
|
||||
modded_names = []
|
||||
modded_contents = []
|
||||
|
||||
count_adept = 0
|
||||
count_pocketbook = 0
|
||||
count_lemonink_invisible = 0
|
||||
count_lemonink_visible = 0
|
||||
lemonink_trackingID = None
|
||||
|
||||
for file in namelist:
|
||||
if not (file.endswith('.html') or file.endswith('.xhtml') or file.endswith('.xml')):
|
||||
continue
|
||||
|
||||
try:
|
||||
file_str = inf.read(file).decode("utf-8")
|
||||
str_new = file_str
|
||||
|
||||
# Remove Adobe ADEPT watermarks
|
||||
# Match optional newline at the beginning, then a "meta" tag with name = "Adept.expected.resource" or "Adept.resource"
|
||||
# and either a "value" or a "content" element with an Adobe UUID
|
||||
pre_remove = str_new
|
||||
str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<meta\s+name=\"(Adept\.resource|Adept\.expected\.resource)\"\s+(content|value)=\"urn:uuid:[0-9a-fA-F\-]+\"\s*\/>', '', str_new)
|
||||
str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<meta\s+(content|value)=\"urn:uuid:[0-9a-fA-F\-]+\"\s+name=\"(Adept\.resource|Adept\.expected\.resource)\"\s*\/>', '', str_new)
|
||||
|
||||
if (str_new != pre_remove):
|
||||
count_adept += 1
|
||||
|
||||
# Remove Pocketbook watermarks
|
||||
pre_remove = str_new
|
||||
str_new = re.sub(r'\<div style\=\"padding\:0\;border\:0\;text\-indent\:0\;line\-height\:normal\;margin\:0 1cm 0.5cm 1cm\;[^\"]*opacity:0.0\;[^\"]*text\-decoration\:none\;[^\"]*background\:none\;[^\"]*\"\>(.*?)\<\/div\>', '', str_new)
|
||||
|
||||
if (str_new != pre_remove):
|
||||
count_pocketbook += 1
|
||||
|
||||
|
||||
# Remove eLibri / LemonInk watermark
|
||||
# Run this in a loop, as it is possible a file has been watermarked twice ...
|
||||
while True:
|
||||
pre_remove = str_new
|
||||
unique_id = re.search(r'<body[^>]+class="[^"]*(t0x[0-9a-fA-F]{25})[^"]*"[^>]*>', str_new)
|
||||
if (unique_id):
|
||||
lemonink_trackingID = unique_id.groups()[0]
|
||||
count_lemonink_invisible += 1
|
||||
str_new = re.sub(lemonink_trackingID, '', str_new)
|
||||
pre_remove = str_new
|
||||
pm = r'(<body[^>]+class="[^"]*"[^>]*>)'
|
||||
pm += r'\<div style\=\'padding\:0\;border\:0\;text\-indent\:0\;line\-height\:normal\;margin\:0 1cm 0.5cm 1cm\;[^\']*text\-decoration\:none\;[^\']*background\:none\;[^\']*\'\>(.*?)</div>'
|
||||
pm += r'\<div style\=\'padding\:0\;border\:0\;text\-indent\:0\;line\-height\:normal\;margin\:0 1cm 0.5cm 1cm\;[^\']*text\-decoration\:none\;[^\']*background\:none\;[^\']*\'\>(.*?)</div>'
|
||||
str_new = re.sub(pm, r'\1', str_new)
|
||||
|
||||
if (str_new != pre_remove):
|
||||
count_lemonink_visible += 1
|
||||
else:
|
||||
break
|
||||
|
||||
except:
|
||||
traceback.print_exc()
|
||||
continue
|
||||
|
||||
if (file_str == str_new):
|
||||
continue
|
||||
|
||||
modded_names.append(file)
|
||||
modded_contents.append(str_new)
|
||||
|
||||
|
||||
if len(modded_names) == 0:
|
||||
# No file modified, return original
|
||||
return path_to_ebook
|
||||
|
||||
if len(modded_names) != len(modded_contents):
|
||||
# Something went terribly wrong, return original
|
||||
print("Watermark: Error during watermark removal")
|
||||
return path_to_ebook
|
||||
|
||||
# Re-package with modified files:
|
||||
namelist.remove("mimetype")
|
||||
|
||||
try:
|
||||
output = object.temporary_file(".epub").name
|
||||
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
||||
with closing(ZipFile(open(output, 'wb'), 'w', **kwds)) as outf:
|
||||
for path in (["mimetype"] + namelist):
|
||||
|
||||
data = inf.read(path)
|
||||
|
||||
try:
|
||||
modded_index = None
|
||||
modded_index = modded_names.index(path)
|
||||
except:
|
||||
pass
|
||||
|
||||
if modded_index is not None:
|
||||
# Found modified file - replace contents
|
||||
data = modded_contents[modded_index]
|
||||
|
||||
zi = ZipInfo(path)
|
||||
oldzi = inf.getinfo(path)
|
||||
try:
|
||||
zi.compress_type = oldzi.compress_type
|
||||
if path == "mimetype":
|
||||
zi.compress_type = ZIP_STORED
|
||||
zi.date_time = oldzi.date_time
|
||||
zi.comment = oldzi.comment
|
||||
zi.extra = oldzi.extra
|
||||
zi.internal_attr = oldzi.internal_attr
|
||||
zi.external_attr = oldzi.external_attr
|
||||
zi.volume = oldzi.volume
|
||||
zi.create_system = oldzi.create_system
|
||||
zi.create_version = oldzi.create_version
|
||||
|
||||
if any(ord(c) >= 128 for c in path) or any(ord(c) >= 128 for c in zi.comment):
|
||||
# If the file name or the comment contains any non-ASCII char, set the UTF8-flag
|
||||
zi.flag_bits |= 0x800
|
||||
except:
|
||||
pass
|
||||
|
||||
# Python 3 has a bug where the external_attr is reset to `0o600 << 16`
|
||||
# if it's NULL, so we need a workaround:
|
||||
if zi.external_attr == 0:
|
||||
zi = ZeroedZipInfo(zi)
|
||||
|
||||
|
||||
outf.writestr(zi, data)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
if (count_adept > 0):
|
||||
print("Watermark: Successfully stripped {0} ADEPT watermark(s) from ebook.".format(count_adept))
|
||||
|
||||
if (count_lemonink_invisible > 0 or count_lemonink_visible > 0):
|
||||
print("Watermark: Successfully stripped {0} visible and {1} invisible LemonInk watermark(s) (\"{2}\") from ebook."
|
||||
.format(count_lemonink_visible, count_lemonink_invisible, lemonink_trackingID))
|
||||
|
||||
if (count_pocketbook > 0):
|
||||
print("Watermark: Successfully stripped {0} Pocketbook watermark(s) from ebook.".format(count_pocketbook))
|
||||
|
||||
return output
|
||||
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
|
||||
|
||||
|
||||
# Finds the main OPF file, then uses RegEx to remove watermarks
|
||||
def removeOPFwatermarks(object, path_to_ebook):
|
||||
contNS = lambda tag: '{%s}%s' % ('urn:oasis:names:tc:opendocument:xmlns:container', tag)
|
||||
opf_path = None
|
||||
|
||||
try:
|
||||
inf = ZipFile(open(path_to_ebook, 'rb'))
|
||||
container = etree.fromstring(inf.read("META-INF/container.xml"))
|
||||
rootfiles = container.find(contNS("rootfiles")).findall(contNS("rootfile"))
|
||||
for rootfile in rootfiles:
|
||||
opf_path = rootfile.get("full-path", None)
|
||||
if (opf_path is not None):
|
||||
break
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
# If path is None, we didn't find an OPF, so we probably don't have a font key.
|
||||
# If path is set, it's the path to the main content OPF file.
|
||||
|
||||
if (opf_path is None):
|
||||
# No OPF found - no watermark
|
||||
return path_to_ebook
|
||||
else:
|
||||
try:
|
||||
container_str = inf.read(opf_path).decode("utf-8")
|
||||
container_str_new = container_str
|
||||
|
||||
had_amazon = False
|
||||
had_elibri = False
|
||||
|
||||
# Remove Amazon hex watermarks
|
||||
# Match optional newline at the beginning, then spaces, then a "meta" tag with name = "Watermark" or "Watermark_(hex)" and a "content" element.
|
||||
# This regex also matches DuMont watermarks with meta name="watermark", with the case-insensitive match on the "w" in watermark.
|
||||
pre_remove = container_str_new
|
||||
container_str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<meta\s+name=\"[Ww]atermark(_\(hex\))?\"\s+content=\"[0-9a-fA-F]+\"\s*\/>', '', container_str_new)
|
||||
container_str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<meta\s+content=\"[0-9a-fA-F]+\"\s+name=\"[Ww]atermark(_\(hex\))?\"\s*\/>', '', container_str_new)
|
||||
if pre_remove != container_str_new:
|
||||
had_amazon = True
|
||||
|
||||
# Remove elibri / lemonink watermark
|
||||
# Lemonink replaces all "id" fields in the opf with "idX_Y", with X being the watermark and Y being a number for that particular ID.
|
||||
# This regex replaces all "idX_Y" IDs with "id_Y", removing the watermark IDs.
|
||||
pre_remove = container_str_new
|
||||
container_str_new = re.sub(r'((\r\n|\r|\n)\s*)?\<\!\-\-\s*Wygenerowane przez elibri dla zamówienia numer [0-9a-fA-F]+\s*\-\-\>', '', container_str_new)
|
||||
if pre_remove != container_str_new:
|
||||
# To prevent this Regex from applying to books without that watermark, only do that if the watermark above was found.
|
||||
container_str_new = re.sub(r'\=\"id[0-9]+_([0-9]+)\"', r'="id_\1"', container_str_new)
|
||||
if pre_remove != container_str_new:
|
||||
had_elibri = True
|
||||
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
if (container_str == container_str_new):
|
||||
# container didn't change - no watermark
|
||||
return path_to_ebook
|
||||
|
||||
# Re-package without watermark
|
||||
namelist = inf.namelist()
|
||||
namelist.remove("mimetype")
|
||||
|
||||
try:
|
||||
output = object.temporary_file(".epub").name
|
||||
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
||||
with closing(ZipFile(open(output, 'wb'), 'w', **kwds)) as outf:
|
||||
for path in (["mimetype"] + namelist):
|
||||
|
||||
data = inf.read(path)
|
||||
if path == opf_path:
|
||||
# Found OPF, replacing ...
|
||||
data = container_str_new
|
||||
|
||||
zi = ZipInfo(path)
|
||||
oldzi = inf.getinfo(path)
|
||||
try:
|
||||
zi.compress_type = oldzi.compress_type
|
||||
if path == "mimetype":
|
||||
zi.compress_type = ZIP_STORED
|
||||
zi.date_time = oldzi.date_time
|
||||
zi.comment = oldzi.comment
|
||||
zi.extra = oldzi.extra
|
||||
zi.internal_attr = oldzi.internal_attr
|
||||
zi.external_attr = oldzi.external_attr
|
||||
zi.volume = oldzi.volume
|
||||
zi.create_system = oldzi.create_system
|
||||
zi.create_version = oldzi.create_version
|
||||
|
||||
if any(ord(c) >= 128 for c in path) or any(ord(c) >= 128 for c in zi.comment):
|
||||
# If the file name or the comment contains any non-ASCII char, set the UTF8-flag
|
||||
zi.flag_bits |= 0x800
|
||||
except:
|
||||
pass
|
||||
|
||||
# Python 3 has a bug where the external_attr is reset to `0o600 << 16`
|
||||
# if it's NULL, so we need a workaround:
|
||||
if zi.external_attr == 0:
|
||||
zi = ZeroedZipInfo(zi)
|
||||
|
||||
outf.writestr(zi, data)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
||||
if had_elibri:
|
||||
print("Watermark: Successfully stripped eLibri watermark from OPF file.")
|
||||
if had_amazon:
|
||||
print("Watermark: Successfully stripped Amazon watermark from OPF file.")
|
||||
|
||||
return output
|
||||
|
||||
|
||||
|
||||
def removeCDPwatermark(object, path_to_ebook):
|
||||
# "META-INF/cdp.info" is a watermark file used by some Tolino vendors.
|
||||
# We don't want that in our eBooks, so lets remove that file.
|
||||
try:
|
||||
infile = ZipFile(open(path_to_ebook, 'rb'))
|
||||
namelist = infile.namelist()
|
||||
if 'META-INF/cdp.info' not in namelist:
|
||||
return path_to_ebook
|
||||
|
||||
namelist.remove("mimetype")
|
||||
namelist.remove("META-INF/cdp.info")
|
||||
|
||||
output = object.temporary_file(".epub").name
|
||||
|
||||
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
||||
with closing(ZipFile(open(output, 'wb'), 'w', **kwds)) as outf:
|
||||
for path in (["mimetype"] + namelist):
|
||||
|
||||
data = infile.read(path)
|
||||
|
||||
zi = ZipInfo(path)
|
||||
oldzi = infile.getinfo(path)
|
||||
try:
|
||||
zi.compress_type = oldzi.compress_type
|
||||
if path == "mimetype":
|
||||
zi.compress_type = ZIP_STORED
|
||||
zi.date_time = oldzi.date_time
|
||||
zi.comment = oldzi.comment
|
||||
zi.extra = oldzi.extra
|
||||
zi.internal_attr = oldzi.internal_attr
|
||||
zi.external_attr = oldzi.external_attr
|
||||
zi.volume = oldzi.volume
|
||||
zi.create_system = oldzi.create_system
|
||||
zi.create_version = oldzi.create_version
|
||||
|
||||
if any(ord(c) >= 128 for c in path) or any(ord(c) >= 128 for c in zi.comment):
|
||||
# If the file name or the comment contains any non-ASCII char, set the UTF8-flag
|
||||
zi.flag_bits |= 0x800
|
||||
except:
|
||||
pass
|
||||
|
||||
# Python 3 has a bug where the external_attr is reset to `0o600 << 16`
|
||||
# if it's NULL, so we need a workaround:
|
||||
if zi.external_attr == 0:
|
||||
zi = ZeroedZipInfo(zi)
|
||||
|
||||
outf.writestr(zi, data)
|
||||
|
||||
print("Watermark: Successfully removed cdp.info watermark")
|
||||
return output
|
||||
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return path_to_ebook
|
||||
|
|
@ -1,68 +0,0 @@
|
|||
'''
|
||||
Extracts the user's ccHash from an .adobe-digital-editions folder
|
||||
typically included in the Nook Android app's data folder.
|
||||
|
||||
Based on ignoblekeyWindowsStore.py, updated for Android by noDRM.
|
||||
'''
|
||||
|
||||
import sys
|
||||
import os
|
||||
import base64
|
||||
try:
|
||||
from Cryptodome.Cipher import AES
|
||||
except ImportError:
|
||||
from Crypto.Cipher import AES
|
||||
import hashlib
|
||||
from lxml import etree
|
||||
|
||||
def unpad(data, padding=16):
|
||||
if sys.version_info[0] == 2:
|
||||
pad_len = ord(data[-1])
|
||||
else:
|
||||
pad_len = data[-1]
|
||||
|
||||
return data[:-pad_len]
|
||||
|
||||
|
||||
PASS_HASH_SECRET = "9ca588496a1bc4394553d9e018d70b9e"
|
||||
|
||||
|
||||
def dump_keys(path_to_adobe_folder):
|
||||
|
||||
activation_path = os.path.join(path_to_adobe_folder, "activation.xml")
|
||||
device_path = os.path.join(path_to_adobe_folder, "device.xml")
|
||||
|
||||
if not os.path.isfile(activation_path):
|
||||
print("Nook activation file is missing: %s\n" % activation_path)
|
||||
return []
|
||||
if not os.path.isfile(device_path):
|
||||
print("Nook device file is missing: %s\n" % device_path)
|
||||
return []
|
||||
|
||||
# Load files:
|
||||
activation_xml = etree.parse(activation_path)
|
||||
device_xml = etree.parse(device_path)
|
||||
|
||||
# Get fingerprint:
|
||||
device_fingerprint = device_xml.findall(".//{http://ns.adobe.com/adept}fingerprint")[0].text
|
||||
device_fingerprint = base64.b64decode(device_fingerprint).hex()
|
||||
|
||||
hash_key = hashlib.sha1(bytearray.fromhex(device_fingerprint + PASS_HASH_SECRET)).digest()[:16]
|
||||
|
||||
hashes = []
|
||||
|
||||
for pass_hash in activation_xml.findall(".//{http://ns.adobe.com/adept}passHash"):
|
||||
try:
|
||||
encrypted_cc_hash = base64.b64decode(pass_hash.text)
|
||||
cc_hash = unpad(AES.new(hash_key, AES.MODE_CBC, encrypted_cc_hash[:16]).decrypt(encrypted_cc_hash[16:]))
|
||||
hashes.append(base64.b64encode(cc_hash).decode("ascii"))
|
||||
#print("Nook ccHash is %s" % (base64.b64encode(cc_hash).decode("ascii")))
|
||||
except:
|
||||
pass
|
||||
|
||||
return hashes
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("No standalone version available.")
|
||||
|
|
@ -1,187 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# ignoblekeyGenPassHash.py
|
||||
# Copyright © 2009-2022 i♥cabbages, Apprentice Harper et al.
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
# Windows users: Before running this program, you must first install Python.
|
||||
# We recommend ActiveState Python 2.7.X for Windows (x86) from
|
||||
# http://www.activestate.com/activepython/downloads.
|
||||
# You must also install PyCrypto from
|
||||
# http://www.voidspace.org.uk/python/modules.shtml#pycrypto
|
||||
# (make certain to install the version for Python 2.7).
|
||||
# Then save this script file as ignoblekeygen.pyw and double-click on it to run it.
|
||||
#
|
||||
# Mac OS X users: Save this script file as ignoblekeygen.pyw. You can run this
|
||||
# program from the command line (python ignoblekeygen.pyw) or by double-clicking
|
||||
# it when it has been associated with PythonLauncher.
|
||||
|
||||
# Revision history:
|
||||
# 1 - Initial release
|
||||
# 2 - Add OS X support by using OpenSSL when available (taken/modified from ineptepub v5)
|
||||
# 2.1 - Allow Windows versions of libcrypto to be found
|
||||
# 2.2 - On Windows try PyCrypto first and then OpenSSL next
|
||||
# 2.3 - Modify interface to allow use of import
|
||||
# 2.4 - Improvements to UI and now works in plugins
|
||||
# 2.5 - Additional improvement for unicode and plugin support
|
||||
# 2.6 - moved unicode_argv call inside main for Windows DeDRM compatibility
|
||||
# 2.7 - Work if TkInter is missing
|
||||
# 2.8 - Fix bug in stand-alone use (import tkFileDialog)
|
||||
# 3.0 - Added Python 3 compatibility for calibre 5.0
|
||||
# 3.1 - Remove OpenSSL support, only PyCryptodome is supported now
|
||||
|
||||
"""
|
||||
Generate Barnes & Noble EPUB user key from name and credit card number.
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = "3.1"
|
||||
|
||||
import sys
|
||||
import os
|
||||
import hashlib
|
||||
import base64
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
try:
|
||||
from Cryptodome.Cipher import AES
|
||||
except ImportError:
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
from .utilities import SafeUnbuffered
|
||||
|
||||
from .argv_utils import unicode_argv
|
||||
|
||||
class IGNOBLEError(Exception):
|
||||
pass
|
||||
|
||||
def normalize_name(name):
|
||||
return ''.join(x for x in name.lower() if x != ' ')
|
||||
|
||||
|
||||
def generate_key(name, ccn):
|
||||
# remove spaces and case from name and CC numbers.
|
||||
name = normalize_name(name)
|
||||
ccn = normalize_name(ccn)
|
||||
|
||||
if type(name)==str:
|
||||
name = name.encode('utf-8')
|
||||
if type(ccn)==str:
|
||||
ccn = ccn.encode('utf-8')
|
||||
|
||||
name = name + b'\x00'
|
||||
ccn = ccn + b'\x00'
|
||||
|
||||
name_sha = hashlib.sha1(name).digest()[:16]
|
||||
ccn_sha = hashlib.sha1(ccn).digest()[:16]
|
||||
both_sha = hashlib.sha1(name + ccn).digest()
|
||||
crypt = AES.new(ccn_sha, AES.MODE_CBC, name_sha).encrypt(both_sha + (b'\x0c' * 0x0c))
|
||||
userkey = hashlib.sha1(crypt).digest()
|
||||
return base64.b64encode(userkey)
|
||||
|
||||
|
||||
def cli_main():
|
||||
sys.stdout=SafeUnbuffered(sys.stdout)
|
||||
sys.stderr=SafeUnbuffered(sys.stderr)
|
||||
argv=unicode_argv("ignoblekeyGenPassHash.py")
|
||||
progname = os.path.basename(argv[0])
|
||||
if len(argv) != 4:
|
||||
print("usage: {0} <Name> <CC#> <keyfileout.b64>".format(progname))
|
||||
return 1
|
||||
name, ccn, keypath = argv[1:]
|
||||
userkey = generate_key(name, ccn)
|
||||
open(keypath,'wb').write(userkey)
|
||||
return 0
|
||||
|
||||
|
||||
def gui_main():
|
||||
try:
|
||||
import tkinter
|
||||
import tkinter.constants
|
||||
import tkinter.messagebox
|
||||
import tkinter.filedialog
|
||||
import traceback
|
||||
except:
|
||||
return cli_main()
|
||||
|
||||
class DecryptionDialog(tkinter.Frame):
|
||||
def __init__(self, root):
|
||||
tkinter.Frame.__init__(self, root, border=5)
|
||||
self.status = tkinter.Label(self, text="Enter parameters")
|
||||
self.status.pack(fill=tkinter.constants.X, expand=1)
|
||||
body = tkinter.Frame(self)
|
||||
body.pack(fill=tkinter.constants.X, expand=1)
|
||||
sticky = tkinter.constants.E + tkinter.constants.W
|
||||
body.grid_columnconfigure(1, weight=2)
|
||||
tkinter.Label(body, text="Account Name").grid(row=0)
|
||||
self.name = tkinter.Entry(body, width=40)
|
||||
self.name.grid(row=0, column=1, sticky=sticky)
|
||||
tkinter.Label(body, text="CC#").grid(row=1)
|
||||
self.ccn = tkinter.Entry(body, width=40)
|
||||
self.ccn.grid(row=1, column=1, sticky=sticky)
|
||||
tkinter.Label(body, text="Output file").grid(row=2)
|
||||
self.keypath = tkinter.Entry(body, width=40)
|
||||
self.keypath.grid(row=2, column=1, sticky=sticky)
|
||||
self.keypath.insert(2, "bnepubkey.b64")
|
||||
button = tkinter.Button(body, text="...", command=self.get_keypath)
|
||||
button.grid(row=2, column=2)
|
||||
buttons = tkinter.Frame(self)
|
||||
buttons.pack()
|
||||
botton = tkinter.Button(
|
||||
buttons, text="Generate", width=10, command=self.generate)
|
||||
botton.pack(side=tkinter.constants.LEFT)
|
||||
tkinter.Frame(buttons, width=10).pack(side=tkinter.constants.LEFT)
|
||||
button = tkinter.Button(
|
||||
buttons, text="Quit", width=10, command=self.quit)
|
||||
button.pack(side=tkinter.constants.RIGHT)
|
||||
|
||||
def get_keypath(self):
|
||||
keypath = tkinter.filedialog.asksaveasfilename(
|
||||
parent=None, title="Select B&N ePub key file to produce",
|
||||
defaultextension=".b64",
|
||||
filetypes=[('base64-encoded files', '.b64'),
|
||||
('All Files', '.*')])
|
||||
if keypath:
|
||||
keypath = os.path.normpath(keypath)
|
||||
self.keypath.delete(0, tkinter.constants.END)
|
||||
self.keypath.insert(0, keypath)
|
||||
return
|
||||
|
||||
def generate(self):
|
||||
name = self.name.get()
|
||||
ccn = self.ccn.get()
|
||||
keypath = self.keypath.get()
|
||||
if not name:
|
||||
self.status['text'] = "Name not specified"
|
||||
return
|
||||
if not ccn:
|
||||
self.status['text'] = "Credit card number not specified"
|
||||
return
|
||||
if not keypath:
|
||||
self.status['text'] = "Output keyfile path not specified"
|
||||
return
|
||||
self.status['text'] = "Generating..."
|
||||
try:
|
||||
userkey = generate_key(name, ccn)
|
||||
except Exception as e:
|
||||
self.status['text'] = "Error: (0}".format(e.args[0])
|
||||
return
|
||||
open(keypath,'wb').write(userkey)
|
||||
self.status['text'] = "Keyfile successfully generated"
|
||||
|
||||
root = tkinter.Tk()
|
||||
root.title("Barnes & Noble ePub Keyfile Generator v.{0}".format(__version__))
|
||||
root.resizable(True, False)
|
||||
root.minsize(300, 0)
|
||||
DecryptionDialog(root).pack(fill=tkinter.constants.X, expand=1)
|
||||
root.mainloop()
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) > 1:
|
||||
sys.exit(cli_main())
|
||||
sys.exit(gui_main())
|
||||
|
|
@ -1,78 +0,0 @@
|
|||
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
|
||||
|
||||
'''
|
||||
Obtain the user's ccHash from the Barnes & Noble Nook Windows Store app.
|
||||
https://www.microsoft.com/en-us/p/nook-books-magazines-newspapers-comics/9wzdncrfj33h
|
||||
(Requires a recent Windows version in a supported region (US).)
|
||||
This procedure has been tested with Nook app version 1.11.0.4 under Windows 11.
|
||||
|
||||
Based on experimental standalone python script created by fesiwi at
|
||||
https://github.com/noDRM/DeDRM_tools/discussions/9
|
||||
'''
|
||||
|
||||
import sys, os
|
||||
import apsw
|
||||
import base64
|
||||
import traceback
|
||||
try:
|
||||
from Cryptodome.Cipher import AES
|
||||
except:
|
||||
from Crypto.Cipher import AES
|
||||
import hashlib
|
||||
from lxml import etree
|
||||
|
||||
def unpad(data, padding=16):
|
||||
if sys.version_info[0] == 2:
|
||||
pad_len = ord(data[-1])
|
||||
else:
|
||||
pad_len = data[-1]
|
||||
|
||||
return data[:-pad_len]
|
||||
|
||||
|
||||
NOOK_DATA_FOLDER = "%LOCALAPPDATA%\\Packages\\BarnesNoble.Nook_ahnzqzva31enc\\LocalState"
|
||||
PASS_HASH_SECRET = "9ca588496a1bc4394553d9e018d70b9e"
|
||||
|
||||
|
||||
def dump_keys(print_result=False):
|
||||
db_filename = os.path.expandvars(NOOK_DATA_FOLDER + "\\NookDB.db3")
|
||||
|
||||
|
||||
if not os.path.isfile(db_filename):
|
||||
print("Database file not found. Is the Nook Windows Store app installed?")
|
||||
return []
|
||||
|
||||
|
||||
# Python2 has no fetchone() so we have to use fetchall() and discard everything but the first result.
|
||||
# There should only be one result anyways.
|
||||
serial_number = apsw.Connection(db_filename).cursor().execute(
|
||||
"SELECT value FROM bn_internal_key_value_table WHERE key = 'serialNumber';").fetchall()[0][0]
|
||||
|
||||
|
||||
hash_key = hashlib.sha1(bytearray.fromhex(serial_number + PASS_HASH_SECRET)).digest()[:16]
|
||||
|
||||
activation_file_name = os.path.expandvars(NOOK_DATA_FOLDER + "\\settings\\activation.xml")
|
||||
|
||||
if not os.path.isfile(activation_file_name):
|
||||
print("Activation file not found. Are you logged in to your Nook account?")
|
||||
return []
|
||||
|
||||
|
||||
activation_xml = etree.parse(activation_file_name)
|
||||
|
||||
decrypted_hashes = []
|
||||
|
||||
for pass_hash in activation_xml.findall(".//{http://ns.adobe.com/adept}passHash"):
|
||||
try:
|
||||
encrypted_cc_hash = base64.b64decode(pass_hash.text)
|
||||
cc_hash = unpad(AES.new(hash_key, AES.MODE_CBC, encrypted_cc_hash[:16]).decrypt(encrypted_cc_hash[16:]), 16)
|
||||
decrypted_hashes.append((base64.b64encode(cc_hash).decode("ascii")))
|
||||
if print_result:
|
||||
print("Nook ccHash is %s" % (base64.b64encode(cc_hash).decode("ascii")))
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
return decrypted_hashes
|
||||
|
||||
if __name__ == "__main__":
|
||||
dump_keys(True)
|
||||
|
|
@ -1,467 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# ineptepub.py
|
||||
# Copyright © 2009-2022 by i♥cabbages, Apprentice Harper et al.
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
|
||||
# Revision history:
|
||||
# 1 - Initial release
|
||||
# 2 - Rename to INEPT, fix exit code
|
||||
# 5 - Version bump to avoid (?) confusion;
|
||||
# Improve OS X support by using OpenSSL when available
|
||||
# 5.1 - Improve OpenSSL error checking
|
||||
# 5.2 - Fix ctypes error causing segfaults on some systems
|
||||
# 5.3 - add support for OpenSSL on Windows, fix bug with some versions of libcrypto 0.9.8 prior to path level o
|
||||
# 5.4 - add support for encoding to 'utf-8' when building up list of files to decrypt from encryption.xml
|
||||
# 5.5 - On Windows try PyCrypto first, OpenSSL next
|
||||
# 5.6 - Modify interface to allow use with import
|
||||
# 5.7 - Fix for potential problem with PyCrypto
|
||||
# 5.8 - Revised to allow use in calibre plugins to eliminate need for duplicate code
|
||||
# 5.9 - Fixed to retain zip file metadata (e.g. file modification date)
|
||||
# 6.0 - moved unicode_argv call inside main for Windows DeDRM compatibility
|
||||
# 6.1 - Work if TkInter is missing
|
||||
# 6.2 - Handle UTF-8 file names inside an ePub, fix by Jose Luis
|
||||
# 6.3 - Add additional check on DER file sanity
|
||||
# 6.4 - Remove erroneous check on DER file sanity
|
||||
# 6.5 - Completely remove erroneous check on DER file sanity
|
||||
# 6.6 - Import tkFileDialog, don't assume something else will import it.
|
||||
# 7.0 - Add Python 3 compatibility for calibre 5.0
|
||||
# 7.1 - Add ignoble support, dropping the dedicated ignobleepub.py script
|
||||
# 7.2 - Only support PyCryptodome; clean up the code
|
||||
# 8.0 - Add support for "hardened" Adobe DRM (RMSDK >= 10)
|
||||
|
||||
"""
|
||||
Decrypt Adobe Digital Editions encrypted ePub books.
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = "8.0"
|
||||
|
||||
import sys
|
||||
import os
|
||||
import traceback
|
||||
import base64
|
||||
import zlib
|
||||
import zipfile
|
||||
from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
|
||||
from zeroedzipinfo import ZeroedZipInfo
|
||||
from contextlib import closing
|
||||
from lxml import etree
|
||||
from uuid import UUID
|
||||
import hashlib
|
||||
|
||||
try:
|
||||
from Cryptodome.Cipher import AES, PKCS1_v1_5
|
||||
from Cryptodome.PublicKey import RSA
|
||||
except ImportError:
|
||||
from Crypto.Cipher import AES, PKCS1_v1_5
|
||||
from Crypto.PublicKey import RSA
|
||||
|
||||
|
||||
def unpad(data, padding=16):
|
||||
if sys.version_info[0] == 2:
|
||||
pad_len = ord(data[-1])
|
||||
else:
|
||||
pad_len = data[-1]
|
||||
|
||||
return data[:-pad_len]
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
from .utilities import SafeUnbuffered
|
||||
from .argv_utils import unicode_argv
|
||||
|
||||
|
||||
class ADEPTError(Exception):
|
||||
pass
|
||||
|
||||
class ADEPTNewVersionError(Exception):
|
||||
pass
|
||||
|
||||
META_NAMES = ('mimetype', 'META-INF/rights.xml')
|
||||
NSMAP = {'adept': 'http://ns.adobe.com/adept',
|
||||
'enc': 'http://www.w3.org/2001/04/xmlenc#'}
|
||||
|
||||
class Decryptor(object):
|
||||
def __init__(self, bookkey, encryption):
|
||||
enc = lambda tag: '{%s}%s' % (NSMAP['enc'], tag)
|
||||
self._aes = AES.new(bookkey, AES.MODE_CBC, b'\x00'*16)
|
||||
self._encryption = etree.fromstring(encryption)
|
||||
self._encrypted = encrypted = set()
|
||||
self._encryptedForceNoDecomp = encryptedForceNoDecomp = set()
|
||||
self._otherData = otherData = set()
|
||||
|
||||
self._json_elements_to_remove = json_elements_to_remove = set()
|
||||
self._has_remaining_xml = False
|
||||
expr = './%s/%s/%s' % (enc('EncryptedData'), enc('CipherData'),
|
||||
enc('CipherReference'))
|
||||
for elem in self._encryption.findall(expr):
|
||||
path = elem.get('URI', None)
|
||||
encryption_type_url = (elem.getparent().getparent().find("./%s" % (enc('EncryptionMethod'))).get('Algorithm', None))
|
||||
if path is not None:
|
||||
if (encryption_type_url == "http://www.w3.org/2001/04/xmlenc#aes128-cbc"):
|
||||
# Adobe
|
||||
path = path.encode('utf-8')
|
||||
encrypted.add(path)
|
||||
json_elements_to_remove.add(elem.getparent().getparent())
|
||||
elif (encryption_type_url == "http://ns.adobe.com/adept/xmlenc#aes128-cbc-uncompressed"):
|
||||
# Adobe uncompressed, for stuff like video files
|
||||
path = path.encode('utf-8')
|
||||
encryptedForceNoDecomp.add(path)
|
||||
json_elements_to_remove.add(elem.getparent().getparent())
|
||||
else:
|
||||
path = path.encode('utf-8')
|
||||
otherData.add(path)
|
||||
self._has_remaining_xml = True
|
||||
|
||||
for elem in json_elements_to_remove:
|
||||
elem.getparent().remove(elem)
|
||||
|
||||
def check_if_remaining(self):
|
||||
return self._has_remaining_xml
|
||||
|
||||
def get_xml(self):
|
||||
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + etree.tostring(self._encryption, encoding="utf-8", pretty_print=True, xml_declaration=False).decode("utf-8")
|
||||
|
||||
|
||||
def decompress(self, bytes):
|
||||
dc = zlib.decompressobj(-15)
|
||||
try:
|
||||
decompressed_bytes = dc.decompress(bytes)
|
||||
ex = dc.decompress(b'Z') + dc.flush()
|
||||
if ex:
|
||||
decompressed_bytes = decompressed_bytes + ex
|
||||
except:
|
||||
# possibly not compressed by zip - just return bytes
|
||||
return bytes
|
||||
return decompressed_bytes
|
||||
|
||||
def decrypt(self, path, data):
|
||||
if path.encode('utf-8') in self._encrypted or path.encode('utf-8') in self._encryptedForceNoDecomp:
|
||||
data = self._aes.decrypt(data)[16:]
|
||||
if type(data[-1]) != int:
|
||||
place = ord(data[-1])
|
||||
else:
|
||||
place = data[-1]
|
||||
data = data[:-place]
|
||||
if not path.encode('utf-8') in self._encryptedForceNoDecomp:
|
||||
data = self.decompress(data)
|
||||
return data
|
||||
|
||||
# check file to make check whether it's probably an Adobe Adept encrypted ePub
|
||||
def adeptBook(inpath):
|
||||
with closing(ZipFile(open(inpath, 'rb'))) as inf:
|
||||
namelist = set(inf.namelist())
|
||||
if 'META-INF/rights.xml' not in namelist or \
|
||||
'META-INF/encryption.xml' not in namelist:
|
||||
return False
|
||||
try:
|
||||
rights = etree.fromstring(inf.read('META-INF/rights.xml'))
|
||||
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
|
||||
expr = './/%s' % (adept('encryptedKey'),)
|
||||
bookkey = ''.join(rights.findtext(expr))
|
||||
if len(bookkey) in [192, 172, 64]:
|
||||
return True
|
||||
except:
|
||||
# if we couldn't check, assume it is
|
||||
return True
|
||||
return False
|
||||
|
||||
def isPassHashBook(inpath):
|
||||
# If this is an Adobe book, check if it's a PassHash-encrypted book (B&N)
|
||||
with closing(ZipFile(open(inpath, 'rb'))) as inf:
|
||||
namelist = set(inf.namelist())
|
||||
if 'META-INF/rights.xml' not in namelist or \
|
||||
'META-INF/encryption.xml' not in namelist:
|
||||
return False
|
||||
try:
|
||||
rights = etree.fromstring(inf.read('META-INF/rights.xml'))
|
||||
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
|
||||
expr = './/%s' % (adept('encryptedKey'),)
|
||||
bookkey = ''.join(rights.findtext(expr))
|
||||
if len(bookkey) == 64:
|
||||
return True
|
||||
except:
|
||||
pass
|
||||
|
||||
return False
|
||||
|
||||
# Checks the license file and returns the UUID the book is licensed for.
|
||||
# This is used so that the Calibre plugin can pick the correct decryption key
|
||||
# first try without having to loop through all possible keys.
|
||||
def adeptGetUserUUID(inpath):
|
||||
with closing(ZipFile(open(inpath, 'rb'))) as inf:
|
||||
try:
|
||||
rights = etree.fromstring(inf.read('META-INF/rights.xml'))
|
||||
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
|
||||
expr = './/%s' % (adept('user'),)
|
||||
user_uuid = ''.join(rights.findtext(expr))
|
||||
if user_uuid[:9] != "urn:uuid:":
|
||||
return None
|
||||
return user_uuid[9:]
|
||||
except:
|
||||
return None
|
||||
|
||||
def removeHardening(rights, keytype, keydata):
|
||||
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
|
||||
textGetter = lambda name: ''.join(rights.findtext('.//%s' % (adept(name),)))
|
||||
|
||||
# Gather what we need, and generate the IV
|
||||
resourceuuid = UUID(textGetter("resource"))
|
||||
deviceuuid = UUID(textGetter("device"))
|
||||
fullfillmentuuid = UUID(textGetter("fulfillment")[:36])
|
||||
kekiv = UUID(int=resourceuuid.int ^ deviceuuid.int ^ fullfillmentuuid.int).bytes
|
||||
|
||||
# Derive kek from just "keytype"
|
||||
rem = int(keytype, 10) % 16
|
||||
H = hashlib.sha256(keytype.encode("ascii")).digest()
|
||||
kek = H[2*rem : 16 + rem] + H[rem : 2*rem]
|
||||
|
||||
return unpad(AES.new(kek, AES.MODE_CBC, kekiv).decrypt(keydata), 16) # PKCS#7
|
||||
|
||||
def decryptBook(userkey, inpath, outpath):
|
||||
with closing(ZipFile(open(inpath, 'rb'))) as inf:
|
||||
namelist = inf.namelist()
|
||||
if 'META-INF/rights.xml' not in namelist or \
|
||||
'META-INF/encryption.xml' not in namelist:
|
||||
print("{0:s} is DRM-free.".format(os.path.basename(inpath)))
|
||||
return 1
|
||||
for name in META_NAMES:
|
||||
namelist.remove(name)
|
||||
try:
|
||||
rights = etree.fromstring(inf.read('META-INF/rights.xml'))
|
||||
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
|
||||
expr = './/%s' % (adept('encryptedKey'),)
|
||||
bookkeyelem = rights.find(expr)
|
||||
bookkey = bookkeyelem.text
|
||||
keytype = bookkeyelem.attrib.get('keyType', '0')
|
||||
if len(bookkey) >= 172 and int(keytype, 10) > 2:
|
||||
print("{0:s} is a secure Adobe Adept ePub with hardening.".format(os.path.basename(inpath)))
|
||||
elif len(bookkey) == 172:
|
||||
print("{0:s} is a secure Adobe Adept ePub.".format(os.path.basename(inpath)))
|
||||
elif len(bookkey) == 64:
|
||||
print("{0:s} is a secure Adobe PassHash (B&N) ePub.".format(os.path.basename(inpath)))
|
||||
else:
|
||||
print("{0:s} is not an Adobe-protected ePub!".format(os.path.basename(inpath)))
|
||||
return 1
|
||||
|
||||
if len(bookkey) != 64:
|
||||
# Normal or "hardened" Adobe ADEPT
|
||||
rsakey = RSA.importKey(userkey) # parses the ASN1 structure
|
||||
bookkey = base64.b64decode(bookkey)
|
||||
if int(keytype, 10) > 2:
|
||||
bookkey = removeHardening(rights, keytype, bookkey)
|
||||
try:
|
||||
bookkey = PKCS1_v1_5.new(rsakey).decrypt(bookkey, None) # automatically unpads
|
||||
except ValueError:
|
||||
bookkey = None
|
||||
|
||||
if bookkey is None:
|
||||
print("Could not decrypt {0:s}. Wrong key".format(os.path.basename(inpath)))
|
||||
return 2
|
||||
else:
|
||||
# Adobe PassHash / B&N
|
||||
key = base64.b64decode(userkey)[:16]
|
||||
bookkey = base64.b64decode(bookkey)
|
||||
bookkey = unpad(AES.new(key, AES.MODE_CBC, b'\x00'*16).decrypt(bookkey), 16) # PKCS#7
|
||||
|
||||
if len(bookkey) > 16:
|
||||
bookkey = bookkey[-16:]
|
||||
|
||||
encryption = inf.read('META-INF/encryption.xml')
|
||||
decryptor = Decryptor(bookkey, encryption)
|
||||
kwds = dict(compression=ZIP_DEFLATED, allowZip64=False)
|
||||
with closing(ZipFile(open(outpath, 'wb'), 'w', **kwds)) as outf:
|
||||
|
||||
for path in (["mimetype"] + namelist):
|
||||
data = inf.read(path)
|
||||
zi = ZipInfo(path)
|
||||
zi.compress_type=ZIP_DEFLATED
|
||||
|
||||
if path == "mimetype":
|
||||
zi.compress_type = ZIP_STORED
|
||||
|
||||
elif path == "META-INF/encryption.xml":
|
||||
# Check if there's still something in there
|
||||
if (decryptor.check_if_remaining()):
|
||||
data = decryptor.get_xml()
|
||||
print("Adding encryption.xml for the remaining embedded files.")
|
||||
# We removed DRM, but there's still stuff like obfuscated fonts.
|
||||
else:
|
||||
continue
|
||||
|
||||
|
||||
try:
|
||||
# get the file info, including time-stamp
|
||||
oldzi = inf.getinfo(path)
|
||||
# copy across useful fields
|
||||
zi.date_time = oldzi.date_time
|
||||
zi.comment = oldzi.comment
|
||||
zi.extra = oldzi.extra
|
||||
zi.internal_attr = oldzi.internal_attr
|
||||
# external attributes are dependent on the create system, so copy both.
|
||||
zi.external_attr = oldzi.external_attr
|
||||
|
||||
zi.volume = oldzi.volume
|
||||
zi.create_system = oldzi.create_system
|
||||
zi.create_version = oldzi.create_version
|
||||
|
||||
if any(ord(c) >= 128 for c in path) or any(ord(c) >= 128 for c in zi.comment):
|
||||
# If the file name or the comment contains any non-ASCII char, set the UTF8-flag
|
||||
zi.flag_bits |= 0x800
|
||||
except:
|
||||
pass
|
||||
|
||||
# Python 3 has a bug where the external_attr is reset to `0o600 << 16`
|
||||
# if it's NULL, so we need a workaround:
|
||||
if zi.external_attr == 0:
|
||||
zi = ZeroedZipInfo(zi)
|
||||
|
||||
|
||||
if path == "META-INF/encryption.xml":
|
||||
outf.writestr(zi, data)
|
||||
else:
|
||||
outf.writestr(zi, decryptor.decrypt(path, data))
|
||||
except:
|
||||
print("Could not decrypt {0:s} because of an exception:\n{1:s}".format(os.path.basename(inpath), traceback.format_exc()))
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
def cli_main():
|
||||
sys.stdout=SafeUnbuffered(sys.stdout)
|
||||
sys.stderr=SafeUnbuffered(sys.stderr)
|
||||
argv=unicode_argv("ineptepub.py")
|
||||
progname = os.path.basename(argv[0])
|
||||
if len(argv) != 4:
|
||||
print("usage: {0} <keyfile.der> <inbook.epub> <outbook.epub>".format(progname))
|
||||
return 1
|
||||
keypath, inpath, outpath = argv[1:]
|
||||
userkey = open(keypath,'rb').read()
|
||||
result = decryptBook(userkey, inpath, outpath)
|
||||
if result == 0:
|
||||
print("Successfully decrypted {0:s} as {1:s}".format(os.path.basename(inpath),os.path.basename(outpath)))
|
||||
return result
|
||||
|
||||
def gui_main():
|
||||
try:
|
||||
import tkinter
|
||||
import tkinter.constants
|
||||
import tkinter.filedialog
|
||||
import tkinter.messagebox
|
||||
import traceback
|
||||
except:
|
||||
return cli_main()
|
||||
|
||||
class DecryptionDialog(tkinter.Frame):
|
||||
def __init__(self, root):
|
||||
tkinter.Frame.__init__(self, root, border=5)
|
||||
self.status = tkinter.Label(self, text="Select files for decryption")
|
||||
self.status.pack(fill=tkinter.constants.X, expand=1)
|
||||
body = tkinter.Frame(self)
|
||||
body.pack(fill=tkinter.constants.X, expand=1)
|
||||
sticky = tkinter.constants.E + tkinter.constants.W
|
||||
body.grid_columnconfigure(1, weight=2)
|
||||
tkinter.Label(body, text="Key file").grid(row=0)
|
||||
self.keypath = tkinter.Entry(body, width=30)
|
||||
self.keypath.grid(row=0, column=1, sticky=sticky)
|
||||
if os.path.exists("adeptkey.der"):
|
||||
self.keypath.insert(0, "adeptkey.der")
|
||||
button = tkinter.Button(body, text="...", command=self.get_keypath)
|
||||
button.grid(row=0, column=2)
|
||||
tkinter.Label(body, text="Input file").grid(row=1)
|
||||
self.inpath = tkinter.Entry(body, width=30)
|
||||
self.inpath.grid(row=1, column=1, sticky=sticky)
|
||||
button = tkinter.Button(body, text="...", command=self.get_inpath)
|
||||
button.grid(row=1, column=2)
|
||||
tkinter.Label(body, text="Output file").grid(row=2)
|
||||
self.outpath = tkinter.Entry(body, width=30)
|
||||
self.outpath.grid(row=2, column=1, sticky=sticky)
|
||||
button = tkinter.Button(body, text="...", command=self.get_outpath)
|
||||
button.grid(row=2, column=2)
|
||||
buttons = tkinter.Frame(self)
|
||||
buttons.pack()
|
||||
botton = tkinter.Button(
|
||||
buttons, text="Decrypt", width=10, command=self.decrypt)
|
||||
botton.pack(side=tkinter.constants.LEFT)
|
||||
tkinter.Frame(buttons, width=10).pack(side=tkinter.constants.LEFT)
|
||||
button = tkinter.Button(
|
||||
buttons, text="Quit", width=10, command=self.quit)
|
||||
button.pack(side=tkinter.constants.RIGHT)
|
||||
|
||||
def get_keypath(self):
|
||||
keypath = tkinter.filedialog.askopenfilename(
|
||||
parent=None, title="Select Adobe Adept \'.der\' key file",
|
||||
defaultextension=".der",
|
||||
filetypes=[('Adobe Adept DER-encoded files', '.der'),
|
||||
('All Files', '.*')])
|
||||
if keypath:
|
||||
keypath = os.path.normpath(keypath)
|
||||
self.keypath.delete(0, tkinter.constants.END)
|
||||
self.keypath.insert(0, keypath)
|
||||
return
|
||||
|
||||
def get_inpath(self):
|
||||
inpath = tkinter.filedialog.askopenfilename(
|
||||
parent=None, title="Select ADEPT-encrypted ePub file to decrypt",
|
||||
defaultextension=".epub", filetypes=[('ePub files', '.epub')])
|
||||
if inpath:
|
||||
inpath = os.path.normpath(inpath)
|
||||
self.inpath.delete(0, tkinter.constants.END)
|
||||
self.inpath.insert(0, inpath)
|
||||
return
|
||||
|
||||
def get_outpath(self):
|
||||
outpath = tkinter.filedialog.asksaveasfilename(
|
||||
parent=None, title="Select unencrypted ePub file to produce",
|
||||
defaultextension=".epub", filetypes=[('ePub files', '.epub')])
|
||||
if outpath:
|
||||
outpath = os.path.normpath(outpath)
|
||||
self.outpath.delete(0, tkinter.constants.END)
|
||||
self.outpath.insert(0, outpath)
|
||||
return
|
||||
|
||||
def decrypt(self):
|
||||
keypath = self.keypath.get()
|
||||
inpath = self.inpath.get()
|
||||
outpath = self.outpath.get()
|
||||
if not keypath or not os.path.exists(keypath):
|
||||
self.status['text'] = "Specified key file does not exist"
|
||||
return
|
||||
if not inpath or not os.path.exists(inpath):
|
||||
self.status['text'] = "Specified input file does not exist"
|
||||
return
|
||||
if not outpath:
|
||||
self.status['text'] = "Output file not specified"
|
||||
return
|
||||
if inpath == outpath:
|
||||
self.status['text'] = "Must have different input and output files"
|
||||
return
|
||||
userkey = open(keypath,'rb').read()
|
||||
self.status['text'] = "Decrypting..."
|
||||
try:
|
||||
decrypt_status = decryptBook(userkey, inpath, outpath)
|
||||
except Exception as e:
|
||||
self.status['text'] = "Error: {0}".format(e.args[0])
|
||||
return
|
||||
if decrypt_status == 0:
|
||||
self.status['text'] = "File successfully decrypted"
|
||||
else:
|
||||
self.status['text'] = "There was an error decrypting the file."
|
||||
|
||||
root = tkinter.Tk()
|
||||
root.title("Adobe Adept ePub Decrypter v.{0}".format(__version__))
|
||||
root.resizable(True, False)
|
||||
root.minsize(300, 0)
|
||||
DecryptionDialog(root).pack(fill=tkinter.constants.X, expand=1)
|
||||
root.mainloop()
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
if len(sys.argv) > 1:
|
||||
sys.exit(cli_main())
|
||||
sys.exit(gui_main())
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,92 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Mobipocket PID calculator v0.4 for Amazon Kindle.
|
||||
# Copyright (c) 2007, 2009 Igor Skochinsky <skochinsky@mail.ru>
|
||||
# History:
|
||||
# 0.1 Initial release
|
||||
# 0.2 Added support for generating PID for iPhone (thanks to mbp)
|
||||
# 0.3 changed to autoflush stdout, fixed return code usage
|
||||
# 0.3 updated for unicode
|
||||
# 0.4 Added support for serial numbers starting with '9', fixed unicode bugs.
|
||||
# 0.5 moved unicode_argv call inside main for Windows DeDRM compatibility
|
||||
# 1.0 Python 3 for calibre 5.0
|
||||
|
||||
|
||||
import sys
|
||||
import binascii
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
from .utilities import SafeUnbuffered
|
||||
from .argv_utils import unicode_argv
|
||||
|
||||
letters = b'ABCDEFGHIJKLMNPQRSTUVWXYZ123456789'
|
||||
|
||||
def crc32(s):
|
||||
return (~binascii.crc32(s,-1))&0xFFFFFFFF
|
||||
|
||||
def checksumPid(s):
|
||||
crc = crc32(s)
|
||||
crc = crc ^ (crc >> 16)
|
||||
res = s
|
||||
l = len(letters)
|
||||
for i in (0,1):
|
||||
b = crc & 0xff
|
||||
pos = (b // l) ^ (b % l)
|
||||
res += bytes(bytearray([letters[pos%l]]))
|
||||
crc >>= 8
|
||||
|
||||
return res
|
||||
|
||||
def pidFromSerial(s, l):
|
||||
crc = crc32(s)
|
||||
|
||||
arr1 = [0]*l
|
||||
for i in range(len(s)):
|
||||
if sys.version_info[0] == 2:
|
||||
arr1[i%l] ^= ord(s[i])
|
||||
else:
|
||||
arr1[i%l] ^= s[i]
|
||||
|
||||
crc_bytes = [crc >> 24 & 0xff, crc >> 16 & 0xff, crc >> 8 & 0xff, crc & 0xff]
|
||||
for i in range(l):
|
||||
arr1[i] ^= crc_bytes[i&3]
|
||||
|
||||
pid = b""
|
||||
for i in range(l):
|
||||
b = arr1[i] & 0xff
|
||||
pid+=bytes(bytearray([letters[(b >> 7) + ((b >> 5 & 3) ^ (b & 0x1f))]]))
|
||||
|
||||
return pid
|
||||
|
||||
def cli_main():
|
||||
print("Mobipocket PID calculator for Amazon Kindle. Copyright © 2007, 2009 Igor Skochinsky")
|
||||
argv=unicode_argv("kindlepid.py")
|
||||
if len(argv)==2:
|
||||
serial = argv[1]
|
||||
else:
|
||||
print("Usage: kindlepid.py <Kindle Serial Number>/<iPhone/iPod Touch UDID>")
|
||||
return 1
|
||||
if len(serial)==16:
|
||||
if serial.startswith("B") or serial.startswith("9"):
|
||||
print("Kindle serial number detected")
|
||||
else:
|
||||
print("Warning: unrecognized serial number. Please recheck input.")
|
||||
return 1
|
||||
pid = pidFromSerial(serial.encode("utf-8"),7)+'*'
|
||||
print("Mobipocket PID for Kindle serial#{0} is {1}".format(serial,checksumPid(pid)))
|
||||
return 0
|
||||
elif len(serial)==40:
|
||||
print("iPhone serial number (UDID) detected")
|
||||
pid = pidFromSerial(serial.encode("utf-8"),8)
|
||||
print("Mobipocket PID for iPhone serial#{0} is {1}".format(serial,checksumPid(pid)))
|
||||
return 0
|
||||
print("Warning: unrecognized serial number. Please recheck input.")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.stdout=SafeUnbuffered(sys.stdout)
|
||||
sys.stderr=SafeUnbuffered(sys.stderr)
|
||||
sys.exit(cli_main())
|
||||
|
|
@ -1,70 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# lcpdedrm.py
|
||||
# Copyright © 2021-2022 NoDRM
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
|
||||
# Revision history:
|
||||
# 1 - Initial release
|
||||
# 2 - LCP DRM code removed due to a DMCA takedown.
|
||||
|
||||
"""
|
||||
This file used to contain code to remove the Readium LCP DRM
|
||||
from eBooks. Unfortunately, Readium has issued a DMCA takedown
|
||||
request, so I was forced to remove that code:
|
||||
|
||||
https://github.com/github/dmca/blob/master/2022/01/2022-01-04-readium.md
|
||||
|
||||
This file now just returns an error message when asked to remove LCP DRM.
|
||||
For more information, see this issue:
|
||||
https://github.com/noDRM/DeDRM_tools/issues/18
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = "2"
|
||||
|
||||
import json
|
||||
from zipfile import ZipFile
|
||||
from contextlib import closing
|
||||
|
||||
|
||||
class LCPError(Exception):
|
||||
pass
|
||||
|
||||
# Check file to see if this is an LCP-protected file
|
||||
def isLCPbook(inpath):
|
||||
try:
|
||||
with closing(ZipFile(open(inpath, 'rb'))) as lcpbook:
|
||||
if ("META-INF/license.lcpl" not in lcpbook.namelist() or
|
||||
"META-INF/encryption.xml" not in lcpbook.namelist() or
|
||||
b"EncryptedContentKey" not in lcpbook.read("META-INF/encryption.xml")):
|
||||
return False
|
||||
|
||||
license = json.loads(lcpbook.read('META-INF/license.lcpl'))
|
||||
|
||||
if "id" in license and "encryption" in license and "profile" in license["encryption"]:
|
||||
return True
|
||||
|
||||
except:
|
||||
return False
|
||||
|
||||
return False
|
||||
|
||||
|
||||
# Takes a file and a list of passphrases
|
||||
def decryptLCPbook(inpath, passphrases, parent_object):
|
||||
|
||||
if not isLCPbook(inpath):
|
||||
raise LCPError("This is not an LCP-encrypted book")
|
||||
|
||||
print("LCP: LCP DRM removal no longer supported due to a DMCA takedown request.")
|
||||
print("LCP: The takedown request can be found here: ")
|
||||
print("LCP: https://github.com/github/dmca/blob/master/2022/01/2022-01-04-readium.md ")
|
||||
print("LCP: More information can be found in the Github repository: ")
|
||||
print("LCP: https://github.com/noDRM/DeDRM_tools/issues/18 ")
|
||||
|
||||
raise LCPError("LCP DRM removal no longer supported")
|
||||
|
|
@ -1,106 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
|
||||
# Standard Python modules.
|
||||
import os, sys
|
||||
import traceback
|
||||
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
|
||||
try:
|
||||
from calibre.utils.config import JSONConfig
|
||||
except:
|
||||
from standalone.jsonconfig import JSONConfig
|
||||
|
||||
from __init__ import PLUGIN_NAME
|
||||
|
||||
class DeDRM_Prefs():
|
||||
def __init__(self, json_path=None):
|
||||
if json_path is None:
|
||||
JSON_PATH = os.path.join("plugins", PLUGIN_NAME.strip().lower().replace(' ', '_') + '.json')
|
||||
else:
|
||||
JSON_PATH = json_path
|
||||
|
||||
self.dedrmprefs = JSONConfig(JSON_PATH)
|
||||
|
||||
self.dedrmprefs.defaults['configured'] = False
|
||||
self.dedrmprefs.defaults['deobfuscate_fonts'] = True
|
||||
self.dedrmprefs.defaults['remove_watermarks'] = False
|
||||
self.dedrmprefs.defaults['bandnkeys'] = {}
|
||||
self.dedrmprefs.defaults['adeptkeys'] = {}
|
||||
self.dedrmprefs.defaults['ereaderkeys'] = {}
|
||||
self.dedrmprefs.defaults['kindlekeys'] = {}
|
||||
self.dedrmprefs.defaults['androidkeys'] = {}
|
||||
self.dedrmprefs.defaults['pids'] = []
|
||||
self.dedrmprefs.defaults['serials'] = []
|
||||
self.dedrmprefs.defaults['lcp_passphrases'] = []
|
||||
self.dedrmprefs.defaults['adobe_pdf_passphrases'] = []
|
||||
self.dedrmprefs.defaults['adobewineprefix'] = ""
|
||||
self.dedrmprefs.defaults['kindlewineprefix'] = ""
|
||||
|
||||
# initialise
|
||||
# we must actually set the prefs that are dictionaries and lists
|
||||
# to empty dictionaries and lists, otherwise we are unable to add to them
|
||||
# as then it just adds to the (memory only) dedrmprefs.defaults versions!
|
||||
if self.dedrmprefs['bandnkeys'] == {}:
|
||||
self.dedrmprefs['bandnkeys'] = {}
|
||||
if self.dedrmprefs['adeptkeys'] == {}:
|
||||
self.dedrmprefs['adeptkeys'] = {}
|
||||
if self.dedrmprefs['ereaderkeys'] == {}:
|
||||
self.dedrmprefs['ereaderkeys'] = {}
|
||||
if self.dedrmprefs['kindlekeys'] == {}:
|
||||
self.dedrmprefs['kindlekeys'] = {}
|
||||
if self.dedrmprefs['androidkeys'] == {}:
|
||||
self.dedrmprefs['androidkeys'] = {}
|
||||
if self.dedrmprefs['pids'] == []:
|
||||
self.dedrmprefs['pids'] = []
|
||||
if self.dedrmprefs['serials'] == []:
|
||||
self.dedrmprefs['serials'] = []
|
||||
if self.dedrmprefs['lcp_passphrases'] == []:
|
||||
self.dedrmprefs['lcp_passphrases'] = []
|
||||
if self.dedrmprefs['adobe_pdf_passphrases'] == []:
|
||||
self.dedrmprefs['adobe_pdf_passphrases'] = []
|
||||
|
||||
def __getitem__(self,kind = None):
|
||||
if kind is not None:
|
||||
return self.dedrmprefs[kind]
|
||||
return self.dedrmprefs
|
||||
|
||||
def set(self, kind, value):
|
||||
self.dedrmprefs[kind] = value
|
||||
|
||||
def writeprefs(self,value = True):
|
||||
self.dedrmprefs['configured'] = value
|
||||
|
||||
def addnamedvaluetoprefs(self, prefkind, keyname, keyvalue):
|
||||
try:
|
||||
if keyvalue not in self.dedrmprefs[prefkind].values():
|
||||
# ensure that the keyname is unique
|
||||
# by adding a number (starting with 2) to the name if it is not
|
||||
namecount = 1
|
||||
newname = keyname
|
||||
while newname in self.dedrmprefs[prefkind]:
|
||||
namecount += 1
|
||||
newname = "{0:s}_{1:d}".format(keyname,namecount)
|
||||
# add to the preferences
|
||||
self.dedrmprefs[prefkind][newname] = keyvalue
|
||||
return (True, newname)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
pass
|
||||
return (False, keyname)
|
||||
|
||||
def addvaluetoprefs(self, prefkind, prefsvalue):
|
||||
# ensure the keyvalue isn't already in the preferences
|
||||
try:
|
||||
if prefsvalue not in self.dedrmprefs[prefkind]:
|
||||
self.dedrmprefs[prefkind].append(prefsvalue)
|
||||
return True
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
|
@ -1,290 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# CLI interface for the DeDRM plugin (useable without Calibre, too)
|
||||
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
"""
|
||||
|
||||
NOTE: This code is not functional (yet). I started working on it a while ago
|
||||
to make a standalone version of the plugins that could work without Calibre,
|
||||
too, but for now there's only a rough code structure and no working code yet.
|
||||
|
||||
Currently, to use these plugins, you will need to use Calibre. Hopwfully that'll
|
||||
change in the future.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
OPT_SHORT_TO_LONG = [
|
||||
["c", "config"],
|
||||
["e", "extract"],
|
||||
["f", "force"],
|
||||
["h", "help"],
|
||||
["i", "import"],
|
||||
["o", "output"],
|
||||
["p", "password"],
|
||||
["q", "quiet"],
|
||||
["t", "test"],
|
||||
["u", "username"],
|
||||
["v", "verbose"],
|
||||
]
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
import os, sys
|
||||
|
||||
|
||||
global _additional_data
|
||||
global _additional_params
|
||||
global _function
|
||||
_additional_data = []
|
||||
_additional_params = []
|
||||
_function = None
|
||||
|
||||
global config_file_path
|
||||
config_file_path = "dedrm.json"
|
||||
|
||||
def print_fname(f, info):
|
||||
print(" " + f.ljust(15) + " " + info)
|
||||
|
||||
def print_opt(short, long, info):
|
||||
if short is None:
|
||||
short = " "
|
||||
else:
|
||||
short = " -" + short
|
||||
|
||||
if long is None:
|
||||
long = " "
|
||||
else:
|
||||
long = "--" + long.ljust(16)
|
||||
|
||||
print(short + " " + long + " " + info, file=sys.stderr)
|
||||
|
||||
def print_std_usage(name, param_string):
|
||||
print("Usage: ", file=sys.stderr)
|
||||
if "calibre" in sys.modules:
|
||||
print(" calibre-debug -r \"DeDRM\" -- "+name+" " + param_string, file=sys.stderr)
|
||||
else:
|
||||
print(" python3 DeDRM_plugin.zip "+name+" "+param_string, file=sys.stderr)
|
||||
|
||||
def print_err_header():
|
||||
from __init__ import PLUGIN_NAME, PLUGIN_VERSION # type: ignore
|
||||
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - DRM removal plugin by noDRM")
|
||||
print()
|
||||
|
||||
def print_help():
|
||||
from __version import PLUGIN_NAME, PLUGIN_VERSION
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - DRM removal plugin by noDRM")
|
||||
print("Based on DeDRM Calibre plugin by Apprentice Harper, Apprentice Alf and others.")
|
||||
print("See https://github.com/noDRM/DeDRM_tools for more information.")
|
||||
print()
|
||||
if "calibre" in sys.modules:
|
||||
print("This plugin can be run through Calibre - like you are doing right now - ")
|
||||
print("but it can also be executed with a standalone Python interpreter.")
|
||||
else:
|
||||
print("This plugin can either be imported into Calibre, or be executed directly")
|
||||
print("through Python like you are doing right now.")
|
||||
print()
|
||||
print("Available functions:")
|
||||
print_fname("passhash", "Manage Adobe PassHashes")
|
||||
print_fname("remove_drm", "Remove DRM from one or multiple books")
|
||||
print()
|
||||
|
||||
# TODO: All parameters that are global should be listed here.
|
||||
|
||||
def print_credits():
|
||||
from __version import PLUGIN_NAME, PLUGIN_VERSION
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - Calibre DRM removal plugin by noDRM")
|
||||
print("Based on DeDRM Calibre plugin by Apprentice Harper, Apprentice Alf and others.")
|
||||
print("See https://github.com/noDRM/DeDRM_tools for more information.")
|
||||
print()
|
||||
print("Credits:")
|
||||
print(" - noDRM for the current release of the DeDRM plugin")
|
||||
print(" - Apprentice Alf and Apprentice Harper for the previous versions of the DeDRM plugin")
|
||||
print(" - The Dark Reverser for the Mobipocket and eReader script")
|
||||
print(" - i ♥ cabbages for the Adobe Digital Editions scripts")
|
||||
print(" - Skindle aka Bart Simpson for the Amazon Kindle for PC script")
|
||||
print(" - CMBDTC for Amazon Topaz DRM removal script")
|
||||
print(" - some_updates, clarknova and Bart Simpson for Amazon Topaz conversion scripts")
|
||||
print(" - DiapDealer for the first calibre plugin versions of the tools")
|
||||
print(" - some_updates, DiapDealer, Apprentice Alf and mdlnx for Amazon Kindle/Mobipocket tools")
|
||||
print(" - some_updates for the DeDRM all-in-one Python tool")
|
||||
print(" - Apprentice Alf for the DeDRM all-in-one AppleScript tool")
|
||||
|
||||
|
||||
def handle_single_argument(arg, next):
|
||||
used_up = 0
|
||||
global _additional_params
|
||||
global config_file_path
|
||||
|
||||
if arg in ["--username", "--password", "--output", "--outputdir"]:
|
||||
used_up = 1
|
||||
_additional_params.append(arg)
|
||||
if next is None or len(next) == 0:
|
||||
print_err_header()
|
||||
print("Missing parameter for argument " + arg, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
else:
|
||||
_additional_params.append(next[0])
|
||||
|
||||
elif arg == "--config":
|
||||
if next is None or len(next) == 0:
|
||||
print_err_header()
|
||||
print("Missing parameter for argument " + arg, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
config_file_path = next[0]
|
||||
used_up = 1
|
||||
|
||||
elif arg in ["--help", "--credits", "--verbose", "--quiet", "--extract", "--import", "--overwrite", "--force"]:
|
||||
_additional_params.append(arg)
|
||||
|
||||
|
||||
else:
|
||||
print_err_header()
|
||||
print("Unknown argument: " + arg, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
# Used up 0 additional arguments
|
||||
return used_up
|
||||
|
||||
|
||||
|
||||
def handle_data(data):
|
||||
global _function
|
||||
global _additional_data
|
||||
|
||||
if _function is None:
|
||||
_function = str(data)
|
||||
else:
|
||||
_additional_data.append(str(data))
|
||||
|
||||
def execute_action(action, filenames, params):
|
||||
print("Executing '{0}' on file(s) {1} with parameters {2}".format(action, str(filenames), str(params)), file=sys.stderr)
|
||||
|
||||
if action == "help":
|
||||
print_help()
|
||||
sys.exit(0)
|
||||
|
||||
elif action == "passhash":
|
||||
from standalone.passhash import perform_action
|
||||
perform_action(params, filenames)
|
||||
|
||||
elif action == "remove_drm":
|
||||
if not os.path.isfile(os.path.abspath(config_file_path)):
|
||||
print("Config file missing ...")
|
||||
|
||||
from standalone.remove_drm import perform_action
|
||||
perform_action(params, filenames)
|
||||
|
||||
elif action == "config":
|
||||
import prefs
|
||||
config = prefs.DeDRM_Prefs(os.path.abspath(config_file_path))
|
||||
print(config["adeptkeys"])
|
||||
|
||||
else:
|
||||
print("Command '"+action+"' is unknown.", file=sys.stderr)
|
||||
|
||||
|
||||
def main(argv):
|
||||
arguments = argv
|
||||
skip_opts = False
|
||||
|
||||
# First element is always the ZIP name, remove that.
|
||||
if not arguments[0].lower().endswith(".zip") and not "calibre" in sys.modules:
|
||||
print("Warning: File name does not end in .zip ...")
|
||||
print(arguments)
|
||||
arguments.pop(0)
|
||||
|
||||
while len(arguments) > 0:
|
||||
arg = arguments.pop(0)
|
||||
|
||||
if arg == "--":
|
||||
skip_opts = True
|
||||
continue
|
||||
|
||||
if not skip_opts:
|
||||
if arg.startswith("--"):
|
||||
# Give the current arg, plus all remaining ones.
|
||||
# Return the number of additional args we used.
|
||||
used = handle_single_argument(arg, arguments)
|
||||
for _ in range(used):
|
||||
# Function returns number of additional arguments that were
|
||||
# "used up" by that argument.
|
||||
# Remove that amount of arguments from the list.
|
||||
try:
|
||||
arguments.pop(0)
|
||||
except:
|
||||
pass
|
||||
continue
|
||||
elif arg.startswith("-"):
|
||||
single_args = list(arg[1:])
|
||||
# single_args is now a list of single chars, for when you call the program like "ls -alR"
|
||||
# with multiple single-letter options combined.
|
||||
while len(single_args) > 0:
|
||||
c = single_args.pop(0)
|
||||
|
||||
# See if we have a long name for that option.
|
||||
for wrapper in OPT_SHORT_TO_LONG:
|
||||
if wrapper[0] == c:
|
||||
c = "--" + wrapper[1]
|
||||
break
|
||||
else:
|
||||
c = "-" + c
|
||||
# c is now the long term (unless there is no long version, then it's the short version).
|
||||
|
||||
if len(single_args) > 0:
|
||||
# If we have more short arguments, the argument for this one must be None.
|
||||
handle_single_argument(c, None)
|
||||
used = 0
|
||||
else:
|
||||
# If not, then there might be parameters for this short argument.
|
||||
used = handle_single_argument(c, arguments)
|
||||
|
||||
for _ in range(used):
|
||||
# Function returns number of additional arguments that were
|
||||
# "used up" by that argument.
|
||||
# Remove that amount of arguments from the list.
|
||||
try:
|
||||
arguments.pop(0)
|
||||
except:
|
||||
pass
|
||||
|
||||
continue
|
||||
|
||||
handle_data(arg)
|
||||
|
||||
|
||||
if _function is None and "--credits" in _additional_params:
|
||||
print_credits()
|
||||
sys.exit(0)
|
||||
|
||||
if _function is None and "--help" in _additional_params:
|
||||
print_help()
|
||||
sys.exit(0)
|
||||
|
||||
if _function is None:
|
||||
print_help()
|
||||
sys.exit(1)
|
||||
|
||||
# Okay, now actually begin doing stuff.
|
||||
# This function gets told what to do and gets additional data (filenames).
|
||||
# It also receives additional parameters.
|
||||
# The rest of the code will be in different Python files.
|
||||
execute_action(_function.lower(), _additional_data, _additional_params)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# NOTE: This MUST not do anything else other than calling main()
|
||||
# All the code must be in main(), not in here.
|
||||
import sys
|
||||
main(sys.argv)
|
||||
|
|
@ -1,151 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# CLI interface for the DeDRM plugin (useable without Calibre, too)
|
||||
# Config implementation
|
||||
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
# Taken from Calibre code - Copyright © 2008, Kovid Goyal kovid@kovidgoyal.net, GPLv3
|
||||
|
||||
"""
|
||||
|
||||
NOTE: This code is not functional (yet). I started working on it a while ago
|
||||
to make a standalone version of the plugins that could work without Calibre,
|
||||
too, but for now there's only a rough code structure and no working code yet.
|
||||
|
||||
Currently, to use these plugins, you will need to use Calibre. Hopwfully that'll
|
||||
change in the future.
|
||||
|
||||
"""
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
import sys, os, codecs, json
|
||||
|
||||
config_dir = "/"
|
||||
CONFIG_DIR_MODE = 0o700
|
||||
iswindows = sys.platform.startswith('win')
|
||||
|
||||
|
||||
filesystem_encoding = sys.getfilesystemencoding()
|
||||
if filesystem_encoding is None:
|
||||
filesystem_encoding = 'utf-8'
|
||||
else:
|
||||
try:
|
||||
if codecs.lookup(filesystem_encoding).name == 'ascii':
|
||||
filesystem_encoding = 'utf-8'
|
||||
# On linux, unicode arguments to os file functions are coerced to an ascii
|
||||
# bytestring if sys.getfilesystemencoding() == 'ascii', which is
|
||||
# just plain dumb. This is fixed by the icu.py module which, when
|
||||
# imported changes ascii to utf-8
|
||||
except Exception:
|
||||
filesystem_encoding = 'utf-8'
|
||||
|
||||
|
||||
class JSONConfig(dict):
|
||||
|
||||
EXTENSION = '.json'
|
||||
|
||||
|
||||
def __init__(self, rel_path_to_cf_file, base_path=config_dir):
|
||||
dict.__init__(self)
|
||||
self.no_commit = False
|
||||
self.defaults = {}
|
||||
self.file_path = os.path.join(base_path,
|
||||
*(rel_path_to_cf_file.split('/')))
|
||||
self.file_path = os.path.abspath(self.file_path)
|
||||
if not self.file_path.endswith(self.EXTENSION):
|
||||
self.file_path += self.EXTENSION
|
||||
|
||||
self.refresh()
|
||||
|
||||
def mtime(self):
|
||||
try:
|
||||
return os.path.getmtime(self.file_path)
|
||||
except OSError:
|
||||
return 0
|
||||
|
||||
def touch(self):
|
||||
try:
|
||||
os.utime(self.file_path, None)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def decouple(self, prefix):
|
||||
self.file_path = os.path.join(os.path.dirname(self.file_path), prefix + os.path.basename(self.file_path))
|
||||
self.refresh()
|
||||
|
||||
def refresh(self, clear_current=True):
|
||||
d = {}
|
||||
if os.path.exists(self.file_path):
|
||||
with open(self.file_path, "rb") as f:
|
||||
raw = f.read()
|
||||
try:
|
||||
d = self.raw_to_object(raw) if raw.strip() else {}
|
||||
except SystemError:
|
||||
pass
|
||||
except:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
d = {}
|
||||
if clear_current:
|
||||
self.clear()
|
||||
self.update(d)
|
||||
|
||||
def has_key(self, key):
|
||||
return dict.__contains__(self, key)
|
||||
|
||||
def set(self, key, val):
|
||||
self.__setitem__(key, val)
|
||||
|
||||
def __delitem__(self, key):
|
||||
try:
|
||||
dict.__delitem__(self, key)
|
||||
except KeyError:
|
||||
pass # ignore missing keys
|
||||
else:
|
||||
self.commit()
|
||||
|
||||
def commit(self):
|
||||
if self.no_commit:
|
||||
return
|
||||
if hasattr(self, 'file_path') and self.file_path:
|
||||
dpath = os.path.dirname(self.file_path)
|
||||
if not os.path.exists(dpath):
|
||||
os.makedirs(dpath, mode=CONFIG_DIR_MODE)
|
||||
with open(self.file_path, "w") as f:
|
||||
raw = self.to_raw()
|
||||
f.seek(0)
|
||||
f.truncate()
|
||||
f.write(raw)
|
||||
|
||||
def __enter__(self):
|
||||
self.no_commit = True
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.no_commit = False
|
||||
self.commit()
|
||||
|
||||
def raw_to_object(self, raw):
|
||||
return json.loads(raw)
|
||||
|
||||
def to_raw(self):
|
||||
return json.dumps(self, ensure_ascii=False)
|
||||
|
||||
def __getitem__(self, key):
|
||||
try:
|
||||
return dict.__getitem__(self, key)
|
||||
except KeyError:
|
||||
return self.defaults[key]
|
||||
|
||||
def get(self, key, default=None):
|
||||
try:
|
||||
return dict.__getitem__(self, key)
|
||||
except KeyError:
|
||||
return self.defaults.get(key, default)
|
||||
|
||||
def __setitem__(self, key, val):
|
||||
dict.__setitem__(self, key, val)
|
||||
self.commit()
|
||||
|
|
@ -1,133 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# CLI interface for the DeDRM plugin (useable without Calibre, too)
|
||||
# Adobe PassHash implementation
|
||||
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
"""
|
||||
|
||||
NOTE: This code is not functional (yet). I started working on it a while ago
|
||||
to make a standalone version of the plugins that could work without Calibre,
|
||||
too, but for now there's only a rough code structure and no working code yet.
|
||||
|
||||
Currently, to use these plugins, you will need to use Calibre. Hopwfully that'll
|
||||
change in the future.
|
||||
|
||||
"""
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
import os, sys
|
||||
|
||||
from standalone.__init__ import print_opt, print_std_usage
|
||||
|
||||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
||||
def print_passhash_help():
|
||||
from __version import PLUGIN_NAME, PLUGIN_VERSION
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - Calibre DRM removal plugin by noDRM")
|
||||
print()
|
||||
print("passhash: Manage Adobe PassHashes")
|
||||
print()
|
||||
print_std_usage("passhash", "[ -u username -p password | -b base64str ] [ -i ] ")
|
||||
|
||||
print()
|
||||
print("Options: ")
|
||||
print_opt("u", "username", "Generate a PassHash with the given username")
|
||||
print_opt("p", "password", "Generate a PassHash with the given password")
|
||||
print_opt("e", "extract", "Display PassHashes found on this machine")
|
||||
print_opt("i", "import", "Import hashes into the JSON config file")
|
||||
|
||||
def perform_action(params, files):
|
||||
user = None
|
||||
pwd = None
|
||||
|
||||
if len(params) == 0:
|
||||
print_passhash_help()
|
||||
return 0
|
||||
|
||||
extract = False
|
||||
import_to_json = True
|
||||
|
||||
while len(params) > 0:
|
||||
p = params.pop(0)
|
||||
if p == "--username":
|
||||
user = params.pop(0)
|
||||
elif p == "--password":
|
||||
pwd = params.pop(0)
|
||||
elif p == "--extract":
|
||||
extract = True
|
||||
elif p == "--help":
|
||||
print_passhash_help()
|
||||
return 0
|
||||
elif p == "--import":
|
||||
import_to_json = True
|
||||
|
||||
if not extract and not import_to_json:
|
||||
if user is None:
|
||||
print("Missing parameter: --username", file=sys.stderr)
|
||||
if pwd is None:
|
||||
print("Missing parameter: --password", file=sys.stderr)
|
||||
if user is None or pwd is None:
|
||||
return 1
|
||||
|
||||
if user is None and pwd is not None:
|
||||
print("Parameter --password also requires --username", file=sys.stderr)
|
||||
return 1
|
||||
if user is not None and pwd is None:
|
||||
print("Parameter --username also requires --password", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if user is not None and pwd is not None:
|
||||
from ignoblekeyGenPassHash import generate_key
|
||||
key = generate_key(user, pwd)
|
||||
if import_to_json:
|
||||
# TODO: Import the key to the JSON
|
||||
pass
|
||||
|
||||
print(key.decode("utf-8"))
|
||||
|
||||
if extract or import_to_json:
|
||||
if not iswindows and not isosx:
|
||||
print("Extracting PassHash keys not supported on Linux.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
keys = []
|
||||
|
||||
from ignoblekeyNookStudy import nookkeys
|
||||
keys.extend(nookkeys())
|
||||
|
||||
if iswindows:
|
||||
from ignoblekeyWindowsStore import dump_keys
|
||||
keys.extend(dump_keys())
|
||||
|
||||
from adobekey_get_passhash import passhash_keys
|
||||
ade_keys, ade_names = passhash_keys()
|
||||
keys.extend(ade_keys)
|
||||
|
||||
# Trim duplicates
|
||||
newkeys = []
|
||||
for k in keys:
|
||||
if not k in newkeys:
|
||||
newkeys.append(k)
|
||||
|
||||
# Print all found keys
|
||||
for k in newkeys:
|
||||
if import_to_json:
|
||||
# TODO: Add keys to json
|
||||
pass
|
||||
|
||||
if extract:
|
||||
print(k)
|
||||
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("This code is not intended to be executed directly!", file=sys.stderr)
|
||||
|
|
@ -1,220 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# CLI interface for the DeDRM plugin (useable without Calibre, too)
|
||||
# DRM removal
|
||||
|
||||
from __future__ import absolute_import, print_function
|
||||
|
||||
# Copyright © 2021 NoDRM
|
||||
|
||||
"""
|
||||
|
||||
NOTE: This code is not functional (yet). I started working on it a while ago
|
||||
to make a standalone version of the plugins that could work without Calibre,
|
||||
too, but for now there's only a rough code structure and no working code yet.
|
||||
|
||||
Currently, to use these plugins, you will need to use Calibre. Hopwfully that'll
|
||||
change in the future.
|
||||
|
||||
"""
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
import os, sys
|
||||
|
||||
from zipfile import ZipInfo, ZipFile, ZIP_STORED, ZIP_DEFLATED
|
||||
from contextlib import closing
|
||||
|
||||
from standalone.__init__ import print_opt, print_std_usage
|
||||
|
||||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
||||
def print_removedrm_help():
|
||||
from __init__ import PLUGIN_NAME, PLUGIN_VERSION
|
||||
print(PLUGIN_NAME + " v" + PLUGIN_VERSION + " - Calibre DRM removal plugin by noDRM")
|
||||
print()
|
||||
print("remove_drm: Remove DRM from one or multiple files")
|
||||
print()
|
||||
print_std_usage("remove_drm", "<filename> ... [ -o <filename> ] [ -f ]")
|
||||
|
||||
print()
|
||||
print("Options: ")
|
||||
print_opt(None, "outputdir", "Folder to export the file(s) to")
|
||||
print_opt("o", "output", "File name to export the file to")
|
||||
print_opt("f", "force", "Overwrite output file if it already exists")
|
||||
print_opt(None, "overwrite", "Replace DRMed file with DRM-free file (implies --force)")
|
||||
|
||||
|
||||
def determine_file_type(file):
|
||||
# Returns a file type:
|
||||
# "PDF", "PDB", "MOBI", "TPZ", "LCP", "ADEPT", "ADEPT-PassHash", "KFX-ZIP", "ZIP" or None
|
||||
|
||||
f = open(file, "rb")
|
||||
fdata = f.read(100)
|
||||
f.close()
|
||||
|
||||
if fdata.startswith(b"PK\x03\x04"):
|
||||
pass
|
||||
# Either LCP, Adobe, or Amazon
|
||||
elif fdata.startswith(b"%PDF"):
|
||||
return "PDF"
|
||||
elif fdata[0x3c:0x3c+8] == b"PNRdPPrs" or fdata[0x3c:0x3c+8] == b"PDctPPrs":
|
||||
return "PDB"
|
||||
elif fdata[0x3c:0x3c+8] == b"BOOKMOBI" or fdata[0x3c:0x3c+8] == b"TEXtREAd":
|
||||
return "MOBI"
|
||||
elif fdata.startswith(b"TPZ"):
|
||||
return "TPZ"
|
||||
else:
|
||||
return None
|
||||
# Unknown file type
|
||||
|
||||
|
||||
# If it's a ZIP, determine the type.
|
||||
|
||||
from lcpdedrm import isLCPbook
|
||||
if isLCPbook(file):
|
||||
return "LCP"
|
||||
|
||||
from ineptepub import adeptBook, isPassHashBook
|
||||
if adeptBook(file):
|
||||
if isPassHashBook(file):
|
||||
return "ADEPT-PassHash"
|
||||
else:
|
||||
return "ADEPT"
|
||||
|
||||
try:
|
||||
# Amazon / KFX-ZIP has a file that starts with b'\xeaDRMION\xee' in the ZIP.
|
||||
with closing(ZipFile(open(file, "rb"))) as book:
|
||||
for subfilename in book.namelist():
|
||||
with book.open(subfilename) as subfile:
|
||||
data = subfile.read(8)
|
||||
if data == b'\xeaDRMION\xee':
|
||||
return "KFX-ZIP"
|
||||
except:
|
||||
pass
|
||||
|
||||
return "ZIP"
|
||||
|
||||
|
||||
|
||||
|
||||
def dedrm_single_file(input_file, output_file):
|
||||
# When this runs, all the stupid file handling is done.
|
||||
# Just take the file at the absolute path "input_file"
|
||||
# and export it, DRM-free, to "output_file".
|
||||
|
||||
# Use a temp file as input_file and output_file
|
||||
# might be identical.
|
||||
|
||||
# The output directory might not exist yet.
|
||||
|
||||
print("File " + input_file + " to " + output_file)
|
||||
|
||||
# Okay, first check the file type and don't rely on the extension.
|
||||
try:
|
||||
ftype = determine_file_type(input_file)
|
||||
except:
|
||||
print("Can't determine file type for this file.")
|
||||
ftype = None
|
||||
|
||||
if ftype is None:
|
||||
return
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def perform_action(params, files):
|
||||
output = None
|
||||
outputdir = None
|
||||
force = False
|
||||
overwrite_original = False
|
||||
|
||||
|
||||
if len(files) == 0:
|
||||
print_removedrm_help()
|
||||
return 0
|
||||
|
||||
while len(params) > 0:
|
||||
p = params.pop(0)
|
||||
if p == "--output":
|
||||
output = params.pop(0)
|
||||
elif p == "--outputdir":
|
||||
outputdir = params.pop(0)
|
||||
elif p == "--force":
|
||||
force = True
|
||||
elif p == "--overwrite":
|
||||
overwrite_original = True
|
||||
force = True
|
||||
elif p == "--help":
|
||||
print_removedrm_help()
|
||||
return 0
|
||||
|
||||
if overwrite_original and (output is not None or outputdir is not None):
|
||||
print("Can't use --overwrite together with --output or --outputdir.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if output is not None and os.path.isfile(output) and not force:
|
||||
print("Output file already exists. Use --force to overwrite.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if output is not None and len(files) > 1:
|
||||
print("Cannot set output file name if there's multiple input files.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
if outputdir is not None and output is not None and os.path.isabs(output):
|
||||
print("--output parameter is absolute path despite --outputdir being set.", file=sys.stderr)
|
||||
print("Remove --outputdir, or give a relative path to --output.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
|
||||
for file in files:
|
||||
|
||||
file = os.path.abspath(file)
|
||||
|
||||
if not os.path.isfile(file):
|
||||
print("Skipping file " + file + " - not found.", file=sys.stderr)
|
||||
continue
|
||||
|
||||
if overwrite_original:
|
||||
output_filename = file
|
||||
else:
|
||||
if output is not None:
|
||||
# Due to the check above, we DO only have one file here.
|
||||
if outputdir is not None and not os.path.isabs(output):
|
||||
output_filename = os.path.join(outputdir, output)
|
||||
else:
|
||||
output_filename = os.path.abspath(output)
|
||||
else:
|
||||
if outputdir is None:
|
||||
outputdir = os.getcwd()
|
||||
output_filename = os.path.join(outputdir, os.path.basename(file))
|
||||
output_filename = os.path.abspath(output_filename)
|
||||
|
||||
if output_filename == file:
|
||||
# If we export to the import folder, add a suffix to the file name.
|
||||
fn, f_ext = os.path.splitext(output_filename)
|
||||
output_filename = fn + "_nodrm" + f_ext
|
||||
|
||||
|
||||
|
||||
if os.path.isfile(output_filename) and not force:
|
||||
print("Skipping file " + file + " because output file already exists (use --force).", file=sys.stderr)
|
||||
continue
|
||||
|
||||
|
||||
|
||||
dedrm_single_file(file, output_filename)
|
||||
|
||||
|
||||
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("This code is not intended to be executed directly!", file=sys.stderr)
|
||||
|
|
@ -1,49 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
import sys
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
|
||||
def uStrCmp (s1, s2, caseless=False):
|
||||
import unicodedata as ud
|
||||
if sys.version_info[0] == 2:
|
||||
str1 = s1 if isinstance(s1, unicode) else unicode(s1)
|
||||
str2 = s2 if isinstance(s2, unicode) else unicode(s2)
|
||||
else:
|
||||
str1 = s1 if isinstance(s1, str) else str(s1)
|
||||
str2 = s2 if isinstance(s2, str) else str(s2)
|
||||
|
||||
if caseless:
|
||||
return ud.normalize('NFC', str1.lower()) == ud.normalize('NFC', str2.lower())
|
||||
else:
|
||||
return ud.normalize('NFC', str1) == ud.normalize('NFC', str2)
|
||||
|
||||
|
||||
|
||||
# Wrap a stream so that output gets flushed immediately
|
||||
# and also make sure that any unicode strings get safely
|
||||
# encoded using "replace" before writing them.
|
||||
class SafeUnbuffered:
|
||||
def __init__(self, stream):
|
||||
self.stream = stream
|
||||
self.encoding = stream.encoding
|
||||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
|
|
@ -1,117 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
|
||||
# Standard Python modules.
|
||||
import os, sys, re, hashlib, traceback
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
from __init__ import PLUGIN_NAME, PLUGIN_VERSION
|
||||
|
||||
|
||||
class NoWinePython3Exception(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class WinePythonCLI:
|
||||
py3_test = "import sys; sys.exit(0 if (sys.version_info.major==3) else 1)"
|
||||
def __init__(self, wineprefix=""):
|
||||
import subprocess
|
||||
|
||||
if wineprefix != "":
|
||||
wineprefix = os.path.abspath(os.path.expanduser(os.path.expandvars(wineprefix)))
|
||||
|
||||
if wineprefix != "" and os.path.exists(wineprefix):
|
||||
self.wineprefix = wineprefix
|
||||
else:
|
||||
self.wineprefix = None
|
||||
|
||||
candidate_execs = [
|
||||
["wine", "py.exe", "-3"],
|
||||
["wine", "python3.exe"],
|
||||
["wine", "python.exe"],
|
||||
["wine", "C:\\Python27\\python.exe"], # Should likely be removed
|
||||
]
|
||||
for e in candidate_execs:
|
||||
self.python_exec = e
|
||||
try:
|
||||
self.check_call(["-c", self.py3_test])
|
||||
print("{0} v{1}: Python3 exec found as {2}".format(
|
||||
PLUGIN_NAME, PLUGIN_VERSION, " ".join(self.python_exec)
|
||||
))
|
||||
return None
|
||||
except subprocess.CalledProcessError as e:
|
||||
if e.returncode == 1:
|
||||
print("{0} v{1}: {2} is not python3".format(
|
||||
PLUGIN_NAME, PLUGIN_VERSION, " ".join(self.python_exec)
|
||||
))
|
||||
elif e.returncode == 53:
|
||||
print("{0} v{1}: {2} does not exist".format(
|
||||
PLUGIN_NAME, PLUGIN_VERSION, " ".join(self.python_exec)
|
||||
))
|
||||
raise NoWinePython3Exception("Could not find python3 executable on specified wine prefix")
|
||||
|
||||
|
||||
def check_call(self, cli_args):
|
||||
import subprocess
|
||||
|
||||
env_dict = os.environ
|
||||
env_dict["PYTHONPATH"] = ""
|
||||
if self.wineprefix is not None:
|
||||
env_dict["WINEPREFIX"] = self.wineprefix
|
||||
|
||||
subprocess.check_call(self.python_exec + cli_args, env=env_dict,
|
||||
stdin=None, stdout=sys.stdout,
|
||||
stderr=subprocess.STDOUT, close_fds=False,
|
||||
bufsize=1)
|
||||
|
||||
|
||||
def WineGetKeys(scriptpath, extension, wineprefix=""):
|
||||
|
||||
if extension == ".k4i":
|
||||
import json
|
||||
|
||||
try:
|
||||
pyexec = WinePythonCLI(wineprefix)
|
||||
except NoWinePython3Exception:
|
||||
print('{0} v{1}: Unable to find python3 executable in WINEPREFIX="{2}"'.format(PLUGIN_NAME, PLUGIN_VERSION, wineprefix))
|
||||
return [], []
|
||||
|
||||
basepath, script = os.path.split(scriptpath)
|
||||
print("{0} v{1}: Running {2} under Wine".format(PLUGIN_NAME, PLUGIN_VERSION, script))
|
||||
|
||||
outdirpath = os.path.join(basepath, "winekeysdir")
|
||||
if not os.path.exists(outdirpath):
|
||||
os.makedirs(outdirpath)
|
||||
|
||||
if wineprefix != "":
|
||||
wineprefix = os.path.abspath(os.path.expanduser(os.path.expandvars(wineprefix)))
|
||||
|
||||
try:
|
||||
result = pyexec.check_call([scriptpath, outdirpath])
|
||||
except Exception as e:
|
||||
print("{0} v{1}: Wine subprocess call error: {2}".format(PLUGIN_NAME, PLUGIN_VERSION, e.args[0]))
|
||||
|
||||
# try finding winekeys anyway, even if above code errored
|
||||
winekeys = []
|
||||
winekey_names = []
|
||||
# get any files with extension in the output dir
|
||||
files = [f for f in os.listdir(outdirpath) if f.endswith(extension)]
|
||||
for filename in files:
|
||||
try:
|
||||
fpath = os.path.join(outdirpath, filename)
|
||||
with open(fpath, 'rb') as keyfile:
|
||||
if extension == ".k4i":
|
||||
new_key_value = json.loads(keyfile.read())
|
||||
else:
|
||||
new_key_value = keyfile.read()
|
||||
winekeys.append(new_key_value)
|
||||
winekey_names.append(filename)
|
||||
except:
|
||||
print("{0} v{1}: Error loading file {2}".format(PLUGIN_NAME, PLUGIN_VERSION, filename))
|
||||
traceback.print_exc()
|
||||
os.remove(fpath)
|
||||
print("{0} v{1}: Found and decrypted {2} {3}".format(PLUGIN_NAME, PLUGIN_VERSION, len(winekeys), "key file" if len(winekeys) == 1 else "key files"))
|
||||
return winekeys, winekey_names
|
||||
|
|
@ -1,30 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
|
||||
"""
|
||||
Python 3's "zipfile" has an annoying bug where the `external_attr` field
|
||||
of a ZIP file cannot be set to 0. However, if the original DRMed ZIP has
|
||||
that set to 0 then we want the DRM-free ZIP to have that as 0, too.
|
||||
See https://github.com/python/cpython/issues/87713
|
||||
|
||||
We cannot just set the "external_attr" to 0 as the code to save the ZIP
|
||||
resets that variable.
|
||||
|
||||
So, here's a class that inherits from ZipInfo and ensures that EVERY
|
||||
read access to that variable will return a 0 ...
|
||||
|
||||
"""
|
||||
|
||||
import zipfile
|
||||
|
||||
class ZeroedZipInfo(zipfile.ZipInfo):
|
||||
def __init__(self, zinfo):
|
||||
for k in self.__slots__:
|
||||
if hasattr(zinfo, k):
|
||||
setattr(self, k, getattr(zinfo, k))
|
||||
|
||||
def __getattribute__(self, name):
|
||||
if name == "external_attr":
|
||||
return 0
|
||||
return object.__getattribute__(self, name)
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
DeDRM_plugin.zip
|
||||
================
|
||||
|
||||
This plugin will remove the DRM from:
|
||||
|
||||
- Kindle ebooks (files from Kindle for Mac/PC and eInk Kindles).
|
||||
- Adobe Digital Editions ePubs (including Kobo and Google ePubs downloaded to ADE)
|
||||
- Adobe Digital Editions PDFs
|
||||
|
||||
For limitations and work-arounds, see the FAQ at https://github.com/noDRM/DeDRM_tools/blob/master/FAQs.md (or the FAQ in Apprentice Harper's original repository at https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md)
|
||||
|
||||
|
||||
Installation
|
||||
------------
|
||||
Open calibre's Preferences dialog. Click on the "Plugins" button. Next, click on the button, "Load plugin from file". Navigate to the unzipped DeDRM_tools folder, find the file "DeDRM_plugin.zip". Click to select the file and select "Open". Click "Yes" in the "Are you sure?" dialog box. Click the "OK" button in the "Success" dialog box.
|
||||
|
||||
|
||||
Customization
|
||||
-------------
|
||||
For Kindle ebooks from an E-Ink based Kindle (e.g. Voyage), or books downloaded from the Amazon web site 'for transfer via USB' to an E-Ink base Kindle, you must enter the Kindle's serial number in the customisation dialog.
|
||||
|
||||
When you have finished entering your configuration information, you must click the OK button to save it. If you click the Cancel button, all your changes in all the configuration dialogs will be lost.
|
||||
|
||||
|
||||
Troubleshooting
|
||||
---------------
|
||||
If you find that the DeDRM plugin is not working for you (imported ebooks still have DRM - that is, they won't convert or open in the calibre ebook viewer), you should make a log of the import process by deleting the DRMed ebook from calibre and then adding the ebook to calibre when it's running in debug mode. This will generate a lot of helpful debugging info that can be copied into any online help requests. Here's how to do it:
|
||||
|
||||
- Remove the DRMed book from calibre.
|
||||
- Click the Preferences drop-down menu and choose 'Restart in debug mode'.
|
||||
- Once calibre has re-started, import the problem ebook.
|
||||
- Now close calibre.
|
||||
|
||||
A log will appear that you can copy and paste into a GitHub issue report at https://github.com/noDRM/DeDRM_tools/issues. Please also include information about the eBook file.
|
||||
|
||||
If you're using Apprentice Harper's original version, you can also comment at Apprentice Alf's blog, http://apprenticealf.wordpress.com/ or open an issue at Apprentice Harper's repository, https://github.com/apprenticeharper/DeDRM_tools/issues.
|
||||
166
FAQs.md
166
FAQs.md
|
|
@ -9,99 +9,118 @@ DRM ("Digital Rights Management") is a way of using encryption to tie the books
|
|||
When your ebooks have DRM you are unable to convert the ebook from one format to another (e.g. Kindle KF8 to Kobo ePub), so you are restricted in the range of ebook stores you can use. DRM also allows publishers to restrict what you can do with the ebook you've bought, e.g. preventing the use of text-to-speech software. Longer term, you can never be sure that you'll be able to come back and re-read your ebooks if they have DRM, even if you save back-up copies.
|
||||
|
||||
## So how can I remove DRM from my ebooks?
|
||||
Just download and use these tools, that's all! Uh, almost. There are a few, uh, provisos, a couple of quid pro quos.
|
||||
Just download and use these tools, that's all! Uh, almost. There are a few, uh, provisos, a, a couple of quid pro quos.
|
||||
|
||||
* The tools don't work on all ebooks. For example, they don't work on any ebooks from Apple's iBooks store.
|
||||
* You must own the ebook - the tools won't work on library ebooks or rented ebooks or books from a friend.
|
||||
* You must not use these tools to give your ebooks to a hundred of your closest friends. Or to a million strangers. Authors need to sell books to be able to write more books. Don't be mean to the authors.
|
||||
* Do NOT use Adobe Digital Editions 3.0 or later to download your ePubs. ADE 3.0 and later might use a new encryption scheme that the tools can't handle. While major ebook stores aren't using the new scheme yet, using ADE 2.0.1 will ensure that your ebooks are downloaded using the old scheme. Once a book has been downloaded with the new scheme, it's IMPOSSIBLE to re-download using the old scheme (without buying it again).
|
||||
* Do NOT use Kindle for PC/Mac version 1.25 or later. The tools don't current work with those versions.
|
||||
|
||||
### Recent Changes to Kindle for PC/Kindle for Mac
|
||||
Starting with version 1.19, Kindle for PC/Mac uses Amazon's new KFX format which isn't quite as good a source for conversion to ePub as the older KF8 (& MOBI) formats. There are two options to get the older formats. Either stick with version 1.17 or earlier, or modify the executable by changing a file name (PC) or disabling a component of the application (Mac).
|
||||
But otherwise, if your ebook is from Amazon, Kobo, Barnes & Noble or any of the ebook stores selling ebooks compatible with Adobe Digital Editions 2.0.1, you should be able to remove the DRM that's been applied to your ebooks.
|
||||
|
||||
Version 1.17 of Kindle is no longer available directly from Amazon, so you will need to search for the proper file name and find it on a third party site. The name is `KindleForPC-installer-1.17.44170.exe` for PC and `KindleForMac-44182.dmg` for Mac. (Note that this is a 32-bit application on the Mac, so will not work on Catalina and newer versions of macOS.)
|
||||
### A Recent Change to Kindle for PC/Kindle for Mac
|
||||
Starting with version 1.19, Kindle for PC/Mac uses Amazon's new KFX format which isn't quite as good a source fro conversion to ePub as the older KF8 (& MOBI) formats. There are two options to get the older formats. Either stick with version 1.17 or earlier, or modify the executable by changing a file name. Note that with Kindle for PC/Mac 1.25 and later, there is no current solution even for FKX. You must use 1.24 or earlier.
|
||||
|
||||
Version 1.17 of Kindle is are no longer available directly from Amazon, so you will need to search for the proper file name and find it on a third party site. The name is "KindleForPC-installer-1.17.44170.exe" for PC and "KindleForMac-44182.dmg" for Mac.
|
||||
Verify the one of the following cryptographic hash values, using software of your choice, before installing the downloaded file in order to avoid viruses. If the hash does not match, delete the downloaded file and try again from another site.
|
||||
Kindle for PC:
|
||||
MD-5: 53F793B562F4823721AA47D7DE099869
|
||||
SHA-1: 73C404D719F0DD8D4AE1C2C96612B095D6C86255
|
||||
SHA-256: 14E0F0053F1276C0C7C446892DC170344F707FBFE99B695176 2C120144163200
|
||||
Kindle for Mac:
|
||||
MD-5: E7E36D5369E1F3CF1D28E5D9115DF15F
|
||||
SHA-1: 7AB9A86B954CB23D622BD79E3257F8E2182D791C
|
||||
SHA-256: 28DC21246A9C7CDEDD2D6F0F4082E6BF7EF9DB9CE9D485548E 8A9E1D19EAE2AC.
|
||||
|
||||
#### Kindle for PC `KindleForPC-installer-1.17.44170.exe`:
|
||||
* MD-5: 53F793B562F4823721AA47D7DE099869
|
||||
* SHA-1: 73C404D719F0DD8D4AE1C2C96612B095D6C86255
|
||||
* SHA-256: 14E0F0053F1276C0C7C446892DC170344F707FBFE99B6951762C120144163200
|
||||
You will need to go to the preferences and uncheck the auto update checkbox. Then download and install 1.17 over the top of the 1.19 installation. You'll also need to delete the KFX folders from your My Kindle Content folder.
|
||||
|
||||
#### Kindle for Mac `KindleForMac-44182.dmg`:
|
||||
* MD-5: E7E36D5369E1F3CF1D28E5D9115DF15F
|
||||
* SHA-1: 7AB9A86B954CB23D622BD79E3257F8E2182D791C
|
||||
* SHA-256: 28DC21246A9C7CDEDD2D6F0F4082E6BF7EF9DB9CE9D485548E8A9E1D19EAE2AC
|
||||
|
||||
You will need to go to the preferences and uncheck the auto update checkbox. Then download and install 1.17 over the top of the newer installation. You'll also need to delete the KFX folders from your My Kindle Content folder. You may also need to take further action to prevent an auto update. The simplest way is to find the 'updates' folder and replace it with a file. See [this thread] (http://www.mobileread.com/forums/showthread.php?t=283371) at MobileRead for a Script to do this on a PC. On a Mac you can find the folder at ~/Library/Application Support/Kindle/. Make the 'updates' folder read-only, or delete it and save a blank text file called 'updates' in its place.
|
||||
|
||||
Another possible solution is to use 1.19 or later, but disable KFX by renaming or disabling a necessary component of the application. This may or may not work on versions after 1.25. In a command window, enter the following commands when Kindle for PC/Mac is not running:
|
||||
A other possible solution is to use 1.19 or later, but disable KFX by renaming or disabling a necessary component of the application. This may or may not work on versions after 1.20. In a command window, enter the following commands when Kindle for PC/Mac is not running:
|
||||
|
||||
#### Windows
|
||||
`ren %localappdata%\Amazon\Kindle\application\renderer-test.exe renderer-test.xxx`
|
||||
ren %localappdata%\Amazon\Kindle\application\renderer-test.exe renderer-test.xxx
|
||||
|
||||
PC Note: The renderer-test program may be in a different location in some Kindle for PC installations. If the rename command fails look in other folders, such as `C:\Program Files\Amazon\Kindle`.
|
||||
PC Note: The renderer-test program may be in a different location in some Kindle for PC installations. If the rename command fails look in other folders, such as C:\Program Files\Amazon\Kindle.
|
||||
|
||||
#### Macintosh
|
||||
`chmod -x /Applications/Kindle.app/Contents/MacOS/renderer-test`
|
||||
chmod -x /Applications/Kindle.app/Contents/MacOS/renderer-test
|
||||
|
||||
Mac Note: If the chmod command fails with a permission error try again using `sudo` before `chmod` - `sudo chmod` [...]. This only works on Kindle for Mac 1.19 thru 1.31, it does NOT work with 1.32 or newer.
|
||||
Mac Note: If the chmod command fails with a permission error try again using sudo before chmod - sudo chmod [...]
|
||||
|
||||
After restarting the Kindle program any books previously downloaded in KFX format will no longer open. You will need to remove them from your device and re-download them. All future downloads will use the older Kindle formats instead of KFX although they will continue to be placed in one individual subdirectory per book. Note that books should be downloaded by right-click and 'Download', not by just opening the book. Recent (1.25+) versions of Kindle for Mac/PC may convert KF8 files to a new format that is not supported by these tools when the book is opened for reading.
|
||||
After restarting the Kindle program any books previously downloaded in KFX format will no longer open. You will need to remove them from your device and re-download them. All future downloads will use the older Kindle formats instead of KFX although they will continue to be placed in one individual subdirectory per book.
|
||||
|
||||
#### Decrypting KFX
|
||||
Thanks to work by several people, the tools can now decrypt KFX format ebooks from Kindle for Mac/PC. In addition to the DeDRM plugin, calibre users will also need to install jhowell's KFX Input plugin which is available through the standard plugin menu in calibre, or directly from [his plugin thread](https://www.mobileread.com/forums/showthread.php?t=291290) on Mobileread.
|
||||
|
||||
It's quite possible that Amazon will update their KFX DeDRM to prevent DRM removal from KFX books again. So Remove DRM as soon as possible!
|
||||
Thanks to work by several people, the tools can now decrypt KFX format ebooks from Kindle for PC. In addition to the DeDRM plugin, calibre users will also need to install jhowell's KFX Input plugin which is available through the standard plugin menu in calibre, or directly from [his plugin thread](https://www.mobileread.com/forums/showthread.php?t=291290) on Mobileread. Not that KFX decryption does not work for Kindle for Mac 1.25 and later.
|
||||
|
||||
#### Thanks
|
||||
Thanks to jhowell for his investigations into KFX format and the KFX Input plugin. Some of these instructions are from [his thread on the subject](https://www.mobileread.com/forums/showthread.php?t=283371) at MobileRead.
|
||||
|
||||
## Where can I get the latest version of these free DRM removal tools?
|
||||
Right here at github. Just go to the [releases page](https://github.com/noDRM/DeDRM_tools/releases) and download the latest zip archive of the tools, named `DeDRM\_tools\_X.X.X.zip`, where X.X.X is the version number. You do not need to download the source code archive. This will get you the forked version by noDRM. If you want to download the original version by Apprentice Harper, go to [this page](https://github.com/apprenticeharper/DeDRM_tools/releases) instead.
|
||||
Right here at github. Just go to the [releases page](https://github.com/apprenticeharper/DeDRM_tools/releases) and download the latest zip archive of the tools, named DeDRM\_tools\_X.X.X.zip, where X.X.X is the version number. You do not need to download the source code archive.
|
||||
|
||||
## I've downloaded the tools archive. Now what?
|
||||
First, unzip the archive. You should now have a DeDRM folder containing several files, including a `ReadMe_Overview.txt` file. Please read the `ReadMe_Overview.txt` file! That will explain what the files are, and you'll be able to work out which of the tools you need.
|
||||
First, unzip the archive. You should now have a DeDRM folder containing several other folders and a ReadMe\_First.txt file. Please read the ReadMe\_First file! That will explain what the folders are, and you'll be able to work out which of the tools you need.
|
||||
|
||||
## That's a big complicated ReadMe file! Isn't there a quick guide?
|
||||
Install calibre. Install the DeDRM\_plugin in calibre. Install the Obok\_plugin in calibre. Restart calibre. In the DeDRM_plugin customisation dialog add in any E-Ink Kindle serial numbers. Remember that the plugin only tries to remove DRM when ebooks are imported.
|
||||
Install calibre. Install the DeDRM\_plugin in calibre. Install the Obok\_plugin in calibre. Restart calibre. In the DeDRM_plugin customisation dialog add in any E-Ink Kindle serial numbers and your B&N account email address and password. Remember that the plugin only tries to remove DRM when ebooks are imported.
|
||||
|
||||
# Installing the Tools
|
||||
## The calibre plugin
|
||||
### I am trying to install the calibre plugin, but calibre says "ERROR: Unhandled exception: InvalidPlugin: The plugin in '[path]DeDRM\_tools\_X.X.X.zip' is invalid. It does not contain a top-level \_\_init\_\_.py file"
|
||||
You are trying to add the tools archive (e.g. `DeDRM_tools_10.0.2.zip`) instead of the plugin. The tools archive is not the plugin. It is a collection of DRM removal tools which includes the plugin. You must unzip the archive, and install the calibre plugin `DeDRM_plugin.zip` from inside the unzipped archive.
|
||||
### I am trying to install the calibre plugin, but calibre says "ERROR: Unhandled exception: InvalidPlugin: The plugin in u’[path]DeDRM\_tools\_6.5.3.zip’ is invalid. It does not contain a top-level \_\_init\_\_.py file"
|
||||
You are trying to add the tools archive (e.g. DeDRM\_tools\_6.5.3.zip) instead of the plugin. The tools archive is not the plugin. It is a collection of DRM removal tools which includes the plugin. You must unzip the archive, and install the calibre plugin (DeDRM\_plugin.zip) from a folder called “DeDRM\_calibre_plugin” in the unzipped archive.
|
||||
|
||||
### I’ve unzipped the tools archive, but I can’t find the calibre plugin when I try to add them to calibre. I use Windows.
|
||||
You should select the zip file that is in the `DeDRM_calibre_plugin` folder, not any files inside the plugin’s zip archive. Make sure you are selecting from the folder that you created when you unzipped the tools archive and not selecting a file inside the still-zipped tools archive.
|
||||
You should select the zip file that is in the “DeDRM\_calibre\_plugin” folder, not any files inside the plugin’s zip archive. Make sure you are selecting from the folder that you created when you unzipped the tools archive and not selecting a file inside the still-zipped tools archive.
|
||||
|
||||
(The problem is that Windows will allow apps to browse inside zip archives without needing to unzip them first. If there are zip archives inside the main zip archives, Windows will show them as unzipped as well. So what happens is people will unzip the `DeDRM_tools_X.X.X.zip` to a folder, but when using calibre they will actually navigate to the still zipped file by mistake and cannot tell they have done so because they do not have file extensions showing. So to the unwary Windows user, it appears that the zip archive was unzipped and that everything inside it was unzipped as well so there is no way to install the plugins.
|
||||
(The problem is that Windows will allow apps to browse inside zip archives without needing to unzip them first. If there are zip archives inside the main zip archives, Windows will show them as unzipped as well. So what happens is people will unzip the DeDRM\_tools\_X.X.X.zip to a folder, but when using calibre they will actually navigate to the still zipped file by mistake and cannot tell they have done so because they do not have file extensions showing. So to the unwary Windows user, it appears that the zip archive was unzipped and that everything inside it was unzipped as well so there is no way to install the plugins.
|
||||
|
||||
We strongly recommend renaming the `DeDRM_tools_X.X.X.zip` archive (after extracting its contents) to `DeDRM_tools_X.X.X_archive.zip`. If you do that, you are less likely to navigate to the wrong location from inside calibre.)
|
||||
We strongly recommend renaming the DeDRM\_tools\_X.X.X.zip archive (after extracting its contents) to DeDRM\_tools\_X.X.X_archive.zip. If you do that, you are less likely to navigate to the wrong location from inside calibre.)
|
||||
|
||||
## The Windows Application
|
||||
### I've installed ActiveState Python and PyCrypto, but the Windows application won't run. What have I done wrong?
|
||||
Nothing. There's a bug in the some older ActiveState Python Windows installers that puts the Tcl code in the wrong place. See [this comment of mine at ActiveState community](https://community.activestate.com/node/19090). Just move the Tcl code to the correct place manually and the Windows app should run.
|
||||
|
||||
## The Macintosh Application
|
||||
### I can't open the Macintosh Application. Some message about it not being signed or something.
|
||||
Try right-clicking and select open. That might give you the option to open it anyway. Otherwise you'll need to change your security settings to allow unsigned applications to run. You can probably change these back after running it for the first time.
|
||||
|
||||
### I can't open the Macintosh Application at all. I get 'The aplication "DeDRM" can't be opened'
|
||||
Some unzip applications do not respect the execution bit setting. Try unzipping the main tools archive using the built-in Mac unzip utility.
|
||||
|
||||
Alternatively, sometimes the execution bit isn't set correctly in the archive. If you put the extracted DeDRM application in your Applications folder, you can set the executable bit on the 'droplet' file from the terminal using the command chmod +x /Applications/DeDRM.app/Contents/MacOS/droplet
|
||||
|
||||
### I can't open the Macintosh Application at all. I get 'spawn_via_launchd() failed, errno=111'
|
||||
There seems to be a bug in Apple's launch services. Try using the free [Maintenance utility](https://www.titanium-software.fr/en/maintenance.html) from Titanium Software to clear the launch cache and database.
|
||||
|
||||
### The application opens, but always gives an error in the log 'ImportError: No module named Crypto.Cipher'
|
||||
Some version of MacOS don't include PyCrpto. Your should be able to install it by using this command in the Terminal app: python -m pip pycrypto
|
||||
|
||||
# Using the Tools
|
||||
## I can’t get the tools to work on my rented or library ebooks.
|
||||
The tools are not designed to remove DRM from rented or library ebooks.
|
||||
|
||||
## I've unzipped the tools, but what are all the different files, and how do I use them?
|
||||
Read the `ReadMe_Overview.txt` file and then the ReadMe files for the tools you're interested in. That's what they're for.
|
||||
Read the ReadMe_First.txt file and then the ReadMe files included in the tools folder(s) you're interested in. That's what they're for.
|
||||
|
||||
## I have installed the calibre plugin, but my books still have DRM. When I try to view or convert my books, calibre says they have DRM.
|
||||
DRM only gets removed when an ebook is imported into calibre. Also, if the book is already in calibre, by default calibre will discard the newly imported file. You can change this in calibre's Adding books preferences page (Automerge..../Overwrite....), so that newly imported files overwrite existing ebook formats. Then just re-import your books and the DRM-free versions will overwrite the DRMed versions while retaining your books' metadata.
|
||||
|
||||
## I have installed the calibre plugin, but I don’t know where my ebooks are stored.
|
||||
## I have installed the calibre plugin or I am trying to use one of the other tools, but I don’t know where my ebooks are stored.
|
||||
Your ebooks are stored on your computer or on your ebook reader. You need to find them to be able to remove the DRM. If they are on your reader, you should be able to locate them easily. On your computer it’s not so obvious. Here are the default locations.
|
||||
|
||||
### Macintosh
|
||||
Navigating from your home folder,
|
||||
|
||||
Kindle for Mac ebooks are in either `Library/Application Support/Kindle/My Kindle Content` or `Documents/My Kindle Content` or `Library/Containers/com.amazon.Kindle/Data/Library/Application Support/Kindle/My Kindle Content`, depending on your version of Kindle for Mac.
|
||||
Kindle for Mac ebooks are in either Library/Application Support/Kindle/My Kindle Content or Documents/My Kindle Content or Library/Containers/com.amazon.Kindle/Data/Library/Application Support/Kindle/My Kindle Content, depending on your version of Kindle for Mac.
|
||||
|
||||
Adobe Digital Editions ebooks are in `Documents/Digital Editions`
|
||||
Adobe Digital Editions ebooks are in Documents/Digital Editions
|
||||
|
||||
### Windows
|
||||
Navigating from your `Documents` folder (`My Documents` folder, pre-Windows 7)
|
||||
Navigating from your "Documents" folder ("My Documents" folder, pre-Windows 7)
|
||||
|
||||
Kindle for PC ebooks are in `My Kindle Content`
|
||||
Kindle for PC ebooks are in My Kindle Content
|
||||
|
||||
Adobe Digital Editions ebooks are in `My Digital Editions`
|
||||
Adobe Digital Editions ebooks are in My Digital Editions
|
||||
|
||||
|
||||
## I have installed the calibre plugin, and the book is not already in calibre, but the DRM does not get removed.
|
||||
|
|
@ -115,58 +134,71 @@ If this book is from an eInk Kindle (e.g. Paperwhite), you must enter the serial
|
|||
|
||||
If this book is from Kindle for Mac or Kindle for PC, you must have the Kindle Software installed on the same computer and user account as your copy of calibre.
|
||||
|
||||
If this book is from Kindle for Mac you must be using version 1.24 or below, even if you have the Input plugin installed.
|
||||
|
||||
If the book is from Kindle for PC or Kindle for Mac and you think you are doing everything right, and you are getting this message, it is possible that the files containing the encryption key aren’t quite in the format the tools expect. To try to fix this:
|
||||
|
||||
1. Deregister Kindle for PC/Mac from your Amazon account.
|
||||
1. Uninstall Kindle for PC/Mac
|
||||
1. Delete the Kindle for PC/Mac preferences
|
||||
* PC: Delete the directory `[home folder]\AppData\Local\Amazon` (it might be hidden) and `[home folder]\My Documents\My Kindle Content`
|
||||
* Mac: Delete the directory `[home folder]/Library/Application Support/Kindle/` and/or `[home folder]/Library/Containers/com.amazon.Kindle/Data/Library/Application Support/Kindle/` (one or both may be present and should be deleted)
|
||||
1. Reinstall Kindle for PC/Mac version 1.17 or earlier (see above for download links).
|
||||
1. Re-register Kindle for PC/Mac with your Amazon account
|
||||
1. Deregister Kindle for PC(Mac) from your Amazon account.
|
||||
1. Uninstall Kindle for PC(Mac)
|
||||
1. Delete the Kindle for PC(Mac) preferences
|
||||
* PC: Delete the directory [home folder]\AppData\Local\Amazon (it might be hidden) and [home folder]\My Documents\My Kindle Content
|
||||
* Mac: Delete the directory [home folder]/Library/Application Support/Kindle/and/or [home folder]/Library/Containers/com.amazon.Kindle/Data/Library/Application Support/Kindle/ (one or both may be present and should be deleted)
|
||||
1. Reinstall Kindle for PC(Mac) version 1.17 or earlier (see above for download links).
|
||||
1. Re-register Kindle for PC(Mac) with your Amazon account
|
||||
1. Download the ebook again. Do not use the files you have downloaded previously.
|
||||
|
||||
## Some of my books had their DRM removed, but some still say that they have DRM and will not convert.
|
||||
There are several possible reasons why only some books get their DRM removed.
|
||||
* You still don’t have the DRM removal tools working correctly, but some of your books didn’t have DRM in the first place.
|
||||
* Kindle only: It is a Topaz format book and contains some coding that the tools do not understand. You will need to get a log of the DeDRM attempt, and then create a [new issue at Apprentice Harper's github repository](https://github.com/apprenticeharper/DeDRM_tools/issues/), attaching the book and the log, so that the tools can be updated.
|
||||
|
||||
If you are still having problems with particular books, you will need to create a log of the DRM removal attempt for one of the problem books. If you're using NoDRM's fork, open [a new issue](https://github.com/noDRM/DeDRM_tools/issues) in the GitHub repo. If you're using Apprentice Harper's version, post that logfile in a new issue at [Apprentice Harper's github repository](https://github.com/apprenticeharper/DeDRM_tools/issues).
|
||||
If you are still having problems with particular books, you will need to create a log of the DRM removal attempt for one of the problem books, and post that in a comment at Apprentice Alf's blog or in a new issue at Apprentice Harper's github repository.
|
||||
|
||||
## My Kindle book has imported and the DRM has been removed, but all the pictures are gone.
|
||||
Most likely, this is a book downloaded from Amazon directly to an eInk Kindle (e.g. Paperwhite). Unfortunately, the pictures are probably in a `.azw6` file that the tools don't understand. You must download the book manually from Amazon's web site "For transfer via USB" to your Kindle. When you download the eBook in this manner, Amazon will package the pictures in the with text in a single file that the tools will be able to import successfully.
|
||||
Most likely, this is a book downloaded from Amazon directly to an eInk Kindle (e.g. Paperwhite). Unfortunately, the pictures are probably in a .azw6 file that the tools don't understand. You must download the book manually from Amazon's web site "For transfer via USB" to your Kindle. When you download the eBook in this manner, Amazon will package the pictures in the with text in a single file that the tools will be able to import successfully.
|
||||
|
||||
## My Kindle book has imported, but it's showing up as an AZW4 format. Conversions take a long time and/or are very poor.
|
||||
You have found a Print Replica Kindle ebook. This is a PDF in a Kindle wrapper. Now the DRM has been removed, you can extract the PDF from the wrapper using the KindleUnpack plugin. Conversion of PDFs rarely gives good results.
|
||||
|
||||
## The tools can't see an ebook that was downloaded directly to my eInk kindle, although it's definitely there, and I can read it on the Kindle. I can't even try to import it.
|
||||
Mostly likely, this is a book downloaded from Amazon directly to one of the newer eInk Kindles (e.g. Paperwhite). Unfortunately, it is probably in a new multi-file KFX format that the tools don't understand. You must download the book manually from Amazon's web site "For transfer via USB" to your Kindle. When you download the ebook in this manner, Amazon will send a single KF8-format file that the tools will be able to import successfully.
|
||||
|
||||
## Do the tools work on books from Kobo?
|
||||
If you use the Kobo desktop application for Mac or PC, install the Obok plugin. This will import and remove the DRM from your Kobo books, and is the easiest method for Kobo ebooks.
|
||||
If you use the Kobo desktop application for Mac or PC, install the obok plugin. This will import and remove the DRM from your Kobo books, and is the easiest method for Kobo ebooks.
|
||||
|
||||
## I registered Adobe Digital Editions 3.0 or later with an Adobe ID before downloading, but my epub or PDF still has DRM.
|
||||
Adobe introduced a new DRM scheme with ADE 3.0 and later. Install ADE 2.0.1 and register with the same Adobe ID. If you can't open your book in ADE 2.01, then you have a book with the new DRM scheme. These tools can't help. You can avoid the new DRM scheme by always downloading your ebooks with ADE 2.0.1. Some retailers will require ADE 3.0 or later, in which case you won't be able to download with ADE 2.0.1.
|
||||
|
||||
## The DRM wasn't removed and the log says "Failed to decrypt with error: Cannot decode library or rented ebooks." What now?
|
||||
You're trying to remove the DRM from an ebook that's only on loan to you. No help will be given to remove DRM from such ebooks. If you think that you have received this message for a book you own, please create an issue at github, or comment at the blog.
|
||||
|
||||
## I cannot solve my problem with the DeDRM plugin, and now I need to ‘post a log’. How do I do that?
|
||||
Remove the DRMed book from calibre. Click the Preferences drop-down menu and choose 'Restart in debug mode'. Once calibre has re-started, import the problem ebook. Now close calibre. A log will appear that you can copy and paste into [a new issue](https://github.com/noDRM/DeDRM_tools/issues) in NoDRM’s GitHub repo. If you're using Apprentice Harper’s version, post that logfile in a new issue at [Apprentice Harper's GitHub repository](https://github.com/apprenticeharper/DeDRM_tools/issues).
|
||||
Remove the DRMed book from calibre. Click the Preferences drop-down menu and choose 'Restart in debug mode'. Once calibre has re-started, import the problem ebook. Now close calibre. A log will appear that you can copy and paste into a comment at Apprentice Alf's blog, or into a new issue at Apprentice Harper's github repository.
|
||||
|
||||
## I cannot solve my problem with the Macintosh DeDRM application, and now I need to ‘post a log’. How do I do that?
|
||||
The Macintosh DeDRM application creates a log file on your desktop every time it is run. After unsuccessfully removing DRM from one ebook, copy the contents of the log file (it is a simple text file) and paste it into your comment at Apprentice Alf's blog or in a new issue at Apprentice Harper's github repository.
|
||||
|
||||
## I cannot solve my problem with the Windows DeDRM application, and now I need to ‘post a log’. How do I do that?
|
||||
The Windows DeDRM application creates a log file in your home directory (C:\Users\[username]) every time it is run. After unsuccessfully removing DRM from one ebook, copy the contents of the log file (it is a simple text file) and paste it into your comment at Apprentice Alf's blog or in a new issue at Apprentice Harper's github repository.
|
||||
|
||||
## Is there a way to use the DeDRM plugin for Calibre from the command line?
|
||||
See the [Calibre command line interface (CLI) instructions](CALIBRE_CLI_INSTRUCTIONS.md).
|
||||
|
||||
## The plugin displays a "MemoryError" in its log file during DRM removal.
|
||||
A "MemoryError" usually occurs when you're using the 32-bit version of Calibre (which is limited in the amount of useable RAM). If you have a 64-bit installation of your operating system (on Windows, press Windows+Break, then make sure it says "64-bit Operating System" under "System type"), try downloading the 64-bit version of Calibre instead of the 32-bit version.
|
||||
|
||||
If the error still occurs, even with the 64-bit version, please open a bug report.
|
||||
|
||||
# General Questions
|
||||
|
||||
## Once the DRM has been removed, is there any trace of my personal identity left in the ebook?
|
||||
That question cannot be answered for sure. While it is easy to check if a book has DRM or not, it is very difficult to verify if all (traces of) personal information have been removed from a book. The tools attempt to remove watermarks when they are detected (optionally, there's an option in the plugin settings to enable that), but that will not be the case for all watermarks.
|
||||
The tools only remove the DRM. No attempt is made to remove any personally identifying information.
|
||||
|
||||
## Why do some of my Kindle ebooks import as HTMLZ format in calibre?
|
||||
## What do some of my Kindle ebooks import as HTMLZ format in calibre?
|
||||
Most Amazon Kindle ebooks are Mobipocket format ebooks, or the new KF8 format. However, some are in a format known as Topaz. The Topaz format is only used by Amazon. A Topaz ebook is a collections of glyphs and their positions on each page tagged with some additional information from that page including OCRed text (Optical Character Recognition generated Text) to allow searching, and some additional layout information. Each page of a Topaz ebook is effectively a description of an image of that page. To convert a Topaz ebook to another format is not easy as there is not a one-to-one mapping between glyphs and characters/fonts. To account for this, two different formats are generated by the DRM removal software. The first is an html description built from the OCRtext and images stored in the Topaz file (HTMLZ). This format is easily reflowed but may suffer from typical OCRtext errors including typos, garbled text, missing italics, missing bolds, etc. The second format uses the glyph and position information to create an accurate scalable vector graphics (SVG) image of each page of the book that can be viewed in web browsers that support svg images (Safari, Firefox 4 or later, etc). Additional conversion software can be used to convert these SVG images to an image only PDF file. The DeDRM calibre plugin only imports the HTMLZ versions of the Topaz ebook. The html version can be manually cleaned up and spell checked and then converted using Sigil/calibre to epubs, mobi ebooks, and etc.
|
||||
|
||||
## Are the tools open source? How can I be sure they are safe and not a trojan horse?
|
||||
All the DRM removal tools hosted here are almost entirely written in Python. So they are inherently open source, and open to inspection by everyone who downloads them.
|
||||
All the DRM removal tools hosted here are almost entirely scripts of one kind or another: Python, Applescript or Windows Batch files. So they are inherently open source, and open to inspection by everyone who downloads them.
|
||||
|
||||
There are some optional shared libraries (`*.dll`, `*.dylib`, and `*.so`) included for performance. The source for any compiled pieces are provided within `alfcrypto_src.zip`. If this is a concern either delete the binary files (there's fallback code in the plugin that allows it to work without these, it will just be slower) or manually rebuild them from source.
|
||||
There are some optional shared libraries (`*.dll`, `*.dylib`, and `*.so`) included for performance. The source for any compiled pieces are provided within `alfcrypto_src.zip`. If this is a concern either delete the binary files or manually rebuild them.
|
||||
|
||||
## What ebooks do these tools work on?
|
||||
The Calibre plugin removes DRM from PDF, ePub, kePub (Kobo), eReader, Kindle (Mobipocket, KF8, Print Replica and Topaz) format ebooks using Adobe Adept, Barnes & Noble, Amazon, Kobo and eReader DRM schemes. It used to remove Readium LCP DRM from ePub or PDF files in the past, but that functionality had to be removed due to a [DMCA takedown request](https://github.com/noDRM/DeDRM_tools/issues/18).
|
||||
The tools linked from this blog remove DRM from PDF, ePub, kePub (Kobo), eReader, Kindle (Mobipocket, KF8, Print Replica and Topaz) format ebooks using Adobe Adept, Barnes & Noble, Amazon, Kobo and eReader DRM schemes.
|
||||
|
||||
Note these tools do NOT ‘crack’ the DRM. They simply allow the book’s owner to use the encryption key information already stored someplace on their computer or device to decrypt the ebook in the same manner the official ebook reading software uses.
|
||||
|
||||
|
|
@ -182,26 +214,22 @@ Amazon turned off backup for Kindle for Android, so the tools can no longer find
|
|||
## Why don't the tools work on books from the Apple iBooks Store?
|
||||
Apple regularly change the details of their DRM and so the tools in the main tools archive will not work with these ebooks. Apple’s Fairplay DRM scheme can be removed using Requiem if the appropriate version of iTunes can still be installed and used. See the post Apple and ebooks: iBookstore DRM and how to remove it at Apprentice Alf's blog for more details.
|
||||
|
||||
## Why don't the tools work with LCP-encrypted ebooks? / Error message about a "DMCA takedown"
|
||||
Support for LCP DRM removal was included in the past, but Readium (the company who developed that particular DRM) has decided to [open a DMCA takedown request](https://github.com/github/dmca/blob/master/2022/01/2022-01-04-readium.md) in January 2022. This means that for legal reasons, this GitHub repository no longer contains the code needed to remove DRM from LCP-encrypted books. For more information please read [this bug report](https://github.com/noDRM/DeDRM_tools/issues/18).
|
||||
|
||||
## I’ve got the tools archive and I’ve read all the FAQs but I still can’t install the tools and/or the DRM removal doesn’t work
|
||||
* Read the `ReadMe_Overview.txt` file in the top level of the tools archive
|
||||
* Read the ReadMe file for the tool you want to use.
|
||||
* If you still can’t remove the DRM, create a new [GitHub issue](https://github.com/noDRM/DeDRM_tools/issues). If you are using Apprentice Harper's original version and not this fork, you can also create a new issue at Apprentice Harper's github repository. If you do report an issue in any of the GitHub repositories, please report the error as precisely as you can. Include what platform you use, what tool you have tried, what errors you get, and what versions you are using. If the problem happens when running one of the tools, post a log (see previous questions on how to do this).
|
||||
* Read the ReadMe_First.txt file in the top level of the tools archive
|
||||
* Read the ReadMe file in the folder of the tools you want to use.
|
||||
* If you still can’t remove the DRM, ask in the comments section of Apprentice Alf's blog or create a new issue at Apprentice Harper's github repository, reporting the error as precisely as you can, what platform you use, what tool you have tried, what errors you get, and what versions you are using. If the problem happens when running one of the tools, post a log (see previous questions on how to do this).
|
||||
|
||||
## Who wrote these scripts?
|
||||
The authors tend to identify themselves only by pseudonyms:
|
||||
* The Adobe Adept and Barnes & Noble scripts were created by i♥cabbages
|
||||
* The Adobe Adept support for ADE3.0+ DRM was added by a980e066a01
|
||||
* ~The Readium LCP support for this plugin was created by NoDRM~ (removed due to a DMCA takedown, see [#18](https://github.com/noDRM/DeDRM_tools/issues/18) )
|
||||
* The Amazon Mobipocket and eReader scripts were created by The Dark Reverser
|
||||
* The Amazon K4PC DRM/format was further decoded by Bart Simpson aka Skindle
|
||||
* The Amazon K4 Mobi tool was created by by some_updates, mdlnx and others
|
||||
* The Amazon Topaz DRM removal script was created by CMBDTC
|
||||
* The Amazon Topaz format conversion was created by some_updates, clarknova, and Bart Simpson
|
||||
* The DeDRM all-in-one AppleScript application was created by Apprentice Alf
|
||||
* The DeDRM all-in-one Python application was created by some_updates
|
||||
* The DeDRM all-in-one calibre plugin was created by Apprentice Alf
|
||||
* The support for .kinf2018 key files and KFX 2&3 was by Apprentice Sakuya
|
||||
* The Scuolabooks tool was created by Hex
|
||||
* The Microsoft code was created by drs
|
||||
* The Apple DRM removal tool was created by Brahms
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -1,364 +0,0 @@
|
|||
# SOME DESCRIPTIVE TITLE.
|
||||
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
|
||||
# This file is distributed under the same license as the PACKAGE package.
|
||||
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
|
||||
#
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: \n"
|
||||
"Report-Msgid-Bugs-To: \n"
|
||||
"POT-Creation-Date: 2014-11-17 12:51+0100\n"
|
||||
"PO-Revision-Date: 2021-01-19 12:20+0100\n"
|
||||
"Language: sv\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
|
||||
"Last-Translator: \n"
|
||||
"Language-Team: \n"
|
||||
"X-Generator: Poedit 2.4.2\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:80
|
||||
msgid ""
|
||||
"<p>No books found in Kobo Library\n"
|
||||
"Are you sure it's installed\\configured\\synchronized?"
|
||||
msgstr ""
|
||||
"<p>Inga böcker hittades i Kobo-bibliotek\n"
|
||||
"Är du säker på att den är installerad\\konfigurerad\\synkroniserad?"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:87
|
||||
msgid "Legacy key found: "
|
||||
msgstr "Äldre nyckel hittades: "
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:93
|
||||
msgid "Trouble retrieving keys with newer obok method."
|
||||
msgstr "Problem med att hämta nycklar med nyare obok-metod."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:97
|
||||
msgid "Found {0} possible keys to try."
|
||||
msgstr "Hittade {0} möjliga nycklar att försöka med."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:99
|
||||
msgid "<p>No userkeys found to decrypt books with. No point in proceeding."
|
||||
msgstr ""
|
||||
"<p>Inga användarnycklar hittades för att dekryptera böcker med. Det är ingen "
|
||||
"idé att fortsätta."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:115
|
||||
msgid "{} - Decryption canceled by user."
|
||||
msgstr "{} - Dekryptering avbröts av användaren."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:135
|
||||
msgid "{} - \"Add books\" canceled by user."
|
||||
msgstr "{} - \"Lägg till böcker\" avbröts av användaren."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:137
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:156
|
||||
msgid "{} - wrapping up results."
|
||||
msgstr "{} - samlar in resultat."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:153
|
||||
msgid "{} - User opted not to try to insert EPUB formats"
|
||||
msgstr "{} - Användaren valde att inte försöka infoga EPUB-format"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:188
|
||||
msgid "{0} - Decrypting {1}"
|
||||
msgstr "{0} - Dekrypterar {1}"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:197
|
||||
msgid "{0} - Couldn't decrypt {1}"
|
||||
msgstr "{0} - Kunde inte dekryptera {1}"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:198
|
||||
msgid "decryption errors"
|
||||
msgstr "dekrypteringsfel"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:213
|
||||
msgid "{0} - Added {1}"
|
||||
msgstr "{0} - Lade till {1}"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:218
|
||||
msgid "{0} - {1} already exists. Will try to add format later."
|
||||
msgstr "{0} - {1} finns redan. Kommer att försöka lägga till format senare."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:219
|
||||
msgid "duplicate detected"
|
||||
msgstr "dubblett upptäcktes"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:233
|
||||
msgid "{0} - Successfully added EPUB format to existing {1}"
|
||||
msgstr "{0} - EPUB-formatet har lagts till i befintliga {1}"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:236
|
||||
msgid ""
|
||||
"{0} - Error adding EPUB format to existing {1}. This really shouldn't happen."
|
||||
msgstr ""
|
||||
"{0} - Fel vid tilläggning av EPUB-formatet till befintliga {1}. Detta borde "
|
||||
"verkligen inte hända."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:259
|
||||
msgid "{} - \"Insert formats\" canceled by user."
|
||||
msgstr "{} - \"Infoga format\" avbröts av användaren."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:291
|
||||
msgid ""
|
||||
"<p><b>{0}</b> EPUB{2} successfully added to library.<br /><br /><b>{1}</b> "
|
||||
msgstr "<p><b>{0}</b> EPUB{2} har lagts till i bibliotek.<br /><br /><b>{1}</b> "
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:292
|
||||
msgid ""
|
||||
"not added because books with the same title/author were detected.<br /><br /"
|
||||
">Would you like to try and add the EPUB format{0}"
|
||||
msgstr ""
|
||||
"lades inte till eftersom böcker med samma titel/författare upptäcktes.<br/"
|
||||
"><br />Vill du försöka lägga till EPUB-formatet{0}"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:293
|
||||
msgid ""
|
||||
" to those existing entries?<br /><br />NOTE: no pre-existing EPUBs will be "
|
||||
"overwritten."
|
||||
msgstr ""
|
||||
" till dessa befintliga poster?<br /><br />OBS: inga befintliga EPUB:er kommer "
|
||||
"att skrivas över."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:295
|
||||
msgid ""
|
||||
"{0} -- not added because of {1} in your library.\n"
|
||||
"\n"
|
||||
msgstr ""
|
||||
"{0} -- lades inte till på grund av {1} i ditt bibliotek.\n"
|
||||
"\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:297
|
||||
msgid "<p><b>{0}</b> -- not added because of {1} in your library.<br /><br />"
|
||||
msgstr ""
|
||||
"<p><b>{0}</b> -- lades inte till på grund av {1} i ditt bibliotek.<br /><br />"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:298
|
||||
msgid ""
|
||||
"Would you like to try and add the EPUB format to an available calibre "
|
||||
"duplicate?<br /><br />"
|
||||
msgstr ""
|
||||
"Vill du försöka lägga till EPUB-formatet till en tillgänglig calibre-dubblett?"
|
||||
"<br /><br />"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:299
|
||||
msgid "NOTE: no pre-existing EPUB will be overwritten."
|
||||
msgstr "OBS: ingen befintlig EPUB kommer att skrivas över."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:346
|
||||
msgid "Trying key: "
|
||||
msgstr "Försöker med nyckel: "
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:378
|
||||
msgid "Decryption failed, trying next key."
|
||||
msgstr "Dekryptering misslyckades, försöker med nästa nyckel."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:382
|
||||
msgid "Unknown Error decrypting, trying next key.."
|
||||
msgstr "Okänt fel vid dekryptering, försöker med nästa nyckel.."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:395
|
||||
msgid ""
|
||||
"<p>All selected Kobo books added as new calibre books or inserted into "
|
||||
"existing calibre ebooks.<br /><br />No issues."
|
||||
msgstr ""
|
||||
"<p>Alla valda Kobo-böcker har lagts till som nya calibre-böcker eller infogats "
|
||||
"i befintliga calibre-e-böcker.<br /><br />Inga problem."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:399
|
||||
msgid "<p>{0} successfully added."
|
||||
msgstr "<p>{0} har lagts till."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:403
|
||||
msgid ""
|
||||
"<p>Not all selected Kobo books made it into calibre.<br /><br />View report "
|
||||
"for details."
|
||||
msgstr ""
|
||||
"<p>Inte alla valda Kobo-böcker lades till i calibre.<br /><br />Visa rapport "
|
||||
"för detaljer."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:404
|
||||
msgid "<p><b>Total attempted:</b> {}</p>\n"
|
||||
msgstr "<p><b>Försök totalt:</b> {}</p>\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:405
|
||||
msgid "<p><b>Decryption errors:</b> {}</p>\n"
|
||||
msgstr "<p><b>Dekrypteringsfel:</b> {}</p>\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:411
|
||||
msgid "<p><b>New Books created:</b> {}</p>\n"
|
||||
msgstr "<p><b>Nya böcker skapade:</b> {}</p>\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:418
|
||||
msgid "<p><b>Duplicates that weren't added:</b> {}</p>\n"
|
||||
msgstr "<p><b>Dubbletter som inte har lagts till:</b> {}</p>\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:426
|
||||
msgid "<p><b>Book imports cancelled by user:</b> {}</p>\n"
|
||||
msgstr "<p><b>Bokimport avbröts av användaren:</b> {}</p>\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:428
|
||||
msgid "<p><b>New EPUB formats inserted in existing calibre books:</b> {0}</p>\n"
|
||||
msgstr ""
|
||||
"<p><b>Nya EPUB-format infogade i befintliga calibre-böcker:</b> {0}</p>\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:434
|
||||
msgid ""
|
||||
"<p><b>EPUB formats NOT inserted into existing calibre books:</b> {}<br />\n"
|
||||
msgstr ""
|
||||
"<p><b>EPUB-format som INTE infogats i befintliga calibre-böcker:</b> {}<br />\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:435
|
||||
msgid ""
|
||||
"(Either because the user <i>chose</i> not to insert them, or because all "
|
||||
"duplicates already had an EPUB format)"
|
||||
msgstr ""
|
||||
"(Antingen för att användaren <i>valde</i> att inte infoga dem, eller för att "
|
||||
"alla dubbletter redan hade ett EPUB-format)"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:444
|
||||
msgid "<p><b>Format imports cancelled by user:</b> {}</p>\n"
|
||||
msgstr "<p><b>Format-importen avbröts av användaren:</b> {}</p>\n"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:458
|
||||
msgid "Unknown Book Title"
|
||||
msgstr "Okänd boktitel"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:460
|
||||
msgid "it couldn't be decrypted."
|
||||
msgstr "den kunde inte dekrypteras."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:462
|
||||
msgid ""
|
||||
"user CHOSE not to insert the new EPUB format, or all existing calibre entries "
|
||||
"HAD an EPUB format already."
|
||||
msgstr ""
|
||||
"användaren VALDE att inte infoga det nya EPUB-formatet, eller alla befintliga "
|
||||
"calibre-poster hade redan ett EPUB-format."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:464
|
||||
msgid "of unknown reasons. Gosh I'm embarrassed!"
|
||||
msgstr "av okända skäl. Jag skäms!"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\action.py:465
|
||||
msgid "<p>{0} not added because {1}"
|
||||
msgstr "<p>{0} lades inte till på grund av {1}"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\common_utils.py:226
|
||||
msgid "Help"
|
||||
msgstr "Hjälp"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\common_utils.py:235
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\utilities.py:214
|
||||
msgid "Restart required"
|
||||
msgstr "Kräver omstart"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\common_utils.py:236
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\utilities.py:215
|
||||
msgid ""
|
||||
"Title image not found - you must restart Calibre before using this plugin!"
|
||||
msgstr ""
|
||||
"Titelbild hittades inte - du måste starta om calibre innan du använder denna "
|
||||
"insticksmodul!"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\common_utils.py:322
|
||||
msgid "Undefined"
|
||||
msgstr "Odefinierad"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\config.py:30
|
||||
msgid "When should Obok try to insert EPUBs into existing calibre entries?"
|
||||
msgstr "När ska Obok försöka infoga EPUB:er i befintliga calibre-poster?"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\config.py:33
|
||||
msgid ""
|
||||
"<p>Default behavior when duplicates are detected. None of the choices will "
|
||||
"cause calibre ebooks to be overwritten"
|
||||
msgstr ""
|
||||
"<p>Standardbeteende när dubbletter upptäcks. Inget av alternativen kommer att "
|
||||
"orsaka att calibre-e-böcker skrivs över"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\config.py:35
|
||||
msgid "Ask"
|
||||
msgstr "Fråga"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\config.py:35
|
||||
msgid "Always"
|
||||
msgstr "Alltid"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\config.py:35
|
||||
msgid "Never"
|
||||
msgstr "Aldrig"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:60
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\utilities.py:150
|
||||
msgid " v"
|
||||
msgstr " v"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:65
|
||||
msgid "Obok DeDRM"
|
||||
msgstr "Obok DeDRM"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:68
|
||||
msgid "<a href=\"http://www.foo.com/\">Help</a>"
|
||||
msgstr "<a href=\"http://www.foo.com/\">Hjälp</a>"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:89
|
||||
msgid "Select All"
|
||||
msgstr "Välj alla"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:90
|
||||
msgid "Select all books to add them to the calibre library."
|
||||
msgstr "Välj alla böcker för att lägga till dem i calibre-biblioteket."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:92
|
||||
msgid "All with DRM"
|
||||
msgstr "Alla med DRM"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:93
|
||||
msgid "Select all books with DRM."
|
||||
msgstr "Välj alla böcker med DRM."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:95
|
||||
msgid "All DRM free"
|
||||
msgstr "Alla utan DRM"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:96
|
||||
msgid "Select all books without DRM."
|
||||
msgstr "Välj alla böcker utan DRM."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:146
|
||||
msgid "Title"
|
||||
msgstr "Titel"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:146
|
||||
msgid "Author"
|
||||
msgstr "Författare"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:146
|
||||
msgid "Series"
|
||||
msgstr "Serier"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:369
|
||||
msgid "Copy to clipboard"
|
||||
msgstr "Kopiera till urklipp"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\dialogs.py:397
|
||||
msgid "View Report"
|
||||
msgstr "Visa rapport"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\__init__.py:21
|
||||
msgid "Removes DRM from Kobo kepubs and adds them to the library."
|
||||
msgstr "Tar bort DRM från Kobo-kepubs och lägger till dem i biblioteket."
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\obok\obok.py:162
|
||||
msgid "AES improper key used"
|
||||
msgstr "Felaktig AES-nyckel används"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\obok\obok.py:167
|
||||
msgid "Failed to initialize AES key"
|
||||
msgstr "Misslyckades med att initiera AES-nyckel"
|
||||
|
||||
#: I:\Herramientas\PoeditPortable\App\Poedit\bin\obok_plugin-3.1.0_trad\obok\obok.py:175
|
||||
msgid "AES decryption failed"
|
||||
msgstr "AES-dekryptering misslyckades"
|
||||
26
README.md
26
README.md
|
|
@ -1,35 +1,17 @@
|
|||
# DeDRM_tools
|
||||
DeDRM tools for ebooks
|
||||
|
||||
This is a fork of Apprentice Harper's version of the DeDRM tools. Apprentice Harper said that the original version of the plugin [is no longer maintained](https://github.com/apprenticeharper/DeDRM_tools#no-longer-maintained), so I've taken over, merged a bunch of open PRs, and added a ton more features and bugfixes.
|
||||
This is a repository of all the scripts and other tools for removing DRM from ebooks that I could find, committed in date order as best as I could manage. (Except for the Requiem tools for Apple's iBooks, and Convert LIT for Microsoft's .lit ebooks.)
|
||||
|
||||
The latest stable (released) version is v10.0.3 which [can be downloaded here](https://github.com/noDRM/DeDRM_tools/releases/tag/v10.0.3). The latest beta is v10.0.9, as a release candidate for v10.1.0. It [can be downloaded here](https://github.com/noDRM/DeDRM_tools/releases/tag/v10.0.9).
|
||||
Mostly it tracks the tools releases by Apprentice Alf, athough it also includes the individual tools and their histories from before Alf had a blog.
|
||||
|
||||
The latest alpha version is available [at this link](https://github.com/noDRM/DeDRM_tools_autorelease/releases). This version is completely untested and will contain the latest code changes in this repository. With each commit in this repository, a new automatic alpha version will be uploaded there. If you want the most up-to-date code to test things and are okay with the plugin occasionally breaking, you can download this version.
|
||||
|
||||
Take a look at [the CHANGELOG](https://github.com/noDRM/DeDRM_tools/blob/master/CHANGELOG.md) to see a list of changes since the last version by Apprentice Harper (v7.2.1).
|
||||
|
||||
My version of the plugin should both work with Calibre 5.x/6.x (Python 3) as well as Calibre 4.x and lower (Python 2). If you encounter issues with this plugin in Calibre 4.x or lower, please open a bug report.
|
||||
|
||||
# Original README from Apprentice Harper
|
||||
|
||||
This is a repository that tracks all the scripts and other tools for removing DRM from ebooks that I could find, committed in date order as best as I could manage. (Except for the Requiem tools for Apple's iBooks, and Convert LIT for Microsoft's .lit ebooks.) This includes the tools from a time before Apprentice Alf had a blog, and continues through to when Apprentice Harper (with help) took over maintenance of the tools.
|
||||
|
||||
The individual scripts are now released as two plugins for calibre: DeDRM and Obok.
|
||||
The DeDRM plugin handles books that use Amazon DRM, Adobe Digital Editions DRM, Barnes & Noble DRM, and some historical formats.
|
||||
The Obok plugin handles Kobo DRM.
|
||||
|
||||
Users with calibre 5.x or later should use release 7.2.0 or later of the tools.
|
||||
Users with calibe 4.x or earlier should use release 6.8.x of the tools.
|
||||
Users should download the latest zip archive.
|
||||
Developers might be interested in forking the repository, as it contains unzipped versions of those tools that are zipped, and text versions of the AppleScripts, to make the changes over time easier to follow.
|
||||
|
||||
For the latest Amazon KFX format, users of the calibre plugin should also install the KFX Input plugin from the standard calibre plugin menu. It's also available from the MobileRead thread here: https://www.mobileread.com/forums/showthread.php?t=291290
|
||||
|
||||
Note that Amazon changes the DRM for KFX files frequently. What works for KFX today might not work tomorrow.
|
||||
|
||||
I welcome contributions from others to improve these tools, from expanding the range of books handled, improving key retrieval, to just general bug fixes, speed improvements and UI enhancements.
|
||||
|
||||
I urge people to read the FAQs. But to cover the most common: Do remember to unzip the downloaded archive to get the plugin (beta versions may be just the plugin don't unzip that). You can't load the whole tools archive into calibre.
|
||||
|
||||
My special thanks to all those developers who have done the hard work of reverse engineering to provide the initial tools.
|
||||
|
||||
Apprentice Harper.
|
||||
|
|
|
|||
|
|
@ -1,60 +0,0 @@
|
|||
Welcome to the tools!
|
||||
=====================
|
||||
|
||||
This file is to give users a quick overview of what is available and how to get started. This document is part of the DeDRM Tools archive from noDRM's github repository: https://github.com/noDRM/DeDRM_tools/
|
||||
|
||||
This archive includes calibre plugins to remove DRM from:
|
||||
|
||||
- Kindle ebooks (files from Kindle for Mac/PC and eInk Kindles).
|
||||
- Adobe Digital Editions ePubs (including Kobo and Google ePubs downloaded to ADE)
|
||||
- Adobe Digital Editions PDFs
|
||||
- Kobo kePubs from the Kobo Desktop application and attached Kobo readers.
|
||||
|
||||
These tools do NOT work with Apple's iBooks FairPlay DRM. Use iBook Copy from TunesKit.
|
||||
These tools no longer work well with books from Barnes & Noble.
|
||||
Due to a DMCA request, these tools no longer work with LCP-encrypted books - see https://github.com/noDRM/DeDRM_tools/issues/18 for details.
|
||||
|
||||
For limitations and work-arounds, see the FAQ at https://github.com/noDRM/DeDRM_tools/blob/master/FAQs.md
|
||||
|
||||
About the tools
|
||||
---------------
|
||||
These tools are updated and maintained by noDRM and many others. They are based on Apprentice Harper's Calibre plugin. You can find the latest updates at noDRM's github repository https://github.com/noDRM/DeDRM_tools/ and get support by creating an issue at the repository (github account required).
|
||||
|
||||
If you re-post these tools, a link to the repository would be appreciated.
|
||||
|
||||
The tools are provided in the form of plugins for calibre. Calibre is an open source freeware ebook library manager. It is the best tool around for keeping track of your ebooks.
|
||||
|
||||
|
||||
DeDRM plugin for calibre (Linux, Mac OS X and Windows)
|
||||
-------------------------------------------------------
|
||||
calibe 5.x and later are now written in Python 3, and plugins must also use Python 3.
|
||||
|
||||
The DeDRM plugin for calibre removes DRM from your Kindle and Adobe DRM ebooks when they are imported to calibre. Just install the DeDRM plugin (DeDRM_plugin.zip), following the instructions and configuration directions provided in the ReadMe file and the help links in the plugin's configuration dialogs.
|
||||
|
||||
Once installed and configured, you can simply add a DRM book to calibre and a DRM-free version will be imported into the calibre database. Note that DRM removal only occurs on IMPORT not on CONVERSION or at any other time. If you have already imported DRMed books you'll need to remove the books from calibre and re-import them.
|
||||
|
||||
|
||||
Obok plugin for calibre (Mac OS X and Windows)
|
||||
----------------------------------------------
|
||||
To import ebooks from the Kobo Desktop app or from a Kobo ebook reader, install the Obok plugin. This works in a different way to the DeDRM plugin, in that it finds your ebooks downloaded using the Kobo Desktop app, or on an attached Kobo ebooks reader, and displays them in a list, so that you can choose the ones you want to import into calibre.
|
||||
|
||||
For instructions, see the obok_plugin_ReadMe.txt file.
|
||||
|
||||
|
||||
Credits
|
||||
-------
|
||||
The original inept and ignoble scripts were by i♥cabbages
|
||||
~The original Readium LCP DRM removal by NoDRM~ (removed due to a DMCA request)
|
||||
The original mobidedrm and erdr2pml scripts were by The Dark Reverser
|
||||
The original topaz DRM removal script was by CMBDTC
|
||||
The original topaz format conversion scripts were by some_updates, clarknova and Bart Simpson
|
||||
The original KFX format decryption was by lulzkabulz, converted to python by Apprentice Naomi and integrated into the tools by tomthumb1997
|
||||
The alfcrypto library is by some_updates
|
||||
The DeDRM plugin is based on plugins by DiapDealer and is currently maintained by noDRM
|
||||
The DeDRM plugin has been maintained by Apprentice Alf and Apprentice Harper until 2021.
|
||||
|
||||
The original obok script was by Physisticated
|
||||
The plugin conversion was done anonymously.
|
||||
The Kobo reader support was added by norbusan
|
||||
|
||||
Fixes, updates and enhancements to the scripts and applicatons have been made by many other anonymous people.
|
||||
102
contrib/DeDRM_Macintosh_Application/DeDRM ReadMe.rtf
Normal file
102
contrib/DeDRM_Macintosh_Application/DeDRM ReadMe.rtf
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
{\rtf1\ansi\ansicpg1252\cocoartf1561\cocoasubrtf600
|
||||
{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fnil\fcharset134 STHeitiSC-Light;}
|
||||
{\colortbl;\red255\green255\blue255;}
|
||||
{\*\expandedcolortbl;;}
|
||||
\paperw11900\paperh16840\vieww12000\viewh15840\viewkind0
|
||||
\deftab720
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\qc\partightenfactor0
|
||||
|
||||
\f0\b\fs24 \cf0 DeDRM ReadMe
|
||||
\b0 \
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\qj\partightenfactor0
|
||||
|
||||
\b \cf0 \
|
||||
\
|
||||
DeDRM is now a 64-bit application for Mac OS X 10.6 and later.
|
||||
\b0 \
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\partightenfactor0
|
||||
\cf0 \
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\partightenfactor0
|
||||
|
||||
\b \cf0 First Use for Mac OS X 10.9 and later\
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\partightenfactor0
|
||||
|
||||
\b0 \cf0 The application is not signed, so the first time you run it you will need to change your security options, or hold down the option key when double-clicking on the icon, or control-click or right-button to get the contextual menu to open it. For later versions, after trying to run it once, you may need to go to the security options of the control panel and give explicit permission for this application to be run.\
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\partightenfactor0
|
||||
|
||||
\b \cf0 \
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\qj\partightenfactor0
|
||||
|
||||
\b0 \cf0 DeDRM is an application that packs all of the python dm removal software into one easy to use program that remembers preferences and settings.\
|
||||
It works without manual configuration with Kindle for Mac ebooks, Adobe Digital Editions Adept ePub and PDF ebooks, and Barnes & Noble NOOK Study ebooks.\
|
||||
\
|
||||
To remove the DRM of Kindle ebooks from eInk Kindles, other Barnes & Noble ePubs, eReader pdb ebooks, or Mobipocket ebooks, you must first run DeDRM application (by double-clicking it) and set some additional Preferences, depending on the origin of your ebook files:\
|
||||
\
|
||||
|
||||
\b eInk Kindle (not Kindle Fire)
|
||||
\b0 :
|
||||
\b \
|
||||
|
||||
\b0 16 digit Serial Number, found in your Amazon account web pages.\
|
||||
|
||||
\b Barnes & Noble (not from NOOK Study)
|
||||
\b0 : \
|
||||
Your account email and password, so the key can be retrieved from the Barnes & Noble servers.\
|
||||
An active internet connection is required for this.\
|
||||
|
||||
\b eReader
|
||||
\b0 :\
|
||||
Name and last 8 digits of CC number\
|
||||
|
||||
\b Mobipocket
|
||||
\b0 :\
|
||||
10 digit PID\
|
||||
\
|
||||
A final preference is the destination folder for the DRM-free copies of your ebooks that the application produces. This can be either the same folder as the original ebook, or a folder of your choice.\
|
||||
\
|
||||
Once these preferences have been set, you can drag and drop ebooks (or folders of ebooks) onto the DeDRM droplet to remove the DRM.\
|
||||
\
|
||||
This program uses notifications, so really needs Mac OS X 10.8 or above.\
|
||||
\
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\partightenfactor0
|
||||
|
||||
\b \cf0 Installation
|
||||
\b0 \
|
||||
Drag the DeDRM application from from the DeDRM_Application_Macintosh folder (the location of this ReadMe) to your Applications folder, or anywhere else you find convenient.\
|
||||
\
|
||||
\
|
||||
|
||||
\b \
|
||||
Use
|
||||
\b0 \
|
||||
1. To set the preferences, double-click the application and follow the instructions in the dialogs.\
|
||||
2. Drag & Drop DRMed ebooks or folders of DRMed ebooks onto the application icon when it is not running.\
|
||||
\
|
||||
\
|
||||
|
||||
\b Troubleshooting\
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\partightenfactor0
|
||||
|
||||
\b0 \cf0 A log is created on your desktop (DeDRM.log) containing detailed information from all the scripts. If you have any problems decrypting your ebooks, copy the contents of this log in a comment at Apprentice Alf's blog.\
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\partightenfactor0
|
||||
{\field{\*\fldinst{HYPERLINK "http://apprenticealf.wordpress.com/"}}{\fldrslt \cf0 http://apprenticealf.wordpress.com/}}\
|
||||
\
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\partightenfactor0
|
||||
|
||||
\b \cf0 Credits\
|
||||
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardeftab720\partightenfactor0
|
||||
|
||||
\b0 \cf0 The original inept and ignoble scripts were by i
|
||||
\f1 \uc0\u9829
|
||||
\f0 cabbages\
|
||||
The original mobidedrm and erdr2pml scripts were by The Dark Reverser\
|
||||
The original topaz DRM removal script was by CMBDTC\
|
||||
The original topaz format conversion scripts were by some_updates, clarknova and Bart Simpson\
|
||||
\
|
||||
The alfcrypto library is by some_updates\
|
||||
The ePub encryption detection script is by Apprentice Alf, adapted from a script by Paul Durrant\
|
||||
The ignoblekey script is by Apprentice Harper\
|
||||
The DeDRM AppleScript is by Apprentice Alf and Apprentice Harper, adapted from a script by Paul Durrant\
|
||||
\
|
||||
Many fixes, updates and enhancements to the scripts and applications have been made by many other people. For more details, see the comments in the individual scripts.\
|
||||
}
|
||||
BIN
contrib/DeDRM_Macintosh_Application/DeDRM.app.txt
Normal file
BIN
contrib/DeDRM_Macintosh_Application/DeDRM.app.txt
Normal file
Binary file not shown.
|
|
@ -0,0 +1,91 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleAllowMixedLocalizations</key>
|
||||
<true/>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>English</string>
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleTypeExtensions</key>
|
||||
<array>
|
||||
<string>*</string>
|
||||
</array>
|
||||
<key>CFBundleTypeOSTypes</key>
|
||||
<array>
|
||||
<string>****</string>
|
||||
</array>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Viewer</string>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>droplet</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>DeDRM</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.apple.ScriptEditor.id.DeDRM</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>DeDRM</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.6.3</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>dplt</string>
|
||||
<key>LSMinimumSystemVersionByArchitecture</key>
|
||||
<dict>
|
||||
<key>x86_64</key>
|
||||
<string>10.6</string>
|
||||
</dict>
|
||||
<key>LSRequiresCarbon</key>
|
||||
<true/>
|
||||
<key>NSAppleEventsUsageDescription</key>
|
||||
<string>This script needs to control other applications to run.</string>
|
||||
<key>NSAppleMusicUsageDescription</key>
|
||||
<string>This script needs access to your music to run.</string>
|
||||
<key>NSCalendarsUsageDescription</key>
|
||||
<string>This script needs access to your calendars to run.</string>
|
||||
<key>NSCameraUsageDescription</key>
|
||||
<string>This script needs access to your camera to run.</string>
|
||||
<key>NSContactsUsageDescription</key>
|
||||
<string>This script needs access to your contacts to run.</string>
|
||||
<key>NSHomeKitUsageDescription</key>
|
||||
<string>This script needs access to your HomeKit Home to run.</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright © 2010–2019 Apprentice Alf</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>This script needs access to your microphone to run.</string>
|
||||
<key>NSPhotoLibraryUsageDescription</key>
|
||||
<string>This script needs access to your photos to run.</string>
|
||||
<key>NSRemindersUsageDescription</key>
|
||||
<string>This script needs access to your reminders to run.</string>
|
||||
<key>NSSiriUsageDescription</key>
|
||||
<string>This script needs access to Siri to run.</string>
|
||||
<key>NSSystemAdministrationUsageDescription</key>
|
||||
<string>This script needs access to administer this system to run.</string>
|
||||
<key>WindowState</key>
|
||||
<dict>
|
||||
<key>bundleDividerCollapsed</key>
|
||||
<false/>
|
||||
<key>bundlePositionOfDivider</key>
|
||||
<real>1162</real>
|
||||
<key>dividerCollapsed</key>
|
||||
<false/>
|
||||
<key>eventLogLevel</key>
|
||||
<integer>0</integer>
|
||||
<key>name</key>
|
||||
<string>ScriptWindowState</string>
|
||||
<key>positionOfDivider</key>
|
||||
<real>651</real>
|
||||
<key>savedFrame</key>
|
||||
<string>0 37 1680 990 0 0 1680 1027 </string>
|
||||
<key>selectedTab</key>
|
||||
<string>log</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
BIN
contrib/DeDRM_Macintosh_Application/DeDRM.app/Contents/MacOS/droplet
Executable file
BIN
contrib/DeDRM_Macintosh_Application/DeDRM.app/Contents/MacOS/droplet
Executable file
Binary file not shown.
|
|
@ -0,0 +1 @@
|
|||
APPLdplt
|
||||
Binary file not shown.
|
|
@ -0,0 +1,50 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>BuildMachineOSBuild</key>
|
||||
<string>10K549</string>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>English</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>DeDRM Progress</string>
|
||||
<key>CFBundleGetInfoString</key>
|
||||
<string>DeDRM Progress 1.1, Written 2010, 2012 by Apprentice Alf and others.</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string>DeDRM Progress</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.apprenticealf.DeDRMProgress</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>DeDRM Progress</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.1</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1.0</string>
|
||||
<key>DTCompiler</key>
|
||||
<string>4.0</string>
|
||||
<key>DTPlatformBuild</key>
|
||||
<string>10M2518</string>
|
||||
<key>DTPlatformVersion</key>
|
||||
<string>PG</string>
|
||||
<key>DTSDKBuild</key>
|
||||
<string>8S2167</string>
|
||||
<key>DTSDKName</key>
|
||||
<string>macosx10.4</string>
|
||||
<key>DTXcode</key>
|
||||
<string>0400</string>
|
||||
<key>DTXcodeBuild</key>
|
||||
<string>10M2518</string>
|
||||
<key>NSAppleScriptEnabled</key>
|
||||
<string>YES</string>
|
||||
<key>NSMainNibFile</key>
|
||||
<string>MainMenu</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
</dict>
|
||||
</plist>
|
||||
Binary file not shown.
|
|
@ -0,0 +1 @@
|
|||
APPL????
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,5 @@
|
|||
{\rtf1\ansi\ansicpg1252\cocoartf1671
|
||||
{\fonttbl}
|
||||
{\colortbl;\red255\green255\blue255;}
|
||||
{\*\expandedcolortbl;;}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
chcp 65001 > nul && set PWD="%~dp0" && cd /d "%~dp0DeDRM_lib" && start /min python DeDRM_App.pyw %*
|
||||
|
|
@ -0,0 +1,704 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# DeDRM.pyw
|
||||
# Copyright 2010-2019 some_updates, Apprentice Alf and Apprentice Harper
|
||||
|
||||
# Revision history:
|
||||
# 6.0.0 - Release along with unified plugin
|
||||
# 6.0.1 - Bug Fixes for Windows App
|
||||
# 6.0.2 - Fixed problem with spaces in paths and the bat file
|
||||
# 6.0.3 - Fix for Windows non-ascii user names
|
||||
# 6.0.4 - Fix for other potential unicode problems
|
||||
# 6.0.5 - Fix typo
|
||||
# 6.2.0 - Update to match plugin and AppleScript
|
||||
# 6.2.1 - Fix for non-ascii user names
|
||||
# 6.2.2 - Added URL method for B&N/nook books
|
||||
# 6.3.0 - Add in Android support
|
||||
# 6.3.1 - Version bump for clarity
|
||||
# 6.3.2 - Version bump to match plugin
|
||||
# 6.3.3 - Version bump to match plugin
|
||||
# 6.3.4 - Version bump to match plugin
|
||||
# 6.3.5 - Version bump to match plugin
|
||||
# 6.3.6 - Version bump to match plugin
|
||||
# 6.4.0 - Fix for Kindle for PC encryption change
|
||||
# 6.4.1 - Fix for new tags in Topaz ebooks
|
||||
# 6.4.2 - Fix for new tags in Topaz ebooks, and very small Topaz ebooks
|
||||
# 6.4.3 - Version bump to match plugin & Mac app
|
||||
# 6.5.0 - Fix for some new tags in Topaz ebooks
|
||||
# 6.5.1 - Version bump to match plugin & Mac app
|
||||
# 6.5.2 - Fix for a new tag in Topaz ebooks
|
||||
# 6.5.3 - Explicitly warn about KFX files
|
||||
# 6.5.4 - PDF float fix.
|
||||
# 6.5.5 - Kindle for PC/Accented characters in username fix.
|
||||
# 6.6.0 - Initial KFX support from TomThumb
|
||||
# 6.6.1 - Standalong app fix from wzyboy
|
||||
# 6.6.2 - Version bump for 64-bit Mac OS X app and various fixes.
|
||||
# 6.6.3 - Version bump for Kindle book name fixes and start of support for .kinf2018
|
||||
|
||||
__version__ = '6.6.3'
|
||||
|
||||
import sys
|
||||
import os, os.path
|
||||
sys.path.append(os.path.join(sys.path[0],"lib"))
|
||||
import sys, os
|
||||
import codecs
|
||||
|
||||
from argv_utils import add_cp65001_codec, set_utf8_default_encoding, unicode_argv
|
||||
add_cp65001_codec()
|
||||
set_utf8_default_encoding()
|
||||
|
||||
|
||||
import shutil
|
||||
import Tkinter
|
||||
from Tkinter import *
|
||||
import Tkconstants
|
||||
import tkFileDialog
|
||||
from scrolltextwidget import ScrolledText
|
||||
from activitybar import ActivityBar
|
||||
if sys.platform.startswith("win"):
|
||||
from askfolder_ed import AskFolder
|
||||
import re
|
||||
import simpleprefs
|
||||
import traceback
|
||||
|
||||
from Queue import Full
|
||||
from Queue import Empty
|
||||
from multiprocessing import Process, Queue
|
||||
|
||||
from scriptinterface import decryptepub, decryptpdb, decryptpdf, decryptk4mobi
|
||||
|
||||
|
||||
# Wrap a stream so that output gets flushed immediately
|
||||
# and appended to shared queue
|
||||
class QueuedUTF8Stream:
|
||||
def __init__(self, stream, q):
|
||||
self.stream = stream
|
||||
self.encoding = 'utf-8'
|
||||
self.q = q
|
||||
def write(self, data):
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode('utf-8',"replace")
|
||||
self.q.put(data)
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
class DrmException(Exception):
|
||||
pass
|
||||
|
||||
class MainApp(Tk):
|
||||
def __init__(self, apphome, dnd=False, filenames=[]):
|
||||
Tk.__init__(self)
|
||||
self.withdraw()
|
||||
self.dnd = dnd
|
||||
self.apphome = apphome
|
||||
|
||||
# preference settings
|
||||
# [dictionary key, file in preferences directory where info is stored]
|
||||
description = [ ['pids' , 'pidlist.txt' ],
|
||||
['serials', 'seriallist.txt'],
|
||||
['sdrms' , 'sdrmlist.txt' ],
|
||||
['outdir' , 'outdir.txt' ]]
|
||||
self.po = simpleprefs.SimplePrefs("DeDRM",description)
|
||||
if self.dnd:
|
||||
self.cd = ConvDialog(self)
|
||||
prefs = self.getPreferences()
|
||||
self.cd.doit(prefs, filenames)
|
||||
else:
|
||||
prefs = self.getPreferences()
|
||||
self.pd = PrefsDialog(self, prefs)
|
||||
self.cd = ConvDialog(self)
|
||||
self.pd.show()
|
||||
|
||||
def getPreferences(self):
|
||||
prefs = self.po.getPreferences()
|
||||
prefdir = prefs['dir']
|
||||
adeptkeyfile = os.path.join(prefdir,'adeptkey.der')
|
||||
if not os.path.exists(adeptkeyfile):
|
||||
import adobekey
|
||||
try:
|
||||
adobekey.getkey(adeptkeyfile)
|
||||
except:
|
||||
pass
|
||||
kindlekeyfile = os.path.join(prefdir,'kindlekey.k4i')
|
||||
if not os.path.exists(kindlekeyfile):
|
||||
import kindlekey
|
||||
try:
|
||||
kindlekey.getkey(kindlekeyfile)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
pass
|
||||
bnepubkeyfile = os.path.join(prefdir,'bnepubkey.b64')
|
||||
if not os.path.exists(bnepubkeyfile):
|
||||
import ignoblekey
|
||||
try:
|
||||
ignoblekey.getkey(bnepubkeyfile)
|
||||
except:
|
||||
traceback.print_exc()
|
||||
pass
|
||||
return prefs
|
||||
|
||||
def setPreferences(self, newprefs):
|
||||
prefdir = self.po.prefdir
|
||||
if 'adkfile' in newprefs:
|
||||
dfile = newprefs['adkfile']
|
||||
fname = os.path.basename(dfile)
|
||||
nfile = os.path.join(prefdir,fname)
|
||||
if os.path.isfile(dfile):
|
||||
shutil.copyfile(dfile,nfile)
|
||||
if 'bnkfile' in newprefs:
|
||||
dfile = newprefs['bnkfile']
|
||||
fname = os.path.basename(dfile)
|
||||
nfile = os.path.join(prefdir,fname)
|
||||
if os.path.isfile(dfile):
|
||||
shutil.copyfile(dfile,nfile)
|
||||
if 'kindlefile' in newprefs:
|
||||
dfile = newprefs['kindlefile']
|
||||
fname = os.path.basename(dfile)
|
||||
nfile = os.path.join(prefdir,fname)
|
||||
if os.path.isfile(dfile):
|
||||
shutil.copyfile(dfile,nfile)
|
||||
if 'androidfile' in newprefs:
|
||||
dfile = newprefs['androidfile']
|
||||
fname = os.path.basename(dfile)
|
||||
nfile = os.path.join(prefdir,fname)
|
||||
if os.path.isfile(dfile):
|
||||
shutil.copyfile(dfile,nfile)
|
||||
self.po.setPreferences(newprefs)
|
||||
return
|
||||
|
||||
def alldone(self):
|
||||
if not self.dnd:
|
||||
self.pd.enablebuttons()
|
||||
else:
|
||||
self.destroy()
|
||||
|
||||
class PrefsDialog(Toplevel):
|
||||
def __init__(self, mainapp, prefs_array):
|
||||
Toplevel.__init__(self, mainapp)
|
||||
self.withdraw()
|
||||
self.protocol("WM_DELETE_WINDOW", self.withdraw)
|
||||
self.title("DeDRM " + __version__)
|
||||
self.prefs_array = prefs_array
|
||||
self.status = Tkinter.Label(self, text='Setting Preferences')
|
||||
self.status.pack(fill=Tkconstants.X, expand=1)
|
||||
body = Tkinter.Frame(self)
|
||||
self.body = body
|
||||
body.pack(fill=Tkconstants.X, expand=1)
|
||||
sticky = Tkconstants.E + Tkconstants.W
|
||||
body.grid_columnconfigure(1, weight=2)
|
||||
|
||||
cur_row = 0
|
||||
Tkinter.Label(body, text='Adobe Key file (adeptkey.der)').grid(row=cur_row, sticky=Tkconstants.E)
|
||||
self.adkpath = Tkinter.Entry(body, width=50)
|
||||
self.adkpath.grid(row=cur_row, column=1, sticky=sticky)
|
||||
prefdir = self.prefs_array['dir']
|
||||
keyfile = os.path.join(prefdir,'adeptkey.der')
|
||||
if os.path.isfile(keyfile):
|
||||
path = keyfile
|
||||
self.adkpath.insert(cur_row, path)
|
||||
button = Tkinter.Button(body, text="...", command=self.get_adkpath)
|
||||
button.grid(row=cur_row, column=2)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='Kindle Key file (kindlekey.k4i)').grid(row=cur_row, sticky=Tkconstants.E)
|
||||
self.kkpath = Tkinter.Entry(body, width=50)
|
||||
self.kkpath.grid(row=cur_row, column=1, sticky=sticky)
|
||||
prefdir = self.prefs_array['dir']
|
||||
keyfile = os.path.join(prefdir,'kindlekey.k4i')
|
||||
if os.path.isfile(keyfile):
|
||||
path = keyfile
|
||||
self.kkpath.insert(0, path)
|
||||
button = Tkinter.Button(body, text="...", command=self.get_kkpath)
|
||||
button.grid(row=cur_row, column=2)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='Android Kindle backup file (backup.ab)').grid(row=cur_row, sticky=Tkconstants.E)
|
||||
self.akkpath = Tkinter.Entry(body, width=50)
|
||||
self.akkpath.grid(row=cur_row, column=1, sticky=sticky)
|
||||
prefdir = self.prefs_array['dir']
|
||||
keyfile = os.path.join(prefdir,'backup.ab')
|
||||
if os.path.isfile(keyfile):
|
||||
path = keyfile
|
||||
self.akkpath.insert(0, path)
|
||||
button = Tkinter.Button(body, text="...", command=self.get_akkpath)
|
||||
button.grid(row=cur_row, column=2)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='Barnes and Noble Key file (bnepubkey.b64)').grid(row=cur_row, sticky=Tkconstants.E)
|
||||
self.bnkpath = Tkinter.Entry(body, width=50)
|
||||
self.bnkpath.grid(row=cur_row, column=1, sticky=sticky)
|
||||
prefdir = self.prefs_array['dir']
|
||||
keyfile = os.path.join(prefdir,'bnepubkey.b64')
|
||||
if os.path.isfile(keyfile):
|
||||
path = keyfile
|
||||
self.bnkpath.insert(0, path)
|
||||
button = Tkinter.Button(body, text="...", command=self.get_bnkpath)
|
||||
button.grid(row=cur_row, column=2)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='Mobipocket PID list\n(8 or 10 characters, comma separated)').grid(row=cur_row, sticky=Tkconstants.E)
|
||||
self.pidnums = Tkinter.StringVar()
|
||||
self.pidinfo = Tkinter.Entry(body, width=50, textvariable=self.pidnums)
|
||||
if 'pids' in self.prefs_array:
|
||||
self.pidnums.set(self.prefs_array['pids'])
|
||||
self.pidinfo.grid(row=cur_row, column=1, sticky=sticky)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='eInk Kindle Serial Number list\n(16 characters, comma separated)').grid(row=cur_row, sticky=Tkconstants.E)
|
||||
self.sernums = Tkinter.StringVar()
|
||||
self.serinfo = Tkinter.Entry(body, width=50, textvariable=self.sernums)
|
||||
if 'serials' in self.prefs_array:
|
||||
self.sernums.set(self.prefs_array['serials'])
|
||||
self.serinfo.grid(row=cur_row, column=1, sticky=sticky)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='eReader data list\n(name:last 8 digits on credit card, comma separated)').grid(row=cur_row, sticky=Tkconstants.E)
|
||||
self.sdrmnums = Tkinter.StringVar()
|
||||
self.sdrminfo = Tkinter.Entry(body, width=50, textvariable=self.sdrmnums)
|
||||
if 'sdrms' in self.prefs_array:
|
||||
self.sdrmnums.set(self.prefs_array['sdrms'])
|
||||
self.sdrminfo.grid(row=cur_row, column=1, sticky=sticky)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text="Output Folder (if blank, use input ebook's folder)").grid(row=cur_row, sticky=Tkconstants.E)
|
||||
self.outpath = Tkinter.Entry(body, width=50)
|
||||
self.outpath.grid(row=cur_row, column=1, sticky=sticky)
|
||||
if 'outdir' in self.prefs_array:
|
||||
dpath = self.prefs_array['outdir']
|
||||
self.outpath.insert(0, dpath)
|
||||
button = Tkinter.Button(body, text="...", command=self.get_outpath)
|
||||
button.grid(row=cur_row, column=2)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='').grid(row=cur_row, column=0, columnspan=2, sticky=Tkconstants.N)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='Alternatively Process an eBook').grid(row=cur_row, column=0, columnspan=2, sticky=Tkconstants.N)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='Select an eBook to Process*').grid(row=cur_row, sticky=Tkconstants.E)
|
||||
self.bookpath = Tkinter.Entry(body, width=50)
|
||||
self.bookpath.grid(row=cur_row, column=1, sticky=sticky)
|
||||
button = Tkinter.Button(body, text="...", command=self.get_bookpath)
|
||||
button.grid(row=cur_row, column=2)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, font=("Helvetica", "10", "italic"), text='*To DeDRM multiple ebooks simultaneously, set your preferences and quit.\nThen drag and drop ebooks or folders onto the DeDRM_Drop_Target').grid(row=cur_row, column=1, sticky=Tkconstants.E)
|
||||
|
||||
cur_row = cur_row + 1
|
||||
Tkinter.Label(body, text='').grid(row=cur_row, column=0, columnspan=2, sticky=Tkconstants.E)
|
||||
|
||||
buttons = Tkinter.Frame(self)
|
||||
buttons.pack()
|
||||
self.sbotton = Tkinter.Button(buttons, text="Set Prefs", width=14, command=self.setprefs)
|
||||
self.sbotton.pack(side=Tkconstants.LEFT)
|
||||
|
||||
buttons.pack()
|
||||
self.pbotton = Tkinter.Button(buttons, text="Process eBook", width=14, command=self.doit)
|
||||
self.pbotton.pack(side=Tkconstants.LEFT)
|
||||
buttons.pack()
|
||||
self.qbotton = Tkinter.Button(buttons, text="Quit", width=14, command=self.quitting)
|
||||
self.qbotton.pack(side=Tkconstants.RIGHT)
|
||||
buttons.pack()
|
||||
|
||||
def disablebuttons(self):
|
||||
self.sbotton.configure(state='disabled')
|
||||
self.pbotton.configure(state='disabled')
|
||||
self.qbotton.configure(state='disabled')
|
||||
|
||||
def enablebuttons(self):
|
||||
self.sbotton.configure(state='normal')
|
||||
self.pbotton.configure(state='normal')
|
||||
self.qbotton.configure(state='normal')
|
||||
|
||||
def show(self):
|
||||
self.deiconify()
|
||||
self.tkraise()
|
||||
|
||||
def hide(self):
|
||||
self.withdraw()
|
||||
|
||||
def get_outpath(self):
|
||||
cpath = self.outpath.get()
|
||||
if sys.platform.startswith("win"):
|
||||
# tk_chooseDirectory is horribly broken for unicode paths
|
||||
# on windows - bug has been reported but not fixed for years
|
||||
# workaround by using our own unicode aware version
|
||||
outpath = AskFolder(message="Choose the folder for DRM-free ebooks",
|
||||
defaultLocation=cpath)
|
||||
else:
|
||||
outpath = tkFileDialog.askdirectory(
|
||||
parent=None, title='Choose the folder for DRM-free ebooks',
|
||||
initialdir=cpath, initialfile=None)
|
||||
if outpath:
|
||||
outpath = os.path.normpath(outpath)
|
||||
self.outpath.delete(0, Tkconstants.END)
|
||||
self.outpath.insert(0, outpath)
|
||||
return
|
||||
|
||||
def get_adkpath(self):
|
||||
cpath = self.adkpath.get()
|
||||
adkpath = tkFileDialog.askopenfilename(initialdir = cpath, parent=None, title='Select Adept Key file',
|
||||
defaultextension='.der', filetypes=[('Adept Key file', '.der'), ('All Files', '.*')])
|
||||
if adkpath:
|
||||
adkpath = os.path.normpath(adkpath)
|
||||
self.adkpath.delete(0, Tkconstants.END)
|
||||
self.adkpath.insert(0, adkpath)
|
||||
return
|
||||
|
||||
def get_kkpath(self):
|
||||
cpath = self.kkpath.get()
|
||||
kkpath = tkFileDialog.askopenfilename(initialdir = cpath, parent=None, title='Select Kindle Key file',
|
||||
defaultextension='.k4i', filetypes=[('Kindle Key file', '.k4i'), ('All Files', '.*')])
|
||||
if kkpath:
|
||||
kkpath = os.path.normpath(kkpath)
|
||||
self.kkpath.delete(0, Tkconstants.END)
|
||||
self.kkpath.insert(0, kkpath)
|
||||
return
|
||||
|
||||
def get_akkpath(self):
|
||||
cpath = self.akkpath.get()
|
||||
akkpath = tkFileDialog.askopenfilename(initialdir = cpath, parent=None, title='Select Android for Kindle backup file',
|
||||
defaultextension='.ab', filetypes=[('Kindle for Android backup file', '.ab'), ('All Files', '.*')])
|
||||
if akkpath:
|
||||
akkpath = os.path.normpath(akkpath)
|
||||
self.akkpath.delete(0, Tkconstants.END)
|
||||
self.akkpath.insert(0, akkpath)
|
||||
return
|
||||
|
||||
def get_bnkpath(self):
|
||||
cpath = self.bnkpath.get()
|
||||
bnkpath = tkFileDialog.askopenfilename(initialdir = cpath, parent=None, title='Select Barnes and Noble Key file',
|
||||
defaultextension='.b64', filetypes=[('Barnes and Noble Key file', '.b64'), ('All Files', '.*')])
|
||||
if bnkpath:
|
||||
bnkpath = os.path.normpath(bnkpath)
|
||||
self.bnkpath.delete(0, Tkconstants.END)
|
||||
self.bnkpath.insert(0, bnkpath)
|
||||
return
|
||||
|
||||
def get_bookpath(self):
|
||||
cpath = self.bookpath.get()
|
||||
bookpath = tkFileDialog.askopenfilename(parent=None, title='Select eBook for DRM Removal',
|
||||
filetypes=[('All Files', '.*'),
|
||||
('ePub Files','.epub'),
|
||||
('Kindle','.azw'),
|
||||
('Kindle','.azw1'),
|
||||
('Kindle','.azw3'),
|
||||
('Kindle','.azw4'),
|
||||
('Kindle','.tpz'),
|
||||
('Kindle','.azw8'),
|
||||
('Kindle','.kfx'),
|
||||
('Kindle','.kfx-zip'),
|
||||
('Kindle','.mobi'),
|
||||
('Kindle','.prc'),
|
||||
('eReader','.pdb'),
|
||||
('PDF','.pdf')],
|
||||
initialdir=cpath)
|
||||
if bookpath:
|
||||
bookpath = os.path.normpath(bookpath)
|
||||
self.bookpath.delete(0, Tkconstants.END)
|
||||
self.bookpath.insert(0, bookpath)
|
||||
return
|
||||
|
||||
def quitting(self):
|
||||
self.master.destroy()
|
||||
|
||||
def setprefs(self):
|
||||
# setting new prefereces
|
||||
new_prefs = {}
|
||||
prefdir = self.prefs_array['dir']
|
||||
new_prefs['dir'] = prefdir
|
||||
new_prefs['pids'] = self.pidinfo.get().replace(" ","")
|
||||
new_prefs['serials'] = self.serinfo.get().replace(" ","")
|
||||
new_prefs['sdrms'] = self.sdrminfo.get().strip().replace(", ",",")
|
||||
new_prefs['outdir'] = self.outpath.get().strip()
|
||||
adkpath = self.adkpath.get()
|
||||
if os.path.dirname(adkpath) != prefdir:
|
||||
new_prefs['adkfile'] = adkpath
|
||||
bnkpath = self.bnkpath.get()
|
||||
if os.path.dirname(bnkpath) != prefdir:
|
||||
new_prefs['bnkfile'] = bnkpath
|
||||
kkpath = self.kkpath.get()
|
||||
if os.path.dirname(kkpath) != prefdir:
|
||||
new_prefs['kindlefile'] = kkpath
|
||||
akkpath = self.akkpath.get()
|
||||
if os.path.dirname(akkpath) != prefdir:
|
||||
new_prefs['androidfile'] = akkpath
|
||||
self.master.setPreferences(new_prefs)
|
||||
# and update internal copies
|
||||
self.prefs_array['pids'] = new_prefs['pids']
|
||||
self.prefs_array['serials'] = new_prefs['serials']
|
||||
self.prefs_array['sdrms'] = new_prefs['sdrms']
|
||||
self.prefs_array['outdir'] = new_prefs['outdir']
|
||||
|
||||
def doit(self):
|
||||
self.disablebuttons()
|
||||
filenames=[]
|
||||
bookpath = self.bookpath.get()
|
||||
bookpath = os.path.abspath(bookpath)
|
||||
filenames.append(bookpath)
|
||||
self.master.cd.doit(self.prefs_array,filenames)
|
||||
|
||||
|
||||
|
||||
class ConvDialog(Toplevel):
|
||||
def __init__(self, master, prefs_array={}, filenames=[]):
|
||||
Toplevel.__init__(self, master)
|
||||
self.withdraw()
|
||||
self.protocol("WM_DELETE_WINDOW", self.withdraw)
|
||||
self.title("DeDRM Processing")
|
||||
self.master = master
|
||||
self.apphome = self.master.apphome
|
||||
self.prefs_array = prefs_array
|
||||
self.filenames = filenames
|
||||
self.interval = 50
|
||||
self.p2 = None
|
||||
self.q = Queue()
|
||||
self.running = 'inactive'
|
||||
self.numgood = 0
|
||||
self.numbad = 0
|
||||
self.status = Tkinter.Label(self, text='DeDRM processing...')
|
||||
self.status.pack(fill=Tkconstants.X, expand=1)
|
||||
body = Tkinter.Frame(self)
|
||||
body.pack(fill=Tkconstants.X, expand=1)
|
||||
sticky = Tkconstants.E + Tkconstants.W
|
||||
body.grid_columnconfigure(1, weight=2)
|
||||
|
||||
Tkinter.Label(body, text='Activity Bar').grid(row=0, sticky=Tkconstants.E)
|
||||
self.bar = ActivityBar(body, length=80, height=15, barwidth=5)
|
||||
self.bar.grid(row=0, column=1, sticky=sticky)
|
||||
|
||||
msg1 = ''
|
||||
self.stext = ScrolledText(body, bd=5, relief=Tkconstants.RIDGE, height=4, width=80, wrap=Tkconstants.WORD)
|
||||
self.stext.grid(row=2, column=0, columnspan=2,sticky=sticky)
|
||||
self.stext.insert(Tkconstants.END,msg1)
|
||||
|
||||
buttons = Tkinter.Frame(self)
|
||||
buttons.pack()
|
||||
self.qbutton = Tkinter.Button(buttons, text="Quit", width=14, command=self.quitting)
|
||||
self.qbutton.pack(side=Tkconstants.BOTTOM)
|
||||
self.status['text'] = ''
|
||||
|
||||
self.logfile = open(os.path.join(os.path.expanduser('~'),'DeDRM.log'),'w')
|
||||
|
||||
def show(self):
|
||||
self.deiconify()
|
||||
self.tkraise()
|
||||
|
||||
def hide(self):
|
||||
self.withdraw()
|
||||
|
||||
def doit(self, prefs, filenames):
|
||||
self.running = 'inactive'
|
||||
self.prefs_array = prefs
|
||||
self.filenames = filenames
|
||||
self.show()
|
||||
self.processBooks()
|
||||
|
||||
def conversion_done(self):
|
||||
self.hide()
|
||||
self.master.alldone()
|
||||
|
||||
def processBooks(self):
|
||||
while self.running == 'inactive':
|
||||
rscpath = self.prefs_array['dir']
|
||||
filename = None
|
||||
if len(self.filenames) > 0:
|
||||
filename = self.filenames.pop(0)
|
||||
if filename == None:
|
||||
msg = 'Complete: '
|
||||
msg += 'Successes: %d, ' % self.numgood
|
||||
msg += 'Failures: %d\n' % self.numbad
|
||||
self.showCmdOutput(msg)
|
||||
if self.numbad == 0:
|
||||
self.after(2000,self.conversion_done())
|
||||
self.logfile.write("DeDRM v{0}: {1}".format(__version__,msg))
|
||||
self.logfile.close()
|
||||
return
|
||||
infile = filename
|
||||
bname = os.path.basename(infile)
|
||||
msg = 'Processing: ' + bname + '...'
|
||||
self.logfile.write("DeDRM v{0}: {1}\n".format(__version__,msg))
|
||||
self.showCmdOutput(msg)
|
||||
outdir = os.path.dirname(filename)
|
||||
if 'outdir' in self.prefs_array:
|
||||
dpath = self.prefs_array['outdir']
|
||||
if dpath.strip() != '':
|
||||
outdir = dpath
|
||||
rv = self.decrypt_ebook(infile, outdir, rscpath)
|
||||
if rv == 0:
|
||||
self.bar.start()
|
||||
self.running = 'active'
|
||||
self.processQueue()
|
||||
else:
|
||||
msg = 'Unknown File: ' + bname + '\n'
|
||||
self.logfile.write("DeDRM v{0}: {1}".format(__version__,msg))
|
||||
self.showCmdOutput(msg)
|
||||
self.numbad += 1
|
||||
|
||||
def quitting(self):
|
||||
# kill any still running subprocess
|
||||
self.running = 'stopped'
|
||||
if self.p2 != None:
|
||||
if (self.p2.exitcode == None):
|
||||
self.p2.terminate()
|
||||
self.conversion_done()
|
||||
|
||||
# post output from subprocess in scrolled text widget
|
||||
def showCmdOutput(self, msg):
|
||||
if msg and msg !='':
|
||||
if sys.platform.startswith('win'):
|
||||
msg = msg.replace('\r\n','\n')
|
||||
self.stext.insert(Tkconstants.END,msg)
|
||||
self.stext.yview_pickplace(Tkconstants.END)
|
||||
return
|
||||
|
||||
# read from subprocess pipe without blocking
|
||||
# invoked every interval via the widget "after"
|
||||
# option being used, so need to reset it for the next time
|
||||
def processQueue(self):
|
||||
if self.p2 == None:
|
||||
# nothing to wait for so just return
|
||||
return
|
||||
poll = self.p2.exitcode
|
||||
#print "processing", poll
|
||||
done = False
|
||||
text = ''
|
||||
while not done:
|
||||
try:
|
||||
data = self.q.get_nowait()
|
||||
text += data
|
||||
except Empty:
|
||||
done = True
|
||||
if text != '':
|
||||
self.logfile.write(text)
|
||||
if poll != None:
|
||||
self.bar.stop()
|
||||
if poll == 0:
|
||||
msg = 'Success\n'
|
||||
self.numgood += 1
|
||||
else:
|
||||
msg = 'Failed\n'
|
||||
self.numbad += 1
|
||||
self.p2.join()
|
||||
self.logfile.write("DeDRM v{0}: {1}\n".format(__version__,msg))
|
||||
self.showCmdOutput(msg)
|
||||
self.p2 = None
|
||||
self.running = 'inactive'
|
||||
self.after(50,self.processBooks)
|
||||
return
|
||||
# make sure we get invoked again by event loop after interval
|
||||
self.stext.after(self.interval,self.processQueue)
|
||||
return
|
||||
|
||||
def decrypt_ebook(self, infile, outdir, rscpath):
|
||||
q = self.q
|
||||
rv = 1
|
||||
name, ext = os.path.splitext(os.path.basename(infile))
|
||||
ext = ext.lower()
|
||||
if ext == '.epub':
|
||||
self.p2 = Process(target=processEPUB, args=(q, infile, outdir, rscpath))
|
||||
self.p2.start()
|
||||
return 0
|
||||
if ext == '.pdb':
|
||||
self.p2 = Process(target=processPDB, args=(q, infile, outdir, rscpath))
|
||||
self.p2.start()
|
||||
return 0
|
||||
if ext in ['.azw', '.azw1', '.azw3', '.azw4', '.prc', '.mobi', '.pobi', '.tpz', '.azw8', '.kfx', '.kfx-zip']:
|
||||
self.p2 = Process(target=processK4MOBI,args=(q, infile, outdir, rscpath))
|
||||
self.p2.start()
|
||||
return 0
|
||||
if ext == '.pdf':
|
||||
self.p2 = Process(target=processPDF, args=(q, infile, outdir, rscpath))
|
||||
self.p2.start()
|
||||
return 0
|
||||
return rv
|
||||
|
||||
|
||||
# child process starts here
|
||||
def processK4MOBI(q, infile, outdir, rscpath):
|
||||
add_cp65001_codec()
|
||||
set_utf8_default_encoding()
|
||||
sys.stdout = QueuedUTF8Stream(sys.stdout, q)
|
||||
sys.stderr = QueuedUTF8Stream(sys.stderr, q)
|
||||
rv = decryptk4mobi(infile, outdir, rscpath)
|
||||
sys.exit(rv)
|
||||
|
||||
# child process starts here
|
||||
def processPDF(q, infile, outdir, rscpath):
|
||||
add_cp65001_codec()
|
||||
set_utf8_default_encoding()
|
||||
sys.stdout = QueuedUTF8Stream(sys.stdout, q)
|
||||
sys.stderr = QueuedUTF8Stream(sys.stderr, q)
|
||||
rv = decryptpdf(infile, outdir, rscpath)
|
||||
sys.exit(rv)
|
||||
|
||||
# child process starts here
|
||||
def processEPUB(q, infile, outdir, rscpath):
|
||||
add_cp65001_codec()
|
||||
set_utf8_default_encoding()
|
||||
sys.stdout = QueuedUTF8Stream(sys.stdout, q)
|
||||
sys.stderr = QueuedUTF8Stream(sys.stderr, q)
|
||||
rv = decryptepub(infile, outdir, rscpath)
|
||||
sys.exit(rv)
|
||||
|
||||
# child process starts here
|
||||
def processPDB(q, infile, outdir, rscpath):
|
||||
add_cp65001_codec()
|
||||
set_utf8_default_encoding()
|
||||
sys.stdout = QueuedUTF8Stream(sys.stdout, q)
|
||||
sys.stderr = QueuedUTF8Stream(sys.stderr, q)
|
||||
rv = decryptpdb(infile, outdir, rscpath)
|
||||
sys.exit(rv)
|
||||
|
||||
|
||||
def main():
|
||||
argv=unicode_argv()
|
||||
apphome = os.path.dirname(argv[0])
|
||||
apphome = os.path.abspath(apphome)
|
||||
|
||||
# windows may pass a spurious quoted null string as argv[1] from bat file
|
||||
# simply work around this until we can figure out a better way to handle things
|
||||
if sys.platform.startswith('win') and len(argv) == 2:
|
||||
temp = argv[1]
|
||||
temp = temp.strip('"')
|
||||
temp = temp.strip()
|
||||
if temp == '':
|
||||
argv.pop()
|
||||
|
||||
if len(argv) == 1:
|
||||
filenames = []
|
||||
dnd = False
|
||||
|
||||
else : # processing books via drag and drop
|
||||
dnd = True
|
||||
# build a list of the files to be processed
|
||||
# note all filenames and paths have been utf-8 encoded
|
||||
infilelst = argv[1:]
|
||||
filenames = []
|
||||
for infile in infilelst:
|
||||
infile = infile.replace('"','')
|
||||
infile = os.path.abspath(infile)
|
||||
if os.path.isdir(infile):
|
||||
bpath = infile
|
||||
filelst = os.listdir(infile)
|
||||
for afile in filelst:
|
||||
if not afile.startswith('.'):
|
||||
filepath = os.path.join(bpath,afile)
|
||||
if os.path.isfile(filepath):
|
||||
filenames.append(filepath)
|
||||
else :
|
||||
afile = os.path.basename(infile)
|
||||
if not afile.startswith('.'):
|
||||
if os.path.isfile(infile):
|
||||
filenames.append(infile)
|
||||
|
||||
# start up gui app
|
||||
app = MainApp(apphome, dnd, filenames)
|
||||
app.mainloop()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
65
contrib/DeDRM_Windows_Application/DeDRM_App_ReadMe.txt
Normal file
65
contrib/DeDRM_Windows_Application/DeDRM_App_ReadMe.txt
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
DeDRM_App - DeDRM_App.pyw and DeDRM_Drop_Target.bat
|
||||
===================================================
|
||||
|
||||
DeDRM_App.pyw is a python drag and drop application that allows users to drag and drop ebooks or folders of ebooks onto the DeDRM_Drop_Target.bat to have the DRM removed. It repackages all the tools (except obok) in one easy to use program that remembers preferences and settings.
|
||||
|
||||
It will work without manual configuration for Kindle for PC ebooks, Adobe Digital Edition (2.0.1) epub and pdf ebooks and Barnes & Noble NOOK Study ePubs when Kindle for PC, Adobe Digital Editions and NOOK Study are installed on the same computer and user account.
|
||||
|
||||
To remove the DRM from eInk Kindle ebooks, Mobipocket ebooks and Fictionwise eReader ebooks requires the user to double-click the DeDRM_Drop_Target.bat file and set some additional Preferences including:
|
||||
|
||||
eInk Kindle: 16 digit Serial Number
|
||||
MobiPocket: 10 digit PID
|
||||
eReader Social DRM: Name:Last 8 digits of CC number
|
||||
|
||||
Once these preferences have been set, the user can simply drag and drop ebooks onto the DeDRM_Drop_Target to remove the DRM. Note that after setting preferences it is necessary to click on "Set Prefs" button and then quit the application for the change in preferences to fully take effect.
|
||||
|
||||
This program requires that Python 2.7 and PyCrypto 2.6 for Python 2.7 be installed on your computer before it will work. See below for how to get and install these programs for Windows.
|
||||
|
||||
|
||||
Installation
|
||||
------------
|
||||
0. If you don't already have a correct version of Python and PyCrypto installed, follow the "Installing Python on Windows" and "Installing PyCrypto on Windows" sections below before continuing.
|
||||
|
||||
1. Drag the DeDRM_App folder from DeDRM_Application_Windows to your "My Documents" folder.
|
||||
|
||||
2. Open the DeDRM_App folder you've just dragged, and make a short-cut of the DeDRM_Drop_Target.bat file (right-click/Create Shortcut). Drag the shortcut file onto your Desktop.
|
||||
|
||||
3. To set the preferences simply double-click on the short-cut you've just created.
|
||||
|
||||
|
||||
Credits
|
||||
-------
|
||||
The original inept and ignoble scripts were by i♥cabbages
|
||||
The original mobidedrm and erdr2pml scripts were by The Dark Reverser
|
||||
The original topaz DRM removal script was by CMBDTC
|
||||
The original topaz format conversion scripts were by some_updates, clarknova and Bart Simpson
|
||||
|
||||
The alfcrypto library is by some_updates
|
||||
The ePub encryption detection script is by Apprentice Alf, adapted from a script by Paul Durrant
|
||||
The ignoblekey script is by Apprentice Harper
|
||||
The DeDRM python GUI was by some_updates and is maintained by Apprentice Alf and Apprentice Harper
|
||||
|
||||
Many fixes, updates and enhancements to the scripts and applicatons have been made by many other people. For more details, see the commments in the individual scripts.
|
||||
|
||||
|
||||
Installing Python on Windows
|
||||
----------------------------
|
||||
I strongly recommend fully installing ActiveState’s Active Python, free Community Edition for Windows. This is a free, full version of the Python. It comes with some important additional modules that are not included in the bare-bones version from www.python.org unless you choose to install everything.
|
||||
|
||||
1. Download ActivePython 2.7.8 for Windows (or later 2.7.x version for Windows, but NOT 3.x) from http://www.activestate.com/activepython/downloads.
|
||||
|
||||
2. When it has finished downloading, run the installer. Accept the default options.
|
||||
|
||||
|
||||
Installing PyCrypto on Windows
|
||||
------------------------------
|
||||
PyCrypto is a set of encryption/decryption routines that work with Python. The sources are freely available, and compiled versions are available from several sources. You must install a version that is for Python 2.7. I recommend the installer linked from Michael Foord’s blog.
|
||||
|
||||
1. Download PyCrypto 2.6 (or later) for Windows and Python 2.7 from http://www.voidspace.org.uk/python/modules.shtml#pycrypto
|
||||
|
||||
2. When it has finished downloading, run the application. Accept the default options.
|
||||
|
||||
|
||||
Linux Users
|
||||
===========
|
||||
The DeDRM_app.pyw script, although not the .bat shortcut, should work under Linux. Drag & drop functionality is not available. Depending on your Linux installation, you may or may not need to install Python 2 and PyCrypto.
|
||||
111
contrib/DeDRM_calibre_plugin/DeDRM_plugin_ReadMe.txt
Normal file
111
contrib/DeDRM_calibre_plugin/DeDRM_plugin_ReadMe.txt
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
DeDRM_plugin.zip
|
||||
================
|
||||
|
||||
This calibre plugin replaces many previously separate DRM removal plugins. Before you install this plugin, you should uninstall any older individual DRM removal plugins, e.g. K4MobiDeDRM. The exception is the obok plugin, which should not be removed.
|
||||
|
||||
This plugin will remove the DRM from
|
||||
- Kindle ebooks (files from Kindle for Mac/PC* and eInk Kindles**).
|
||||
- Barnes and Noble ePubs
|
||||
- Adobe Digital Editions (v2.0.1***) ePubs (including Kobo and Google ePubs downloaded to ADE)
|
||||
- Adobe Digital Editions (v2.0.1) PDFs
|
||||
- Mobipocket ebooks
|
||||
- eReader PDB books
|
||||
|
||||
These tools do NOT work with kepubs downloaded using Kobo's desktop app (see the separate obok plugin) nor Apple's iBooks FairPlay DRM (see details about Requiem at the end of this file.)
|
||||
|
||||
* With Kindle for PC/Mac 1.19 and later, Amazon included support for their new KFX format. While the tools now include a first attempt at supporting drm removal for KFX format, we recommend using Kindle for PC/Mac 1.17 or earlier which prevents downloads of the new format, as conversions from the olde KF8 format are likely to be more successful.
|
||||
|
||||
** Some later Kindles support Amazon's new KFX format. And some books download in a split azw3/azw6 format. For best results, instead of using files downloaded directly to your Kindle, download from Amazon's web site 'for transfer via USB'. This will give you an single file to import. See also the FAQ entry about this.
|
||||
|
||||
*** With Adobe Digital Editions 3.0 and later, Adobe have introduced a new, optional, DRM scheme. To avoid this new scheme, you should use Adobe Digital Editions 2.0.1. Some books are required to use the new DRM scheme and so will not download with ADE 2.0.1. If you still want such a book, you will need to use ADE 3.0 or later to download it, but you should remember that no tools to remove Adobe's new DRM scheme exist as of October 2017.
|
||||
|
||||
|
||||
Installation
|
||||
------------
|
||||
Open calibre's Preferences dialog. Click on the "Plugins" button. Next, click on the button, "Load plugin from file". Navigate to the unzipped DeDRM_tools folder and, in the folder "DeDRM_calibre_plugin", find the file "DeDRM_plugin.zip". Click to select the file and select "Open". Click "Yes" in the "Are you sure?" dialog box. Click the "OK" button in the "Success" dialog box.
|
||||
|
||||
|
||||
Customization
|
||||
-------------
|
||||
You MUST add some key information for the following kinds of ebooks:
|
||||
- Kindle ebooks from an E-Ink based Kindle (e.g. Voyage).
|
||||
- Barnes & Noble ePubs other than those downloaded using NOOK Study
|
||||
- Mobipocket ebooks
|
||||
- eReader PDB books
|
||||
|
||||
You do not need to add any key information for eBooks
|
||||
- downloaded using Kindle for Mac/PC
|
||||
- downloaded using Adobe Digital Editions (v2.0.1)
|
||||
- downloaded using NOOK Study
|
||||
as the necessary keys are automatically retrieved from files on your computer.
|
||||
|
||||
To add needed key information for other books, highlight the plugin (DeDRM under the "File type plugins" category) and click the "Customize Plugin" button.
|
||||
|
||||
The buttons in the configuration dialog will open individual configuration dialogs that will allow you to enter the needed information, depending on the type and source of your DRMed eBooks. Additional help on the information required is available in each of the the dialogs vias the [?] help button.
|
||||
|
||||
If you have used previous versions of the various DeDRM plugins on this machine, you may find that some of the configuration dialogs already contain the information you entered through those previous plugins.
|
||||
|
||||
When you have finished entering your configuration information, you must click the OK button to save it. If you click the Cancel button, all your changes in all the configuration dialogs will be lost.
|
||||
|
||||
|
||||
Troubleshooting
|
||||
---------------
|
||||
If you find that the DeDRM plugin is not working for you (imported ebooks still have DRM - that is, they won't convert or open in the calibre ebook viewer), you should make a log of the import process by deleting the DRMed ebook from calibre and then adding the ebook to calibre when it's running in debug mode. This will generate a lot of helpful debugging info that can be copied into any online help requests. Here's how to do it:
|
||||
|
||||
- Remove the DRMed book from calibre.
|
||||
- Click the Preferences drop-down menu and choose 'Restart in debug mode'.
|
||||
- Once calibre has re-started, import the problem ebook.
|
||||
- Now close calibre.
|
||||
|
||||
A log will appear that you can copy and paste into a comment at Apprentice Alf's blog, http://apprenticealf.wordpress.com/ or an issue at Apprentice Harper's repository, https://github.com/apprenticeharper/DeDRM_tools/issues . You should also give details of your computer, and how you obtained the ebook file.
|
||||
|
||||
|
||||
Credits
|
||||
-------
|
||||
The original inept and ignoble scripts were by i♥cabbages
|
||||
The original mobidedrm and erdr2pml scripts were by The Dark Reverser
|
||||
The original topaz DRM removal script was by CMBDTC
|
||||
The original topaz format conversion scripts were by some_updates, clarknova and Bart Simpson
|
||||
The original obok script was by Physisticated
|
||||
The original KFX format decryption was by lulzkabulz, converted to python by Apprentice Naomi and integrated into the tools by tomthumb1997
|
||||
|
||||
The alfcrypto library is by some_updates
|
||||
The ePub encryption detection script is by Apprentice Alf, adapted from a script by Paul Durrant
|
||||
The ignoblekey script is by Apprentice Harper
|
||||
The DeDRM plugin was based on plugins by DiapDealer and is maintained by Apprentice Alf and Apprentice Harper
|
||||
|
||||
Many fixes, updates and enhancements to the scripts and applicatons have been made by many other people. For more details, see the commments in the individual scripts.
|
||||
|
||||
|
||||
Linux Systems Only
|
||||
==================
|
||||
|
||||
Instructions for installing Wine, Kindle for PC, Adobe Digital Editions, Python and PyCrypto
|
||||
--------------------------------------------------------------------------------------------
|
||||
|
||||
These instructions have been tested with Wine 1.4 on Ubuntu but are now very out of date.
|
||||
|
||||
1. First download the software you're going to to have to install.
|
||||
a. Adobe Digital Editions 1.7.x from http://helpx.adobe.com/digital-editions/kb/cant-install-digital-editions.html
|
||||
(Adobe Digital Editions 2.x doesn't work with Wine.)
|
||||
b. Python 2.7.X for Windows (x86) from https://www.python.org/ftp/python/2.7.13/python-2.7.13.msi
|
||||
c. PyCrypto 2.1 for 32bit Windows and Python 2.7 from http://www.voidspace.org.uk/python/modules.shtml#pycrypto
|
||||
(PyCrypto downloads as a zip file. You will need to unzip it.)
|
||||
2. Install Wine for 32-bit x86. (e.g. on Ubuntu, Open the Ubuntu Software Center, search for Wine, and install "Wine Windows Program Loader".)
|
||||
2a. [update] Kindle for PC now requires Windows 7, so in the following setups, choose any option for Windows 7, not Windows XP.
|
||||
3. Run "Configure Wine", which will set up the default 'wineprefix'
|
||||
4. Navigate to "Install an application" and install Kindle. Alternatively, run `winetricks kindle`
|
||||
5. Install Adobe Digital Editions. Accept all defaults and register with your Adobe ID.
|
||||
6. Install Python 2.7.x using `msiexec /i python-2.7.8.msi`. Accept all defaults.
|
||||
7. Install PyCrypto 2.1. Accept all defaults.
|
||||
8. Unzip DeDRM_plugin.zip and move kindlekey.py to somewhere in drive_c, such as ~/.wine/drive_c/DeDRM/libraryfiles/kindlekey.py.
|
||||
9. Run `wine 'C:\Python27/python.exe' 'C:\DeDRM/libraryfiles/kindlekey.py'`, or wherever you copied kindlekey.py to.
|
||||
10. Import the resulting key file to the Calibre plugin through the Kindle for Mac/PC ebooks option.
|
||||
|
||||
|
||||
Instructions for getting Kindle for PC and Adobe Digital Editions default decryption keys
|
||||
-----------------------------------------------------------------------------------------
|
||||
|
||||
If everything has been installed in wine as above, the keys will be retrieved automatically.
|
||||
|
||||
If you have a more complex wine installation, you may enter the appropriate WINEPREFIX in the configuration dialogs for Kindle for PC and Adobe Digital Editions. You can also test that you have entered the WINEPREFIX correctly by trying to add the default keys to the preferences by clicking on the green plus button in the configuration dialogs.
|
||||
53
contrib/Obok_calibre_plugin/obok_plugin_ReadMe.txt
Normal file
53
contrib/Obok_calibre_plugin/obok_plugin_ReadMe.txt
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
obok_plugin.zip
|
||||
================
|
||||
|
||||
This plugin will remove the DRM from Kobo ebooks download on Mac or Windows using the Kobo desktop application, or from Kobo ebooks on an attached E-Ink Kobo reader (but not a Kobo Arc or Kobo Vox). If both are available, ebooks will be read from the attached E-Ink Kobo reader. To import from the desktop application, unplug the Kobo reader.
|
||||
|
||||
|
||||
Installation
|
||||
------------
|
||||
Open calibre's Preferences dialog. Click on the "Plugins" button. Next, click on the button, "Load plugin from file". Navigate to the unzipped DeDRM_tools folder and, in the folder "obok_calibre_plugin", find the file "obok_plugin.zip". Click to select the file and select "Open". Click "Yes" in the "Are you sure?" dialog box. Click the "OK" button in the "Success" dialog box.
|
||||
|
||||
|
||||
Customization
|
||||
-------------
|
||||
No customization is required, except choosing which menus will show the plugin. Altough the ability to enter a device serial number is given, this should not need to be filled in, as the serial number should be picked up automatically from the attached Kobo reader.
|
||||
|
||||
|
||||
Using the plugin
|
||||
----------------
|
||||
|
||||
Select the plugin's menu or icon from whichever part of the calibre interface you have chosen to have it. Follow the instructions in the dialog that appears.
|
||||
|
||||
|
||||
Troubleshooting
|
||||
---------------
|
||||
If you find that it's not working for you (imported ebooks still have DRM - that is, they won't convert or open in the calibre ebook viewer), you should make a log of import process by deleting the DRMed ebook from calibre and then adding the ebook to calibre when it's running in debug mode. This will generate a lot of helpful debugging info that can be copied into any online help requests. Here's how to do it:
|
||||
|
||||
On Windows, open a terminal/command window. (Start/Run… and then type 'cmd.exe' (without the 's) as the program to run).
|
||||
On Macintosh, open the Terminal application (in your Utilities folder).
|
||||
On Linux open a command window. Hopefully all Linux users know how to do this.
|
||||
|
||||
You should now have a text-based command-line window open.
|
||||
|
||||
Type in "calibre-debug -g" (without the "s but with the space before the -g) and press the return/enter key. Calibre will launch and run as normal, but with debugging information output to the terminal window.
|
||||
|
||||
Import the DRMed eBook into calibre in any of the the normal ways. (I usually drag&drop onto the calibre window.)
|
||||
|
||||
Debug information will be written to the terminal window.
|
||||
|
||||
Copy the output from the terminal window.
|
||||
On Windows, you must use the window menu (little icon at left of window bar) to select all the text and then to copy it.
|
||||
On Macintosh and Linux, just use the normal text select and copy commands.
|
||||
|
||||
Paste the information into a comment at my blog, http://apprenticealf.wordpress.com/ describing your problem.
|
||||
|
||||
|
||||
Credits
|
||||
-------
|
||||
The original obok script was by Physisticated
|
||||
The plugin conversion was done anonymously.
|
||||
The Kobo reader support was added by norbusan
|
||||
|
||||
Additional improvements to the script and the plugin adaption by numerous anonymous people.
|
||||
|
||||
|
|
@ -68,20 +68,12 @@ class SafeUnbuffered:
|
|||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
|
|
@ -137,10 +129,7 @@ if iswindows:
|
|||
c_long, c_ulong
|
||||
|
||||
from ctypes.wintypes import LPVOID, DWORD, BOOL
|
||||
try:
|
||||
import winreg
|
||||
except ImportError:
|
||||
import _winreg as winreg
|
||||
import _winreg as winreg
|
||||
|
||||
def _load_crypto_libcrypto():
|
||||
from ctypes.util import find_library
|
||||
|
|
@ -4,7 +4,7 @@
|
|||
from __future__ import with_statement
|
||||
|
||||
# ignoblekey.py
|
||||
# Copyright © 2015-2020 Apprentice Harper et al.
|
||||
# Copyright © 2015 Apprentice Alf and Apprentice Harper
|
||||
|
||||
# Based on kindlekey.py, Copyright © 2010-2013 by some_updates and Apprentice Alf
|
||||
|
||||
|
|
@ -14,14 +14,13 @@ from __future__ import with_statement
|
|||
# Revision history:
|
||||
# 1.0 - Initial release
|
||||
# 1.1 - remove duplicates and return last key as single key
|
||||
# 2.0 - Python 3
|
||||
|
||||
"""
|
||||
Get Barnes & Noble EPUB user key from nook Studio log file
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = "2.0"
|
||||
__version__ = "1.1"
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
|
@ -39,20 +38,12 @@ class SafeUnbuffered:
|
|||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
|
|
@ -106,10 +97,7 @@ def getNookLogFiles():
|
|||
logFiles = []
|
||||
found = False
|
||||
if iswindows:
|
||||
try:
|
||||
import winreg
|
||||
except ImportError:
|
||||
import _winreg as winreg
|
||||
import _winreg as winreg
|
||||
|
||||
# some 64 bit machines do not have the proper registry key for some reason
|
||||
# or the python interface to the 32 vs 64 bit registry is broken
|
||||
|
|
@ -330,7 +318,7 @@ def gui_main():
|
|||
keyfileout.write(key)
|
||||
success = True
|
||||
tkMessageBox.showinfo(progname, u"Key successfully retrieved to {0}".format(outfile))
|
||||
except DrmException as e:
|
||||
except DrmException, e:
|
||||
tkMessageBox.showerror(progname, u"Error: {0}".format(str(e)))
|
||||
except Exception:
|
||||
root.wm_state('normal')
|
||||
|
|
@ -45,20 +45,12 @@ class SafeUnbuffered:
|
|||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
|
|
@ -56,20 +56,12 @@ class SafeUnbuffered:
|
|||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
|
|
@ -48,20 +48,12 @@ class SafeUnbuffered:
|
|||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
|
|
@ -51,20 +51,12 @@ class SafeUnbuffered:
|
|||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
|
|
@ -185,10 +177,7 @@ if iswindows:
|
|||
create_unicode_buffer, create_string_buffer, CFUNCTYPE, addressof, \
|
||||
string_at, Structure, c_void_p, cast
|
||||
|
||||
try:
|
||||
import winreg
|
||||
except ImportError:
|
||||
import _winreg as winreg
|
||||
import _winreg as winreg
|
||||
MAX_PATH = 255
|
||||
kernel32 = windll.kernel32
|
||||
advapi32 = windll.advapi32
|
||||
|
|
@ -300,7 +289,7 @@ if iswindows:
|
|||
numBlocks, numExtraBytes = divmod(len(self.bytesToDecrypt), self.blockSize)
|
||||
if more == None: # no more calls to decrypt, should have all the data
|
||||
if numExtraBytes != 0:
|
||||
raise DecryptNotBlockAlignedError('Data not block aligned on decrypt')
|
||||
raise DecryptNotBlockAlignedError, 'Data not block aligned on decrypt'
|
||||
|
||||
# hold back some bytes in case last decrypt has zero len
|
||||
if (more != None) and (numExtraBytes == 0) and (numBlocks >0) :
|
||||
|
|
@ -342,7 +331,7 @@ if iswindows:
|
|||
def removePad(self, paddedBinaryString, blockSize):
|
||||
""" Remove padding from a binary string """
|
||||
if not(0<len(paddedBinaryString)):
|
||||
raise DecryptNotBlockAlignedError('Expected More Data')
|
||||
raise DecryptNotBlockAlignedError, 'Expected More Data'
|
||||
return paddedBinaryString[:-ord(paddedBinaryString[-1])]
|
||||
|
||||
class noPadding(Pad):
|
||||
|
|
@ -372,8 +361,8 @@ if iswindows:
|
|||
self.blockSize = blockSize # blockSize is in bytes
|
||||
self.padding = padding # change default to noPadding() to get normal ECB behavior
|
||||
|
||||
assert( keySize%4==0 and keySize/4 in NrTable[4]),'key size must be 16,20,24,29 or 32 bytes'
|
||||
assert( blockSize%4==0 and blockSize/4 in NrTable), 'block size must be 16,20,24,29 or 32 bytes'
|
||||
assert( keySize%4==0 and NrTable[4].has_key(keySize/4)),'key size must be 16,20,24,29 or 32 bytes'
|
||||
assert( blockSize%4==0 and NrTable.has_key(blockSize/4)), 'block size must be 16,20,24,29 or 32 bytes'
|
||||
|
||||
self.Nb = self.blockSize/4 # Nb is number of columns of 32 bit words
|
||||
self.Nk = keySize/4 # Nk is the key length in 32-bit words
|
||||
|
|
@ -650,7 +639,7 @@ if iswindows:
|
|||
def __init__(self, key = None, padding = padWithPadLen(), keySize=16):
|
||||
""" Initialize AES, keySize is in bytes """
|
||||
if not (keySize == 16 or keySize == 24 or keySize == 32) :
|
||||
raise BadKeySizeError('Illegal AES key size, must be 16, 24, or 32 bytes')
|
||||
raise BadKeySizeError, 'Illegal AES key size, must be 16, 24, or 32 bytes'
|
||||
|
||||
Rijndael.__init__( self, key, padding=padding, keySize=keySize, blockSize=16 )
|
||||
|
||||
|
|
@ -790,11 +779,10 @@ if iswindows:
|
|||
# [c_char_p, c_ulong, c_char_p, c_ulong, c_ulong, c_ulong, c_char_p])
|
||||
def pbkdf2(self, passwd, salt, iter, keylen):
|
||||
|
||||
def xorbytes( a, b ):
|
||||
def xorstr( a, b ):
|
||||
if len(a) != len(b):
|
||||
raise Exception("xorbytes(): lengths differ")
|
||||
return bytes([x ^ y for x, y in zip(a, b)])
|
||||
|
||||
raise Exception("xorstr(): lengths differ")
|
||||
return ''.join((chr(ord(x)^ord(y)) for x, y in zip(a, b)))
|
||||
|
||||
def prf( h, data ):
|
||||
hm = h.copy()
|
||||
|
|
@ -806,13 +794,13 @@ if iswindows:
|
|||
T = U
|
||||
for i in range(2, itercount+1):
|
||||
U = prf( h, U )
|
||||
T = xorbytes( T, U )
|
||||
T = xorstr( T, U )
|
||||
return T
|
||||
|
||||
sha = hashlib.sha1
|
||||
digest_size = sha().digest_size
|
||||
# l - number of output blocks to produce
|
||||
l = keylen // digest_size
|
||||
l = keylen / digest_size
|
||||
if keylen % digest_size != 0:
|
||||
l += 1
|
||||
h = hmac.new( passwd, None, sha )
|
||||
|
|
@ -32,20 +32,12 @@ class SafeUnbuffered:
|
|||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
|
||||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
|
@ -150,10 +150,9 @@
|
|||
# after all.
|
||||
#
|
||||
"""Manage all Kobo books, either encrypted or DRM-free."""
|
||||
from __future__ import print_function
|
||||
|
||||
__version__ = '3.2.4'
|
||||
__about__ = "Obok v{0}\nCopyright © 2012-2016 Physisticated et al.".format(__version__)
|
||||
__about__ = u"Obok v{0}\nCopyright © 2012-2016 Physisticated et al.".format(__version__)
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
|
@ -173,10 +172,10 @@ import tempfile
|
|||
can_parse_xml = True
|
||||
try:
|
||||
from xml.etree import ElementTree as ET
|
||||
# print "using xml.etree for xml parsing"
|
||||
# print u"using xml.etree for xml parsing"
|
||||
except ImportError:
|
||||
can_parse_xml = False
|
||||
# print "Cannot find xml.etree, disabling extraction of serial numbers"
|
||||
# print u"Cannot find xml.etree, disabling extraction of serial numbers"
|
||||
|
||||
# List of all known hash keys
|
||||
KOBO_HASH_KEYS = ['88b3a2e13', 'XzUhGYdFp', 'NoCanLook','QJhwzAtXL']
|
||||
|
|
@ -276,20 +275,12 @@ class SafeUnbuffered:
|
|||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,str) or isinstance(data,unicode):
|
||||
# str for Python3, unicode for Python2
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
buffer = getattr(self.stream, 'buffer', self.stream)
|
||||
# self.stream.buffer for Python3, self.stream for Python2
|
||||
buffer.write(data)
|
||||
buffer.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
raise
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
|
||||
|
||||
class KoboLibrary(object):
|
||||
|
|
@ -300,7 +291,7 @@ class KoboLibrary(object):
|
|||
of books, their titles, and the user's encryption key(s)."""
|
||||
|
||||
def __init__ (self, serials = [], device_path = None):
|
||||
print(__about__)
|
||||
print __about__
|
||||
self.kobodir = u""
|
||||
kobodb = u""
|
||||
|
||||
|
|
@ -317,9 +308,9 @@ class KoboLibrary(object):
|
|||
# step 1. check whether this looks like a real device
|
||||
if (device_path):
|
||||
# we got a device path
|
||||
self.kobodir = os.path.join(device_path, ".kobo")
|
||||
self.kobodir = os.path.join(device_path, u".kobo")
|
||||
# devices use KoboReader.sqlite
|
||||
kobodb = os.path.join(self.kobodir, "KoboReader.sqlite")
|
||||
kobodb = os.path.join(self.kobodir, u"KoboReader.sqlite")
|
||||
if (not(os.path.isfile(kobodb))):
|
||||
# device path seems to be wrong, unset it
|
||||
device_path = u""
|
||||
|
|
@ -331,22 +322,22 @@ class KoboLibrary(object):
|
|||
if (len(serials) == 0):
|
||||
# we got a device path but no saved serial
|
||||
# try to get the serial from the device
|
||||
# print "get_device_settings - device_path = {0}".format(device_path)
|
||||
# print u"get_device_settings - device_path = {0}".format(device_path)
|
||||
# get serial from device_path/.adobe-digital-editions/device.xml
|
||||
if can_parse_xml:
|
||||
devicexml = os.path.join(device_path, '.adobe-digital-editions', 'device.xml')
|
||||
# print "trying to load {0}".format(devicexml)
|
||||
# print u"trying to load {0}".format(devicexml)
|
||||
if (os.path.exists(devicexml)):
|
||||
# print "trying to parse {0}".format(devicexml)
|
||||
# print u"trying to parse {0}".format(devicexml)
|
||||
xmltree = ET.parse(devicexml)
|
||||
for node in xmltree.iter():
|
||||
if "deviceSerial" in node.tag:
|
||||
serial = node.text
|
||||
# print "found serial {0}".format(serial)
|
||||
# print u"found serial {0}".format(serial)
|
||||
serials.append(serial)
|
||||
break
|
||||
else:
|
||||
# print "cannot get serials from device."
|
||||
# print u"cannot get serials from device."
|
||||
device_path = u""
|
||||
self.kobodir = u""
|
||||
kobodb = u""
|
||||
|
|
@ -354,26 +345,23 @@ class KoboLibrary(object):
|
|||
if (self.kobodir == u""):
|
||||
# step 4. we haven't found a device with serials, so try desktop apps
|
||||
if sys.platform.startswith('win'):
|
||||
try:
|
||||
import winreg
|
||||
except ImportError:
|
||||
import _winreg as winreg
|
||||
import _winreg as winreg
|
||||
if sys.getwindowsversion().major > 5:
|
||||
if 'LOCALAPPDATA' in os.environ.keys():
|
||||
# Python 2.x does not return unicode env. Use Python 3.x
|
||||
self.kobodir = winreg.ExpandEnvironmentStrings("%LOCALAPPDATA%")
|
||||
self.kobodir = winreg.ExpandEnvironmentStrings(u"%LOCALAPPDATA%")
|
||||
if (self.kobodir == u""):
|
||||
if 'USERPROFILE' in os.environ.keys():
|
||||
# Python 2.x does not return unicode env. Use Python 3.x
|
||||
self.kobodir = os.path.join(winreg.ExpandEnvironmentStrings("%USERPROFILE%"), "Local Settings", "Application Data")
|
||||
self.kobodir = os.path.join(self.kobodir, "Kobo", "Kobo Desktop Edition")
|
||||
self.kobodir = os.path.join(winreg.ExpandEnvironmentStrings(u"%USERPROFILE%"), u"Local Settings", u"Application Data")
|
||||
self.kobodir = os.path.join(self.kobodir, u"Kobo", u"Kobo Desktop Edition")
|
||||
elif sys.platform.startswith('darwin'):
|
||||
self.kobodir = os.path.join(os.environ['HOME'], "Library", "Application Support", "Kobo", "Kobo Desktop Edition")
|
||||
self.kobodir = os.path.join(os.environ['HOME'], u"Library", u"Application Support", u"Kobo", u"Kobo Desktop Edition")
|
||||
#elif linux_path != None:
|
||||
# Probably Linux, let's get the wine prefix and path to Kobo.
|
||||
# self.kobodir = os.path.join(linux_path, "Local Settings", "Application Data", "Kobo", "Kobo Desktop Edition")
|
||||
# self.kobodir = os.path.join(linux_path, u"Local Settings", u"Application Data", u"Kobo", u"Kobo Desktop Edition")
|
||||
# desktop versions use Kobo.sqlite
|
||||
kobodb = os.path.join(self.kobodir, "Kobo.sqlite")
|
||||
kobodb = os.path.join(self.kobodir, u"Kobo.sqlite")
|
||||
# check for existence of file
|
||||
if (not(os.path.isfile(kobodb))):
|
||||
# give up here, we haven't found anything useful
|
||||
|
|
@ -382,11 +370,11 @@ class KoboLibrary(object):
|
|||
|
||||
|
||||
if (self.kobodir != u""):
|
||||
self.bookdir = os.path.join(self.kobodir, "kepub")
|
||||
self.bookdir = os.path.join(self.kobodir, u"kepub")
|
||||
# make a copy of the database in a temporary file
|
||||
# so we can ensure it's not using WAL logging which sqlite3 can't do.
|
||||
self.newdb = tempfile.NamedTemporaryFile(mode='wb', delete=False)
|
||||
print(self.newdb.name)
|
||||
print self.newdb.name
|
||||
olddb = open(kobodb, 'rb')
|
||||
self.newdb.write(olddb.read(18))
|
||||
self.newdb.write('\x01\x01')
|
||||
|
|
@ -442,7 +430,7 @@ class KoboLibrary(object):
|
|||
|
||||
def __bookfile (self, volumeid):
|
||||
"""The filename needed to open a given book."""
|
||||
return os.path.join(self.kobodir, "kepub", volumeid)
|
||||
return os.path.join(self.kobodir, u"kepub", volumeid)
|
||||
|
||||
def __getmacaddrs (self):
|
||||
"""The list of all MAC addresses on this machine."""
|
||||
|
|
@ -459,7 +447,7 @@ class KoboLibrary(object):
|
|||
output = subprocess.check_output('/sbin/ifconfig -a', shell=True)
|
||||
matches = c.findall(output)
|
||||
for m in matches:
|
||||
# print "m:{0}".format(m[0])
|
||||
# print u"m:{0}".format(m[0])
|
||||
macaddrs.append(m[0].upper())
|
||||
elif sys.platform.startswith('linux'):
|
||||
p_out = subprocess.check_output("ip -br link show | awk '{print $3}'", shell=True)
|
||||
|
|
@ -607,32 +595,32 @@ class KoboFile(object):
|
|||
# assume utf-8 with no BOM
|
||||
textoffset = 0
|
||||
stride = 1
|
||||
print("Checking text:{0}:".format(contents[:10]))
|
||||
print u"Checking text:{0}:".format(contents[:10])
|
||||
# check for byte order mark
|
||||
if contents[:3]=="\xef\xbb\xbf":
|
||||
# seems to be utf-8 with BOM
|
||||
print("Could be utf-8 with BOM")
|
||||
print u"Could be utf-8 with BOM"
|
||||
textoffset = 3
|
||||
elif contents[:2]=="\xfe\xff":
|
||||
# seems to be utf-16BE
|
||||
print("Could be utf-16BE")
|
||||
print u"Could be utf-16BE"
|
||||
textoffset = 3
|
||||
stride = 2
|
||||
elif contents[:2]=="\xff\xfe":
|
||||
# seems to be utf-16LE
|
||||
print("Could be utf-16LE")
|
||||
print u"Could be utf-16LE"
|
||||
textoffset = 2
|
||||
stride = 2
|
||||
else:
|
||||
print("Perhaps utf-8 without BOM")
|
||||
print u"Perhaps utf-8 without BOM"
|
||||
|
||||
# now check that the first few characters are in the ASCII range
|
||||
for i in xrange(textoffset,textoffset+5*stride,stride):
|
||||
if ord(contents[i])<32 or ord(contents[i])>127:
|
||||
# Non-ascii, so decryption probably failed
|
||||
print("Bad character at {0}, value {1}".format(i,ord(contents[i])))
|
||||
print u"Bad character at {0}, value {1}".format(i,ord(contents[i]))
|
||||
raise ValueError
|
||||
print("Seems to be good text")
|
||||
print u"Seems to be good text"
|
||||
return True
|
||||
if contents[:5]=="<?xml" or contents[:8]=="\xef\xbb\xbf<?xml":
|
||||
# utf-8
|
||||
|
|
@ -653,13 +641,13 @@ class KoboFile(object):
|
|||
# utf-16LE of weird <!DOCTYPE start
|
||||
return True
|
||||
else:
|
||||
print("Bad XML: {0}".format(contents[:8]))
|
||||
print u"Bad XML: {0}".format(contents[:8])
|
||||
raise ValueError
|
||||
elif self.mimetype == 'image/jpeg':
|
||||
if contents[:3] == '\xff\xd8\xff':
|
||||
return True
|
||||
else:
|
||||
print("Bad JPEG: {0}".format(contents[:3].encode('hex')))
|
||||
print u"Bad JPEG: {0}".format(contents[:3].encode('hex'))
|
||||
raise ValueError()
|
||||
return False
|
||||
|
||||
|
|
@ -682,18 +670,18 @@ class KoboFile(object):
|
|||
return contents
|
||||
|
||||
def decrypt_book(book, lib):
|
||||
print("Converting {0}".format(book.title))
|
||||
print u"Converting {0}".format(book.title)
|
||||
zin = zipfile.ZipFile(book.filename, "r")
|
||||
# make filename out of Unicode alphanumeric and whitespace equivalents from title
|
||||
outname = "{0}.epub".format(re.sub('[^\s\w]', '_', book.title, 0, re.UNICODE))
|
||||
outname = u"{0}.epub".format(re.sub('[^\s\w]', '_', book.title, 0, re.UNICODE))
|
||||
if (book.type == 'drm-free'):
|
||||
print("DRM-free book, conversion is not needed")
|
||||
print u"DRM-free book, conversion is not needed"
|
||||
shutil.copyfile(book.filename, outname)
|
||||
print("Book saved as {0}".format(os.path.join(os.getcwd(), outname)))
|
||||
print u"Book saved as {0}".format(os.path.join(os.getcwd(), outname))
|
||||
return 0
|
||||
result = 1
|
||||
for userkey in lib.userkeys:
|
||||
print("Trying key: {0}".format(userkey.encode('hex_codec')))
|
||||
print u"Trying key: {0}".format(userkey.encode('hex_codec'))
|
||||
try:
|
||||
zout = zipfile.ZipFile(outname, "w", zipfile.ZIP_DEFLATED)
|
||||
for filename in zin.namelist():
|
||||
|
|
@ -705,12 +693,12 @@ def decrypt_book(book, lib):
|
|||
file.check(contents)
|
||||
zout.writestr(filename, contents)
|
||||
zout.close()
|
||||
print("Decryption succeeded.")
|
||||
print("Book saved as {0}".format(os.path.join(os.getcwd(), outname)))
|
||||
print u"Decryption succeeded."
|
||||
print u"Book saved as {0}".format(os.path.join(os.getcwd(), outname))
|
||||
result = 0
|
||||
break
|
||||
except ValueError:
|
||||
print("Decryption failed.")
|
||||
print u"Decryption failed."
|
||||
zout.close()
|
||||
os.remove(outname)
|
||||
zin.close()
|
||||
|
|
@ -719,7 +707,7 @@ def decrypt_book(book, lib):
|
|||
|
||||
def cli_main():
|
||||
description = __about__
|
||||
epilog = "Parsing of arguments failed."
|
||||
epilog = u"Parsing of arguments failed."
|
||||
parser = argparse.ArgumentParser(prog=sys.argv[0], description=description, epilog=epilog)
|
||||
parser.add_argument('--devicedir', default='/media/KOBOeReader', help="directory of connected Kobo device")
|
||||
parser.add_argument('--all', action='store_true', help="flag for converting all books on device")
|
||||
|
|
@ -735,25 +723,25 @@ def cli_main():
|
|||
books = lib.books
|
||||
else:
|
||||
for i, book in enumerate(lib.books):
|
||||
print("{0}: {1}".format(i + 1, book.title))
|
||||
print("Or 'all'")
|
||||
print u"{0}: {1}".format(i + 1, book.title)
|
||||
print u"Or 'all'"
|
||||
|
||||
choice = raw_input("Convert book number... ")
|
||||
if choice == "all":
|
||||
choice = raw_input(u"Convert book number... ")
|
||||
if choice == u'all':
|
||||
books = list(lib.books)
|
||||
else:
|
||||
try:
|
||||
num = int(choice)
|
||||
books = [lib.books[num - 1]]
|
||||
except (ValueError, IndexError):
|
||||
print("Invalid choice. Exiting...")
|
||||
sys.exit()
|
||||
print u"Invalid choice. Exiting..."
|
||||
exit()
|
||||
|
||||
results = [decrypt_book(book, lib) for book in books]
|
||||
lib.close()
|
||||
overall_result = all(result != 0 for result in results)
|
||||
if overall_result != 0:
|
||||
print("Could not decrypt book with any of the keys found.")
|
||||
print u"Could not decrypt book with any of the keys found."
|
||||
return overall_result
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load diff
159
contrib/ReadMe_First.txt
Normal file
159
contrib/ReadMe_First.txt
Normal file
|
|
@ -0,0 +1,159 @@
|
|||
Welcome to the tools!
|
||||
=====================
|
||||
|
||||
This ReadMe_First.txt is meant to give users a quick overview of what is available and how to get started. This document is part of the Tools v6.6.2 archive from Apprentice Harper's github repository: https://github.com/apprenticeharper/DeDRM_tools/
|
||||
|
||||
The is archive includes tools to remove DRM from:
|
||||
|
||||
- Kindle ebooks (files from Kindle for Mac/PC* and eInk Kindles**).
|
||||
- Adobe Digital Editions (v2.0.1***) ePubs (including Kobo and Google ePubs downloaded to ADE)
|
||||
- Kobo kePubs from the Kobo Desktop application
|
||||
- Barnes and Noble ePubs
|
||||
- Adobe Digital Editions (v2.0.1) PDFs
|
||||
- Scuolabooks (Link to solution by Hex)
|
||||
- Mobipocket ebooks
|
||||
- eReader PDB ebooks
|
||||
- Rocket ebooks (source only)
|
||||
|
||||
These tools do NOT work with Apple's iBooks FairPlay DRM (see end of this file.)
|
||||
|
||||
* With Kindle for PC/Mac 1.19 and later, Amazon included support for their new KFX format. While the tools now include a first attempt at supporting drm removal for KFX format, we recommend using Kindle for PC/Mac 1.17 or earlier which prevents downloads of the new format, as conversions from the olde KF8 format are likely to be more successful.
|
||||
|
||||
** Some later Kindles support Amazon's new KFX format. And some books download in a split azw3/azw6 format. For best results, instead of using files downloaded directly to your Kindle, download from Amazon's web site 'for transfer via USB'. This will give you an single file to import. See also the FAQ entry about this.
|
||||
|
||||
*** With Adobe Digital Editions 3.0 and later, Adobe have introduced a new, optional, DRM scheme. To avoid this new scheme, you should use Adobe Digital Editions 2.0.1. Some books are required to use the new DRM scheme and so will not download with ADE 2.0.1. If you still want such a book, you will need to use ADE 3.0 or later to download it, but you should remember that no tools to remove Adobe's new DRM scheme exist as of June 2017.
|
||||
|
||||
About the tools
|
||||
---------------
|
||||
These tools are updated and maintained by Apprentice Harper and many others. You can find the latest updates at Apprentice Harper's github repository https://github.com/apprenticeharper/DeDRM_tools/ and get support by creating an issue at the repository (github account required) or by posting a comment at Apprentice Alf's blog: http://www.apprenticealf.wordpress.com/
|
||||
|
||||
If you re-post these tools, a link to the repository and/or the blog would be appreciated.
|
||||
|
||||
|
||||
DeDRM plugin for calibre (Mac OS X, Windows, and Linux)
|
||||
-------------------------------------------------------
|
||||
Calibre is an open source freeware ebook library manager. It is the best tool around for keeping track of your ebooks. The DeDRM plugin for calibre provides the simplest way, especially on Windows, to remove DRM from your Kindle and Adobe DRM ebooks. Just install the DeDRM plugin from the DeDRM_calibre_plugin folder, following the instructions and configuration directions provided in the ReadMe file and the help links in the plugin's configuration dialogs.
|
||||
|
||||
Once installed and configured, you can simply add a DRM book to calibre and the DRM-free version will be imported into the calibre database. Note that DRM removal only occurs on IMPORT not on CONVERSION or at any other time. If you have already imported DRM books you'll need to remove them from calibre and re-import them.
|
||||
|
||||
For instructions, see the DeDRM_plugin_ReadMe.txt file in the DeDRM_calibre_plugin folder.
|
||||
|
||||
|
||||
Obok plugin for calibre (Mac OS X and Windows)
|
||||
----------------------------------------------
|
||||
To import ebooks from the Kobo Desktop app or from a Kobo ebook reader, install the Obok plugin. This works in a different way to the DeDRM plugin, in that it finds your ebooks downloaded using the Kobo Desktop app, or on an attached Kobo ebooks reader, and displays them in a list, so that you can choose the ones you want to import into calibre.
|
||||
|
||||
For instructions, see the obok_plugin_ReadMe.txt file in the Obok_calibre_plugin folder.
|
||||
|
||||
|
||||
DeDRM application for Mac OS X users: (Mac OS X 10.6 and above)
|
||||
---------------------------------------------------------------
|
||||
This application is a stand-alone DRM removal application for Mac OS X users. It is only needed for people who cannot or will not use the calibre plugin. KFX support has not been tested yet.
|
||||
|
||||
For instructions, see the "DeDRM ReadMe.rtf" file in the DeDRM_Macintosh_Application folder.
|
||||
|
||||
|
||||
DeDRM application for Windows users: (Windows XP through Windows 10)
|
||||
------------------------------------------------------------------
|
||||
***This program requires that Python and PyCrypto be properly installed.***
|
||||
***See below for details on recommended versions and how to install them.***
|
||||
|
||||
This application is a stand-alone application for Windows users. It is only needed for people who cannot or will not use the calibre plugin. KFX support has not been tested yet.
|
||||
|
||||
For instructions, see the DeDRM_App_ReadMe.txt file in the DeDRM_Windows_Applications folder.
|
||||
|
||||
|
||||
Other_Tools
|
||||
-----------
|
||||
This is a folder of other tools that may be useful for DRMed ebooks from certain sources or for Linux users. Most users won't need any of these tools.
|
||||
|
||||
B_and_N_Download_Helper
|
||||
A Javascript to enable a download button at the B&N website for ebooks that normally won't download to your PC. Only for the adventurous.
|
||||
|
||||
DRM_Key_Scripts
|
||||
This folder contains python scripts that create or extract or fetch encryption keyfiles for Barnes and Noble, Adobe Digital Editions, Kindle for Mac/PC and old versions of Kindle for Android.
|
||||
|
||||
Kindle_for_Android_Patches
|
||||
Definitely only for the adventurous, this folder contains information on how to modify the Kindle for Android app to b able to get a PID for use with the other Kindle tools (DeDRM apps and calibre plugin).
|
||||
|
||||
Kobo
|
||||
Contains the standalone obok python script for removing DRM from kePubs downloaded using the kobo desktop application.
|
||||
|
||||
Rocket_ebooks
|
||||
Information about the now-obsolete Rocket ebook format and DRM, along with source for a tool to remove the DRM.
|
||||
|
||||
Scuolabook_DRM
|
||||
A link to the tool for removing DRM from ScuolaBooks PDFs, created by "Hex".
|
||||
|
||||
|
||||
Windows and Python
|
||||
------------------
|
||||
We **strongly** recommend using calibre and the plugin.
|
||||
|
||||
If you really want to use the WIndows app or the individual scripts, you'll need to install python.
|
||||
ActiveState's Active Python 2.7 Community Edition for Windowscan be downloaded for free from:
|
||||
|
||||
http://www.activestate.com/activepython/downloads
|
||||
|
||||
In addition, Windows Users need PyCrypto:
|
||||
|
||||
There are many places to get PyCrypto installers for Windows. One such place is:
|
||||
|
||||
http://www.voidspace.org.uk/python/modules.shtml
|
||||
|
||||
Please get the latest (currently 2.6) PyCrypto meant for Windows Python version 2.7. Note that the PyCrypto binaries have two version numbers. The first is the PyCrypto version, and the second is the python version that they work with. This can be confusing.
|
||||
|
||||
Once Windows users have installed Python 2.7, and the matching PyCrypto, they are ready to run the DeDRM application or individual scripts.
|
||||
|
||||
For (experimental) KFX support, you also need LZMA support. LZMA is built-in
|
||||
in Python 3.3+ but not present in Python 2. Choices are backports.lzma and
|
||||
pylzma, both of which need compiling. Compiling Python extensions on Windows
|
||||
requires Visual Studio and is a PITA. The recommended way is to install wheels
|
||||
(binary) directly.
|
||||
|
||||
Windows binary wheels for backports.lzma and pylzma could be found here:
|
||||
|
||||
https://www.lfd.uci.edu/~gohlke/pythonlibs/
|
||||
|
||||
|
||||
Apple's iBooks FairPlay DRM
|
||||
---------------------------
|
||||
|
||||
The only tool that removes Apple's iBooks Fairplay DRM is Requiem by Brahms version 3.3.6 and works with iTunes 10.5. Requiem 4.0 and later do not remove DRM from ebooks.
|
||||
|
||||
Requiem is no longer developed as of 2012, with the last version 4.1.
|
||||
|
||||
You can download it from these download links:
|
||||
|
||||
Requiem 3.3.6 for Windows: http://www.datafilehost.com/download-f7916922.html
|
||||
MD5: 10ab191f2d86c692d57f6a07b4622cf8
|
||||
|
||||
Requiem 3.3.6 for Mac OS X: http://www.datafilehost.com/download-47fce8b7.html
|
||||
MD5: 6d4167d47e6982ddbb8528212198b520
|
||||
|
||||
Requiem 3.3.6 source code: http://www.datafilehost.com/download-172920e9.html
|
||||
MD5: 1636862796d573c693d56bcc526b60bd
|
||||
|
||||
No support for requiem is provided at Apprentice Alf's blog or Apprentice Harper's github repository.
|
||||
|
||||
|
||||
Credits
|
||||
-------
|
||||
The original inept and ignoble scripts were by i♥cabbages
|
||||
The original mobidedrm and erdr2pml scripts were by The Dark Reverser
|
||||
The original topaz DRM removal script was by CMBDTC
|
||||
The original topaz format conversion scripts were by some_updates, clarknova and Bart Simpson
|
||||
The original KFX format decryption was by lulzkabulz, converted to python by Apprentice Naomi and integrated into the tools by tomthumb1997
|
||||
|
||||
The original obok script was by Physisticated
|
||||
|
||||
The alfcrypto library is by some_updates
|
||||
The ePub encryption detection script is by Apprentice Alf, adapted from a script by Paul Durrant
|
||||
The ignoblekey script is by Apprentice Harper
|
||||
The DeDRM plugin was based on plugins by DiapDealer and is maintained by Apprentice Alf and Apprentice Harper
|
||||
The DeDRM AppleScript was by Paul Durrant and is maintained by Apprentice Alf and Apprentice Harper
|
||||
The DeDRM python GUI was by some_updates and is maintained by Apprentice Alf and Apprentice Harper
|
||||
|
||||
The Scuolabooks tool is by Hex
|
||||
|
||||
Many fixes, updates and enhancements to the scripts and applicatons have been made by many other people. For more details, see the comments in the individual scripts.
|
||||
|
|
@ -38,7 +38,7 @@ li {margin-top: 0.5em}
|
|||
|
||||
<h3>Renaming Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a sheet of paper. Clicking this button will prompt you to enter a new name for the highlighted key in the list. Enter the new name for the encryption key and click the OK button to use the new name, or Cancel to revert to the old name..</p>
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a sheet of paper. Clicking this button will promt you to enter a new name for the highlighted key in the list. Enter the new name for the encryption key and click the OK button to use the new name, or Cancel to revert to the old name..</p>
|
||||
|
||||
<h3>Exporting Keys:</h3>
|
||||
|
||||
68
dedrm_src/DeDRM_Barnes and Noble Key_Help.htm
Normal file
68
dedrm_src/DeDRM_Barnes and Noble Key_Help.htm
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
|
||||
"http://www.w3.org/TR/html4/strict.dtd">
|
||||
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
||||
<title>Managing Barnes and Noble Keys</title>
|
||||
<style type="text/css">
|
||||
span.version {font-size: 50%}
|
||||
span.bold {font-weight: bold}
|
||||
h3 {margin-bottom: 0}
|
||||
p {margin-top: 0}
|
||||
li {margin-top: 0.5em}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<h1>Managing Barnes and Noble Keys</h1>
|
||||
|
||||
|
||||
<p>If you have upgraded from an earlier version of the plugin, any existing Barnes and Noble keys will have been automatically imported, so you might not need to do any more configuration. Continue reading for key generation and management instructions.</p>
|
||||
|
||||
<h3>Changes at Barnes & Noble</h3>
|
||||
|
||||
<p>In mid-2014, Barnes & Noble changed the way they generated encryption keys. Instead of deriving the key from the user's name and credit card number, they started generating a random key themselves, sending that key through to devices when they connected to the Barnes & Noble servers. This means that most users will now find that no combination of their name and CC# will work in decrypting their recently downloaded ebooks.</p>
|
||||
|
||||
<p>Someone commenting at Apprentice Alf's blog detailed a way to retrieve a new account key using the account's email address and password. This method has now been incorporated into the plugin.
|
||||
|
||||
<h3>Creating New Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a green plus sign (+). Clicking this button will open a new dialog for entering the necessary data to generate a new key.</p>
|
||||
<ul>
|
||||
<li><span class="bold">Unique Key Name:</span> this is a unique name you choose to help you identify the key. This name will show in the list of configured keys. Choose something that will help you remember the data (account email address) it was created with.</li>
|
||||
<li><span class="bold">B&N/nook account email address:</span> This is the default email address for your Barnes and Noble/nook account. This email will not be stored anywhere on your computer or in calibre. It will only be used to fetch the account key that from the B&N server, and it is that key that will be stored in the preferences.</li>
|
||||
<li><span class="bold">B&N/nook account password:</span> this is the password for your Barnes and Noble/nook account. As with the email address, this will not be stored anywhere on your computer or in calibre. It will only be used to fetch the key from the B&N server.</li>
|
||||
</ul>
|
||||
|
||||
<p>Click the OK button to create and store the generated key. Or Cancel if you don’t want to create a key.</p>
|
||||
<p>New keys are checked against the current list of keys before being added, and duplicates are discarded.</p>
|
||||
|
||||
<h3>Deleting Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a red "X". Clicking this button will delete the highlighted key in the list. You will be prompted once to be sure that’s what you truly mean to do. Once gone, it’s permanently gone.</p>
|
||||
|
||||
<h3>Renaming Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a sheet of paper. Clicking this button will promt you to enter a new name for the highlighted key in the list. Enter the new name for the encryption key and click the OK button to use the new name, or Cancel to revert to the old name..</p>
|
||||
|
||||
<h3>Exporting Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a computer’s hard-drive. Use this button to export the highlighted key to a file (with a ‘.b64’ file name extension). Used for backup purposes or to migrate key data to other computers/calibre installations. The dialog will prompt you for a place to save the file.</p>
|
||||
|
||||
<h3>Importing Existing Keyfiles:</h3>
|
||||
|
||||
<p>At the bottom-left of the plugin’s customization dialog, you will see a button labeled "Import Existing Keyfiles". Use this button to import existing ‘.b64’ key files. Key files might come from being exported from this or older plugins, or may have been generated using the original i♥cabbages script, or you may have made it by following the instructions above.</p>
|
||||
|
||||
<p>Once done creating/deleting/renaming/importing decryption keys, click Close to exit the customization dialogue. Your changes wil only be saved permanently when you click OK in the main configuration dialog.</p>
|
||||
|
||||
<h3>NOOK Study</h3>
|
||||
<p>Books downloaded through NOOK Study may or may not use the key found using the above method. If a book is not decrypted successfully with any of the keys, the plugin will attempt to recover keys from the NOOK Study log file and use them.</p>
|
||||
|
||||
|
||||
|
||||
</body>
|
||||
|
||||
</html>
|
||||
|
|
@ -36,7 +36,7 @@ li {margin-top: 0.5em}
|
|||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a red "X". Clicking this button will delete the highlighted Kindle serial number from the list. You will be prompted once to be sure that’s what you truly mean to do. Once gone, it’s permanently gone.</p>
|
||||
|
||||
<p>Once done creating/deleting serial numbers, click Close to exit the customization dialogue. Your changes will only be saved permanently when you click OK in the main configuration dialog.</p>
|
||||
<p>Once done creating/deleting serial numbers, click Close to exit the customization dialogue. Your changes wil only be saved permanently when you click OK in the main configuration dialog.</p>
|
||||
|
||||
</body>
|
||||
|
||||
|
|
@ -17,21 +17,15 @@ p {margin-top: 0}
|
|||
|
||||
<body>
|
||||
|
||||
<h1>DeDRM Plugin <span class="version">(v10.0.9 / v10.1.0 RC1)</span></h1>
|
||||
<h1>DeDRM Plugin <span class="version">(v6.3.0)</span></h1>
|
||||
|
||||
<p>This plugin removes DRM from ebooks when they are imported into calibre. If you already have DRMed ebooks in your calibre library, you will need to remove them and import them again.</p>
|
||||
|
||||
<p>It is a forked version created by NoDRM, based on the original plugin by Apprentice Alf and Apprentice Harper.</p>
|
||||
|
||||
<h3>Installation</h3>
|
||||
<p>You have obviously managed to install the plugin, as otherwise you wouldn’t be reading this help file. However, you should also delete any older DRM removal plugins, as this DeDRM plugin replaces the five older plugins: Kindle and Mobipocket DeDRM (K4MobiDeDRM), Ignoble Epub DeDRM (ignobleepub), Inept Epub DeDRM (ineptepub), Inept PDF DeDRM (ineptepub) and eReader PDB 2 PML (eReaderPDB2PML).</p>
|
||||
|
||||
<p>This plugin (in versions v10.0.0 and above) will automatically replace the older 7.X and below versions from Apprentice Alf and Apprentice Harper.</p>
|
||||
<p>You have obviously managed to install the plugin, as otherwise you wouldn’t be reading this help file. However, you should also delete any older DeDRM plugins, as this DeDRM plugin replaces the five older plugins: Kindle and Mobipocket DeDRM (K4MobiDeDRM), Ignoble Epub DeDRM (ignobleepub), Inept Epub DeDRM (ineptepub), Inept PDF DeDRM (ineptepub) and eReader PDB 2 PML (eReaderPDB2PML).</p>
|
||||
|
||||
<h3>Configuration</h3>
|
||||
<p>On Windows and Mac, the keys for ebooks downloaded for Kindle for Mac/PC and Adobe Digital Editions are automatically generated. If all your DRMed ebooks can be opened and read in Kindle for Mac/PC and/or Adobe Digital Editions on the same computer on which you are running calibre, you do not need to do any configuration of this plugin. On Linux, keys for Kindle for PC and Adobe Digital Editions need to be generated separately (see the Linux section below).</p>
|
||||
|
||||
<p>If you are using the <a href="https://www.mobileread.com/forums/showthread.php?t=341975">DeACSM / ACSM Input Plugin</a> for Calibre, the keys will also automatically be dumped for you.</p>
|
||||
<p>On Windows and Mac, the keys for ebooks downloaded for Kindle for Mac/PC and Adobe Digital Editions are automatically generated. If all your DRMed ebooks can be opened and read in Kindle for Mac/PC and/or Adobe Digital Editions on the same computer on which you are running calibre, you do not need to do any configuration of this plugin. On Linux, keys for Kindle for PC and Adobe Digital Editions need to be generated separately (see the Linux section below)</p>
|
||||
|
||||
<p>If you have other DRMed ebooks, you will need to enter extra configuration information. The buttons in this dialog will open individual configuration dialogs that will allow you to enter the needed information, depending on the type and source of your DRMed eBooks. Additional help on the information required is available in each of the the dialogs.</p>
|
||||
|
||||
|
|
@ -41,19 +35,18 @@ p {margin-top: 0}
|
|||
|
||||
<h3>Troubleshooting:</h3>
|
||||
|
||||
<p>If you find that it’s not working for you , you can save a lot of time by trying to add the ebook to Calibre in debug mode. This will print out a lot of helpful info that can be copied into any online help requests.</p>
|
||||
<p >If you find that it’s not working for you , you can save a lot of time by trying to add the ebook to Calibre in debug mode. This will print out a lot of helpful info that can be copied into any online help requests.</p>
|
||||
|
||||
<p>Open a command prompt (terminal window) and type "calibre-debug -g" (without the quotes). Calibre will launch, and you can can add the problem ebook the usual way. The debug info will be output to the original command prompt (terminal window). Copy the resulting output and paste it into the comment you make at my blog.</p>
|
||||
<p><span class="bold">Note:</span> The Mac version of Calibre doesn’t install the command line tools by default. If you go to the ‘Preferences’ page and click on the miscellaneous button, you’ll find the option to install the command line tools.</p>
|
||||
|
||||
<h3>Credits:</h3>
|
||||
<ul>
|
||||
<li>NoDRM for a bunch of updates and maintenance since November 2021<s>, and the Readium LCP support</s></li>
|
||||
<li>The Dark Reverser for the Mobipocket and eReader scripts</li>
|
||||
<li>i♥cabbages for the Adobe Digital Editions scripts</li>
|
||||
<li>Skindle aka Bart Simpson for the Amazon Kindle for PC script</li>
|
||||
<li>CMBDTC for Amazon Topaz DRM removal script</li>
|
||||
<li>some_updates, clarknova and Bart Simpson for Amazon Topaz conversion scripts</li>
|
||||
<li>some_updates, clarknova and Bart Simpson for Amazon Topaz conversion scripts</li>
|
||||
<li>DiapDealer for the first calibre plugin versions of the tools</li>
|
||||
<li>some_updates, DiapDealer, Apprentice Alf and mdlnx for Amazon Kindle/Mobipocket tools</li>
|
||||
<li>some_updates for the DeDRM all-in-one Python tool</li>
|
||||
|
|
@ -62,8 +55,7 @@ p {margin-top: 0}
|
|||
<li>And probably many more.</li>
|
||||
</ul>
|
||||
|
||||
<h4>For additional help read the <a href="https://github.com/noDRM/DeDRM_tools/blob/master/FAQs.md">FAQs</a> at <a href="https://github.com/noDRM/DeDRM_tools">NoDRM's GitHub repository</a> (or the corresponding <a href="https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md">FAQs</a> at <a href="https://github.com/apprenticeharper/DeDRM_tools/">Apprentice Harpers’s GitHub repository</a>). You can <a href="https://github.com/noDRM/DeDRM_tools/issues">open issue reports</a> related to this fork at NoDRM's GitHub repository.</h4>
|
||||
|
||||
<h3> For additional help read the <a href="https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md">FAQs</a> at <a href="https://github.com/apprenticeharper/DeDRM_tools/">Apprentice Harpers’s GitHub repository</a>. You can ask questions in the comments section of the <a href="http://apprenticealf.wordpress.com/2012/09/10/drm-removal-tools-for-ebooks/">first post</a> at <a href="http://wordpress.com/apprenticealf/">Apprentice Alf's blog</a> or <a href="https://github.com/apprenticeharper/DeDRM_tools/issues">raise an issue</a>. </h3>
|
||||
|
||||
<h2>Linux Systems Only</h2>
|
||||
<h3>Generating decryption keys for Adobe Digital Editions and Kindle for PC</h3>
|
||||
|
|
@ -22,8 +22,6 @@ li {margin-top: 0.5em}
|
|||
|
||||
<p>If you have upgraded from an earlier version of the plugin, any existing Kindle for Mac/PC keys will have been automatically imported, so you might not need to do any more configuration. In addition, on Windows and Mac, the default Kindle for Mac/PC key is added the first time the plugin is run. Continue reading for key generation and management instructions.</p>
|
||||
|
||||
<p>Note that for best results, you should run Calibre / this plugin on the same machine where Kindle 4 PC / Kindle 4 Mac is running. It is possible to export/import the keys to another machine, but this may not always work, particularly with the newer DRM versions.</p>
|
||||
|
||||
<h3>Creating New Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a green plus sign (+). Clicking this button will open a new dialog prompting you to enter a key name for the default Kindle for Mac/PC key. </p>
|
||||
|
|
@ -40,7 +38,7 @@ li {margin-top: 0.5em}
|
|||
|
||||
<h3>Renaming Keys:</h3>
|
||||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a sheet of paper. Clicking this button will prompt you to enter a new name for the highlighted key in the list. Enter the new name for the encryption key and click the OK button to use the new name, or Cancel to revert to the old name..</p>
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a sheet of paper. Clicking this button will promt you to enter a new name for the highlighted key in the list. Enter the new name for the encryption key and click the OK button to use the new name, or Cancel to revert to the old name..</p>
|
||||
|
||||
<h3>Exporting Keys:</h3>
|
||||
|
||||
|
|
@ -48,7 +46,7 @@ li {margin-top: 0.5em}
|
|||
|
||||
<h3>Linux Users: WINEPREFIX</h3>
|
||||
|
||||
<p>Under the list of keys, Linux users will see a text field labeled "WINEPREFIX". If you are using the Kindle for PC under Wine, and your wine installation containing Kindle for PC isn't the default Wine installation, you may enter the full path to the correct Wine installation here. Leave blank if you are unsure.</p>
|
||||
<p>Under the list of keys, Linux users will see a text field labeled "WINEPREFIX". If you are use Kindle for PC under Wine, and your wine installation containing Kindle for PC isn't the default Wine installation, you may enter the full path to the correct Wine installation here. Leave blank if you are unsure.</p>
|
||||
|
||||
<h3>Importing Existing Keyfiles:</h3>
|
||||
|
||||
|
|
@ -35,7 +35,7 @@ li {margin-top: 0.5em}
|
|||
|
||||
<p>On the right-hand side of the plugin’s customization dialog, you will see a button with an icon that looks like a red "X". Clicking this button will delete the highlighted Mobipocket PID from the list. You will be prompted once to be sure that’s what you truly mean to do. Once gone, it’s permanently gone.</p>
|
||||
|
||||
<p>Once done creating/deleting PIDs, click Close to exit the customization dialogue. Your changes will only be saved permanently when you click OK in the main configuration dialog.</p>
|
||||
<p>Once done creating/deleting PIDs, click Close to exit the customization dialogue. Your changes wil only be saved permanently when you click OK in the main configuration dialog.</p>
|
||||
|
||||
</body>
|
||||
|
||||
651
dedrm_src/__init__.py
Normal file
651
dedrm_src/__init__.py
Normal file
|
|
@ -0,0 +1,651 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import with_statement
|
||||
|
||||
# __init__.py for DeDRM_plugin
|
||||
# Copyright © 2008-2019 Apprentice Harper et al.
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = '6.6.3'
|
||||
__docformat__ = 'restructuredtext en'
|
||||
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
#
|
||||
# All credit given to i♥cabbages and The Dark Reverser for the original standalone scripts.
|
||||
# We had the much easier job of converting them to a calibre plugin.
|
||||
#
|
||||
# This plugin is meant to decrypt eReader PDBs, Adobe Adept ePubs, Barnes & Noble ePubs,
|
||||
# Adobe Adept PDFs, Amazon Kindle and Mobipocket files without having to
|
||||
# install any dependencies... other than having calibre installed, of course.
|
||||
#
|
||||
# Configuration:
|
||||
# Check out the plugin's configuration settings by clicking the "Customize plugin"
|
||||
# button when you have the "DeDRM" plugin highlighted (under Preferences->
|
||||
# Plugins->File type plugins). Once you have the configuration dialog open, you'll
|
||||
# see a Help link on the top right-hand side.
|
||||
#
|
||||
# Revision history:
|
||||
# 6.0.0 - Initial release
|
||||
# 6.0.1 - Bug Fixes for Windows App, Kindle for Mac and Windows Adobe Digital Editions
|
||||
# 6.0.2 - Restored call to Wine to get Kindle for PC keys, added for ADE
|
||||
# 6.0.3 - Fixes for Kindle for Mac and Windows non-ascii user names
|
||||
# 6.0.4 - Fixes for stand-alone scripts and applications
|
||||
# and pdb files in plugin and initial conversion of prefs.
|
||||
# 6.0.5 - Fix a key issue
|
||||
# 6.0.6 - Fix up an incorrect function call
|
||||
# 6.0.7 - Error handling for incomplete PDF metadata
|
||||
# 6.0.8 - Fixes a Wine key issue and topaz support
|
||||
# 6.0.9 - Ported to work with newer versions of Calibre (moved to Qt5). Still supports older Qt4 versions.
|
||||
# 6.1.0 - Fixed multiple books import problem and PDF import with no key problem
|
||||
# 6.2.0 - Support for getting B&N key from nook Study log. Fix for UTF-8 filenames in Adobe ePubs.
|
||||
# Fix for not copying needed files. Fix for getting default Adobe key for PDFs
|
||||
# 6.2.1 - Fix for non-ascii Windows user names
|
||||
# 6.2.2 - Added URL method for B&N/nook books
|
||||
# 6.3.0 - Added in Kindle for Android serial number solution
|
||||
# 6.3.1 - Version number bump for clarity
|
||||
# 6.3.2 - Fixed Kindle for Android help file
|
||||
# 6.3.3 - Bug fix for Kindle for PC support
|
||||
# 6.3.4 - Fixes for Kindle for Android, Linux, and Kobo 3.17
|
||||
# 6.3.5 - Fixes for Linux, and Kobo 3.19 and more logging
|
||||
# 6.3.6 - Fixes for ADE ePub and PDF introduced in 6.3.5
|
||||
# 6.4.0 - Updated for new Kindle for PC encryption
|
||||
# 6.4.1 - Fix for some new tags in Topaz ebooks.
|
||||
# 6.4.2 - Fix for more new tags in Topaz ebooks and very small Topaz ebooks
|
||||
# 6.4.3 - Fix for error that only appears when not in debug mode
|
||||
# Also includes fix for Macs with bonded ethernet ports
|
||||
# 6.5.0 - Big update to Macintosh app
|
||||
# Fix for some more 'new' tags in Topaz ebooks.
|
||||
# Fix an error in wineutils.py
|
||||
# 6.5.1 - Updated version number, added PDF check for DRM-free documents
|
||||
# 6.5.2 - Another Topaz fix
|
||||
# 6.5.3 - Warn about KFX files explicitly
|
||||
# 6.5.4 - Mac App Fix, improve PDF decryption, handle latest tcl changes in ActivePython
|
||||
# 6.5.5 - Finally a fix for the Windows non-ASCII user names.
|
||||
# 6.6.0 - Add kfx and kfx-zip as supported file types (also invoke this plugin if the original
|
||||
# imported format was azw8 since that may be converted to kfx)
|
||||
# 6.6.1 - Thanks to wzyboy for a fix for stand-alone tools, and the new folder structure.
|
||||
# 6.6.2 - revamp of folders to get Mac OS X app working. Updated to 64-bit app. Various fixes.
|
||||
# 6.6.3 - More cleanup of kindle book names and start of support for .kinf2018
|
||||
|
||||
|
||||
"""
|
||||
Decrypt DRMed ebooks.
|
||||
"""
|
||||
|
||||
PLUGIN_NAME = u"DeDRM"
|
||||
PLUGIN_VERSION_TUPLE = (6, 6, 3)
|
||||
PLUGIN_VERSION = u".".join([unicode(str(x)) for x in PLUGIN_VERSION_TUPLE])
|
||||
# Include an html helpfile in the plugin's zipfile with the following name.
|
||||
RESOURCE_NAME = PLUGIN_NAME + '_Help.htm'
|
||||
|
||||
import sys, os, re
|
||||
import time
|
||||
import zipfile
|
||||
import traceback
|
||||
from zipfile import ZipFile
|
||||
|
||||
class DeDRMError(Exception):
|
||||
pass
|
||||
|
||||
from calibre.customize import FileTypePlugin
|
||||
from calibre.constants import iswindows, isosx
|
||||
from calibre.gui2 import is_ok_to_use_qt
|
||||
from calibre.utils.config import config_dir
|
||||
|
||||
|
||||
# Wrap a stream so that output gets flushed immediately
|
||||
# and also make sure that any unicode strings get safely
|
||||
# encoded using "replace" before writing them.
|
||||
class SafeUnbuffered:
|
||||
def __init__(self, stream):
|
||||
self.stream = stream
|
||||
self.encoding = stream.encoding
|
||||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
try:
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
except:
|
||||
# We can do nothing if a write fails
|
||||
pass
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
class DeDRM(FileTypePlugin):
|
||||
name = PLUGIN_NAME
|
||||
description = u"Removes DRM from Amazon Kindle, Adobe Adept (including Kobo), Barnes & Noble, Mobipocket and eReader ebooks. Credit given to i♥cabbages and The Dark Reverser for the original stand-alone scripts."
|
||||
supported_platforms = ['linux', 'osx', 'windows']
|
||||
author = u"Apprentice Alf, Aprentice Harper, The Dark Reverser and i♥cabbages"
|
||||
version = PLUGIN_VERSION_TUPLE
|
||||
minimum_calibre_version = (1, 0, 0) # Compiled python libraries cannot be imported in earlier versions.
|
||||
file_types = set(['epub','pdf','pdb','prc','mobi','pobi','azw','azw1','azw3','azw4','azw8','tpz','kfx','kfx-zip'])
|
||||
on_import = True
|
||||
priority = 600
|
||||
|
||||
|
||||
def initialize(self):
|
||||
"""
|
||||
Dynamic modules can't be imported/loaded from a zipfile.
|
||||
So this routine will extract the appropriate
|
||||
library for the target OS and copy it to the 'alfcrypto' subdirectory of
|
||||
calibre's configuration directory. That 'alfcrypto' directory is then
|
||||
inserted into the syspath (as the very first entry) in the run function
|
||||
so the CDLL stuff will work in the alfcrypto.py script.
|
||||
|
||||
The extraction only happens once per version of the plugin
|
||||
Also perform upgrade of preferences once per version
|
||||
"""
|
||||
try:
|
||||
self.pluginsdir = os.path.join(config_dir,u"plugins")
|
||||
if not os.path.exists(self.pluginsdir):
|
||||
os.mkdir(self.pluginsdir)
|
||||
self.maindir = os.path.join(self.pluginsdir,u"DeDRM")
|
||||
if not os.path.exists(self.maindir):
|
||||
os.mkdir(self.maindir)
|
||||
self.helpdir = os.path.join(self.maindir,u"help")
|
||||
if not os.path.exists(self.helpdir):
|
||||
os.mkdir(self.helpdir)
|
||||
self.alfdir = os.path.join(self.maindir,u"libraryfiles")
|
||||
if not os.path.exists(self.alfdir):
|
||||
os.mkdir(self.alfdir)
|
||||
# only continue if we've never run this version of the plugin before
|
||||
self.verdir = os.path.join(self.maindir,PLUGIN_VERSION)
|
||||
if not os.path.exists(self.verdir):
|
||||
if iswindows:
|
||||
names = [u"alfcrypto.dll",u"alfcrypto64.dll"]
|
||||
elif isosx:
|
||||
names = [u"libalfcrypto.dylib"]
|
||||
else:
|
||||
names = [u"libalfcrypto32.so",u"libalfcrypto64.so",u"kindlekey.py",u"adobekey.py",u"subasyncio.py"]
|
||||
lib_dict = self.load_resources(names)
|
||||
print u"{0} v{1}: Copying needed library files from plugin's zip".format(PLUGIN_NAME, PLUGIN_VERSION)
|
||||
|
||||
for entry, data in lib_dict.items():
|
||||
file_path = os.path.join(self.alfdir, entry)
|
||||
try:
|
||||
os.remove(file_path)
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
open(file_path,'wb').write(data)
|
||||
except:
|
||||
print u"{0} v{1}: Exception when copying needed library files".format(PLUGIN_NAME, PLUGIN_VERSION)
|
||||
traceback.print_exc()
|
||||
pass
|
||||
|
||||
# convert old preferences, if necessary.
|
||||
from calibre_plugins.dedrm.prefs import convertprefs
|
||||
convertprefs()
|
||||
|
||||
# mark that this version has been initialized
|
||||
os.mkdir(self.verdir)
|
||||
except Exception, e:
|
||||
traceback.print_exc()
|
||||
raise
|
||||
|
||||
def ePubDecrypt(self,path_to_ebook):
|
||||
# Create a TemporaryPersistent file to work with.
|
||||
# Check original epub archive for zip errors.
|
||||
import calibre_plugins.dedrm.zipfix
|
||||
|
||||
inf = self.temporary_file(u".epub")
|
||||
try:
|
||||
print u"{0} v{1}: Verifying zip archive integrity".format(PLUGIN_NAME, PLUGIN_VERSION)
|
||||
fr = zipfix.fixZip(path_to_ebook, inf.name)
|
||||
fr.fix()
|
||||
except Exception, e:
|
||||
print u"{0} v{1}: Error \'{2}\' when checking zip archive".format(PLUGIN_NAME, PLUGIN_VERSION, e.args[0])
|
||||
raise Exception(e)
|
||||
|
||||
# import the decryption keys
|
||||
import calibre_plugins.dedrm.prefs as prefs
|
||||
dedrmprefs = prefs.DeDRM_Prefs()
|
||||
|
||||
# import the Barnes & Noble ePub handler
|
||||
import calibre_plugins.dedrm.ignobleepub as ignobleepub
|
||||
|
||||
|
||||
#check the book
|
||||
if ignobleepub.ignobleBook(inf.name):
|
||||
print u"{0} v{1}: “{2}” is a secure Barnes & Noble ePub".format(PLUGIN_NAME, PLUGIN_VERSION, os.path.basename(path_to_ebook))
|
||||
|
||||
# Attempt to decrypt epub with each encryption key (generated or provided).
|
||||
for keyname, userkey in dedrmprefs['bandnkeys'].items():
|
||||
keyname_masked = u"".join((u'X' if (x.isdigit()) else x) for x in keyname)
|
||||
print u"{0} v{1}: Trying Encryption key {2:s}".format(PLUGIN_NAME, PLUGIN_VERSION, keyname_masked)
|
||||
of = self.temporary_file(u".epub")
|
||||
|
||||
# Give the user key, ebook and TemporaryPersistent file to the decryption function.
|
||||
try:
|
||||
result = ignobleepub.decryptBook(userkey, inf.name, of.name)
|
||||
except:
|
||||
print u"{0} v{1}: Exception when trying to decrypt after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
result = 1
|
||||
|
||||
of.close()
|
||||
|
||||
if result == 0:
|
||||
# Decryption was successful.
|
||||
# Return the modified PersistentTemporary file to calibre.
|
||||
return of.name
|
||||
|
||||
print u"{0} v{1}: Failed to decrypt with key {2:s} after {3:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,keyname_masked,time.time()-self.starttime)
|
||||
|
||||
# perhaps we should see if we can get a key from a log file
|
||||
print u"{0} v{1}: Looking for new NOOK Study Keys after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
|
||||
# get the default NOOK Study keys
|
||||
defaultkeys = []
|
||||
|
||||
try:
|
||||
if iswindows or isosx:
|
||||
from calibre_plugins.dedrm.ignoblekey import nookkeys
|
||||
|
||||
defaultkeys = nookkeys()
|
||||
else: # linux
|
||||
from wineutils import WineGetKeys
|
||||
|
||||
scriptpath = os.path.join(self.alfdir,u"ignoblekey.py")
|
||||
defaultkeys = WineGetKeys(scriptpath, u".b64",dedrmprefs['adobewineprefix'])
|
||||
|
||||
except:
|
||||
print u"{0} v{1}: Exception when getting default NOOK Study Key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
|
||||
newkeys = []
|
||||
for keyvalue in defaultkeys:
|
||||
if keyvalue not in dedrmprefs['bandnkeys'].values():
|
||||
newkeys.append(keyvalue)
|
||||
|
||||
if len(newkeys) > 0:
|
||||
try:
|
||||
for i,userkey in enumerate(newkeys):
|
||||
print u"{0} v{1}: Trying a new default key".format(PLUGIN_NAME, PLUGIN_VERSION)
|
||||
|
||||
of = self.temporary_file(u".epub")
|
||||
|
||||
# Give the user key, ebook and TemporaryPersistent file to the decryption function.
|
||||
try:
|
||||
result = ignobleepub.decryptBook(userkey, inf.name, of.name)
|
||||
except:
|
||||
print u"{0} v{1}: Exception when trying to decrypt after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
result = 1
|
||||
|
||||
of.close()
|
||||
|
||||
if result == 0:
|
||||
# Decryption was a success
|
||||
# Store the new successful key in the defaults
|
||||
print u"{0} v{1}: Saving a new default key".format(PLUGIN_NAME, PLUGIN_VERSION)
|
||||
try:
|
||||
dedrmprefs.addnamedvaluetoprefs('bandnkeys','nook_Study_key',keyvalue)
|
||||
dedrmprefs.writeprefs()
|
||||
print u"{0} v{1}: Saved a new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
except:
|
||||
print u"{0} v{1}: Exception saving a new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
# Return the modified PersistentTemporary file to calibre.
|
||||
return of.name
|
||||
|
||||
print u"{0} v{1}: Failed to decrypt with new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
except Exception, e:
|
||||
pass
|
||||
|
||||
print u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
raise DeDRMError(u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime))
|
||||
|
||||
# import the Adobe Adept ePub handler
|
||||
import calibre_plugins.dedrm.ineptepub as ineptepub
|
||||
|
||||
if ineptepub.adeptBook(inf.name):
|
||||
print u"{0} v{1}: {2} is a secure Adobe Adept ePub".format(PLUGIN_NAME, PLUGIN_VERSION, os.path.basename(path_to_ebook))
|
||||
|
||||
# Attempt to decrypt epub with each encryption key (generated or provided).
|
||||
for keyname, userkeyhex in dedrmprefs['adeptkeys'].items():
|
||||
userkey = userkeyhex.decode('hex')
|
||||
print u"{0} v{1}: Trying Encryption key {2:s}".format(PLUGIN_NAME, PLUGIN_VERSION, keyname)
|
||||
of = self.temporary_file(u".epub")
|
||||
|
||||
# Give the user key, ebook and TemporaryPersistent file to the decryption function.
|
||||
try:
|
||||
result = ineptepub.decryptBook(userkey, inf.name, of.name)
|
||||
except:
|
||||
print u"{0} v{1}: Exception when decrypting after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
result = 1
|
||||
|
||||
try:
|
||||
of.close()
|
||||
except:
|
||||
print u"{0} v{1}: Exception closing temporary file after {2:.1f} seconds. Ignored.".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
|
||||
if result == 0:
|
||||
# Decryption was successful.
|
||||
# Return the modified PersistentTemporary file to calibre.
|
||||
print u"{0} v{1}: Decrypted with key {2:s} after {3:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,keyname,time.time()-self.starttime)
|
||||
return of.name
|
||||
|
||||
print u"{0} v{1}: Failed to decrypt with key {2:s} after {3:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,keyname,time.time()-self.starttime)
|
||||
|
||||
# perhaps we need to get a new default ADE key
|
||||
print u"{0} v{1}: Looking for new default Adobe Digital Editions Keys after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
|
||||
# get the default Adobe keys
|
||||
defaultkeys = []
|
||||
|
||||
try:
|
||||
if iswindows or isosx:
|
||||
from calibre_plugins.dedrm.adobekey import adeptkeys
|
||||
|
||||
defaultkeys = adeptkeys()
|
||||
else: # linux
|
||||
from wineutils import WineGetKeys
|
||||
|
||||
scriptpath = os.path.join(self.alfdir,u"adobekey.py")
|
||||
defaultkeys = WineGetKeys(scriptpath, u".der",dedrmprefs['adobewineprefix'])
|
||||
|
||||
self.default_key = defaultkeys[0]
|
||||
except:
|
||||
print u"{0} v{1}: Exception when getting default Adobe Key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
self.default_key = u""
|
||||
|
||||
newkeys = []
|
||||
for keyvalue in defaultkeys:
|
||||
if keyvalue.encode('hex') not in dedrmprefs['adeptkeys'].values():
|
||||
newkeys.append(keyvalue)
|
||||
|
||||
if len(newkeys) > 0:
|
||||
try:
|
||||
for i,userkey in enumerate(newkeys):
|
||||
print u"{0} v{1}: Trying a new default key".format(PLUGIN_NAME, PLUGIN_VERSION)
|
||||
of = self.temporary_file(u".epub")
|
||||
|
||||
# Give the user key, ebook and TemporaryPersistent file to the decryption function.
|
||||
try:
|
||||
result = ineptepub.decryptBook(userkey, inf.name, of.name)
|
||||
except:
|
||||
print u"{0} v{1}: Exception when decrypting after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
result = 1
|
||||
|
||||
of.close()
|
||||
|
||||
if result == 0:
|
||||
# Decryption was a success
|
||||
# Store the new successful key in the defaults
|
||||
print u"{0} v{1}: Saving a new default key".format(PLUGIN_NAME, PLUGIN_VERSION)
|
||||
try:
|
||||
dedrmprefs.addnamedvaluetoprefs('adeptkeys','default_key',keyvalue.encode('hex'))
|
||||
dedrmprefs.writeprefs()
|
||||
print u"{0} v{1}: Saved a new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
except:
|
||||
print u"{0} v{1}: Exception when saving a new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
print u"{0} v{1}: Decrypted with new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
# Return the modified PersistentTemporary file to calibre.
|
||||
return of.name
|
||||
|
||||
print u"{0} v{1}: Failed to decrypt with new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
except Exception, e:
|
||||
print u"{0} v{1}: Unexpected Exception trying a new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
pass
|
||||
|
||||
# Something went wrong with decryption.
|
||||
print u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
raise DeDRMError(u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime))
|
||||
|
||||
# Not a Barnes & Noble nor an Adobe Adept
|
||||
# Import the fixed epub.
|
||||
print u"{0} v{1}: “{2}” is neither an Adobe Adept nor a Barnes & Noble encrypted ePub".format(PLUGIN_NAME, PLUGIN_VERSION, os.path.basename(path_to_ebook))
|
||||
raise DeDRMError(u"{0} v{1}: Couldn't decrypt after {2:.1f} seconds. DRM free perhaps?".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime))
|
||||
|
||||
def PDFDecrypt(self,path_to_ebook):
|
||||
import calibre_plugins.dedrm.prefs as prefs
|
||||
import calibre_plugins.dedrm.ineptpdf
|
||||
|
||||
dedrmprefs = prefs.DeDRM_Prefs()
|
||||
# Attempt to decrypt epub with each encryption key (generated or provided).
|
||||
print u"{0} v{1}: {2} is a PDF ebook".format(PLUGIN_NAME, PLUGIN_VERSION, os.path.basename(path_to_ebook))
|
||||
for keyname, userkeyhex in dedrmprefs['adeptkeys'].items():
|
||||
userkey = userkeyhex.decode('hex')
|
||||
print u"{0} v{1}: Trying Encryption key {2:s}".format(PLUGIN_NAME, PLUGIN_VERSION, keyname)
|
||||
of = self.temporary_file(u".pdf")
|
||||
|
||||
# Give the user key, ebook and TemporaryPersistent file to the decryption function.
|
||||
try:
|
||||
result = ineptpdf.decryptBook(userkey, path_to_ebook, of.name)
|
||||
except:
|
||||
print u"{0} v{1}: Exception when decrypting after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
result = 1
|
||||
|
||||
of.close()
|
||||
|
||||
if result == 0:
|
||||
# Decryption was successful.
|
||||
# Return the modified PersistentTemporary file to calibre.
|
||||
return of.name
|
||||
|
||||
print u"{0} v{1}: Failed to decrypt with key {2:s} after {3:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,keyname,time.time()-self.starttime)
|
||||
|
||||
# perhaps we need to get a new default ADE key
|
||||
print u"{0} v{1}: Looking for new default Adobe Digital Editions Keys after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
|
||||
# get the default Adobe keys
|
||||
defaultkeys = []
|
||||
|
||||
try:
|
||||
if iswindows or isosx:
|
||||
from calibre_plugins.dedrm.adobekey import adeptkeys
|
||||
|
||||
defaultkeys = adeptkeys()
|
||||
else: # linux
|
||||
from wineutils import WineGetKeys
|
||||
|
||||
scriptpath = os.path.join(self.alfdir,u"adobekey.py")
|
||||
defaultkeys = WineGetKeys(scriptpath, u".der",dedrmprefs['adobewineprefix'])
|
||||
|
||||
self.default_key = defaultkeys[0]
|
||||
except:
|
||||
print u"{0} v{1}: Exception when getting default Adobe Key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
self.default_key = u""
|
||||
|
||||
newkeys = []
|
||||
for keyvalue in defaultkeys:
|
||||
if keyvalue.encode('hex') not in dedrmprefs['adeptkeys'].values():
|
||||
newkeys.append(keyvalue)
|
||||
|
||||
if len(newkeys) > 0:
|
||||
try:
|
||||
for i,userkey in enumerate(newkeys):
|
||||
print u"{0} v{1}: Trying a new default key".format(PLUGIN_NAME, PLUGIN_VERSION)
|
||||
of = self.temporary_file(u".pdf")
|
||||
|
||||
# Give the user key, ebook and TemporaryPersistent file to the decryption function.
|
||||
try:
|
||||
result = ineptpdf.decryptBook(userkey, path_to_ebook, of.name)
|
||||
except:
|
||||
print u"{0} v{1}: Exception when decrypting after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
result = 1
|
||||
|
||||
of.close()
|
||||
|
||||
if result == 0:
|
||||
# Decryption was a success
|
||||
# Store the new successful key in the defaults
|
||||
print u"{0} v{1}: Saving a new default key".format(PLUGIN_NAME, PLUGIN_VERSION)
|
||||
try:
|
||||
dedrmprefs.addnamedvaluetoprefs('adeptkeys','default_key',keyvalue.encode('hex'))
|
||||
dedrmprefs.writeprefs()
|
||||
print u"{0} v{1}: Saved a new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
except:
|
||||
print u"{0} v{1}: Exception when saving a new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
# Return the modified PersistentTemporary file to calibre.
|
||||
return of.name
|
||||
|
||||
print u"{0} v{1}: Failed to decrypt with new default key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
except Exception, e:
|
||||
pass
|
||||
|
||||
# Something went wrong with decryption.
|
||||
print u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
raise DeDRMError(u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime))
|
||||
|
||||
|
||||
def KindleMobiDecrypt(self,path_to_ebook):
|
||||
|
||||
# add the alfcrypto directory to sys.path so alfcrypto.py
|
||||
# will be able to locate the custom lib(s) for CDLL import.
|
||||
sys.path.insert(0, self.alfdir)
|
||||
# Had to move this import here so the custom libs can be
|
||||
# extracted to the appropriate places beforehand these routines
|
||||
# look for them.
|
||||
import calibre_plugins.dedrm.prefs as prefs
|
||||
import calibre_plugins.dedrm.k4mobidedrm
|
||||
|
||||
dedrmprefs = prefs.DeDRM_Prefs()
|
||||
pids = dedrmprefs['pids']
|
||||
serials = dedrmprefs['serials']
|
||||
for android_serials_list in dedrmprefs['androidkeys'].values():
|
||||
#print android_serials_list
|
||||
serials.extend(android_serials_list)
|
||||
#print serials
|
||||
androidFiles = []
|
||||
kindleDatabases = dedrmprefs['kindlekeys'].items()
|
||||
|
||||
try:
|
||||
book = k4mobidedrm.GetDecryptedBook(path_to_ebook,kindleDatabases,androidFiles,serials,pids,self.starttime)
|
||||
except Exception, e:
|
||||
decoded = False
|
||||
# perhaps we need to get a new default Kindle for Mac/PC key
|
||||
defaultkeys = []
|
||||
print u"{0} v{1}: Failed to decrypt with error: {2}".format(PLUGIN_NAME, PLUGIN_VERSION,e.args[0])
|
||||
print u"{0} v{1}: Looking for new default Kindle Key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
|
||||
try:
|
||||
if iswindows or isosx:
|
||||
from calibre_plugins.dedrm.kindlekey import kindlekeys
|
||||
|
||||
defaultkeys = kindlekeys()
|
||||
else: # linux
|
||||
from wineutils import WineGetKeys
|
||||
|
||||
scriptpath = os.path.join(self.alfdir,u"kindlekey.py")
|
||||
defaultkeys = WineGetKeys(scriptpath, u".k4i",dedrmprefs['kindlewineprefix'])
|
||||
except:
|
||||
print u"{0} v{1}: Exception when getting default Kindle Key after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime)
|
||||
traceback.print_exc()
|
||||
pass
|
||||
|
||||
newkeys = {}
|
||||
for i,keyvalue in enumerate(defaultkeys):
|
||||
keyname = u"default_key_{0:d}".format(i+1)
|
||||
if keyvalue not in dedrmprefs['kindlekeys'].values():
|
||||
newkeys[keyname] = keyvalue
|
||||
if len(newkeys) > 0:
|
||||
print u"{0} v{1}: Found {2} new {3}".format(PLUGIN_NAME, PLUGIN_VERSION, len(newkeys), u"key" if len(newkeys)==1 else u"keys")
|
||||
try:
|
||||
book = k4mobidedrm.GetDecryptedBook(path_to_ebook,newkeys.items(),[],[],[],self.starttime)
|
||||
decoded = True
|
||||
# store the new successful keys in the defaults
|
||||
print u"{0} v{1}: Saving {2} new {3}".format(PLUGIN_NAME, PLUGIN_VERSION, len(newkeys), u"key" if len(newkeys)==1 else u"keys")
|
||||
for keyvalue in newkeys.values():
|
||||
dedrmprefs.addnamedvaluetoprefs('kindlekeys','default_key',keyvalue)
|
||||
dedrmprefs.writeprefs()
|
||||
except Exception, e:
|
||||
pass
|
||||
if not decoded:
|
||||
#if you reached here then no luck raise and exception
|
||||
print u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
raise DeDRMError(u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime))
|
||||
|
||||
of = self.temporary_file(book.getBookExtension())
|
||||
book.getFile(of.name)
|
||||
of.close()
|
||||
book.cleanup()
|
||||
return of.name
|
||||
|
||||
|
||||
def eReaderDecrypt(self,path_to_ebook):
|
||||
|
||||
import calibre_plugins.dedrm.prefs as prefs
|
||||
import calibre_plugins.dedrm.erdr2pml
|
||||
|
||||
dedrmprefs = prefs.DeDRM_Prefs()
|
||||
# Attempt to decrypt epub with each encryption key (generated or provided).
|
||||
for keyname, userkey in dedrmprefs['ereaderkeys'].items():
|
||||
keyname_masked = u"".join((u'X' if (x.isdigit()) else x) for x in keyname)
|
||||
print u"{0} v{1}: Trying Encryption key {2:s}".format(PLUGIN_NAME, PLUGIN_VERSION, keyname_masked)
|
||||
of = self.temporary_file(u".pmlz")
|
||||
|
||||
# Give the userkey, ebook and TemporaryPersistent file to the decryption function.
|
||||
result = erdr2pml.decryptBook(path_to_ebook, of.name, True, userkey.decode('hex'))
|
||||
|
||||
of.close()
|
||||
|
||||
# Decryption was successful return the modified PersistentTemporary
|
||||
# file to Calibre's import process.
|
||||
if result == 0:
|
||||
print u"{0} v{1}: Successfully decrypted with key {2:s} after {3:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,keyname_masked,time.time()-self.starttime)
|
||||
return of.name
|
||||
|
||||
print u"{0} v{1}: Failed to decrypt with key {2:s} after {3:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,keyname_masked,time.time()-self.starttime)
|
||||
|
||||
print u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
raise DeDRMError(u"{0} v{1}: Ultimately failed to decrypt after {2:.1f} seconds. Read the FAQs at Harper's repository: https://github.com/apprenticeharper/DeDRM_tools/blob/master/FAQs.md".format(PLUGIN_NAME, PLUGIN_VERSION, time.time()-self.starttime))
|
||||
|
||||
|
||||
def run(self, path_to_ebook):
|
||||
|
||||
# make sure any unicode output gets converted safely with 'replace'
|
||||
sys.stdout=SafeUnbuffered(sys.stdout)
|
||||
sys.stderr=SafeUnbuffered(sys.stderr)
|
||||
|
||||
print u"{0} v{1}: Trying to decrypt {2}".format(PLUGIN_NAME, PLUGIN_VERSION, os.path.basename(path_to_ebook))
|
||||
self.starttime = time.time()
|
||||
|
||||
booktype = os.path.splitext(path_to_ebook)[1].lower()[1:]
|
||||
if booktype in ['prc','mobi','pobi','azw','azw1','azw3','azw4','tpz','kfx-zip']:
|
||||
# Kindle/Mobipocket
|
||||
decrypted_ebook = self.KindleMobiDecrypt(path_to_ebook)
|
||||
elif booktype == 'pdb':
|
||||
# eReader
|
||||
decrypted_ebook = self.eReaderDecrypt(path_to_ebook)
|
||||
pass
|
||||
elif booktype == 'pdf':
|
||||
# Adobe Adept PDF (hopefully)
|
||||
decrypted_ebook = self.PDFDecrypt(path_to_ebook)
|
||||
pass
|
||||
elif booktype == 'epub':
|
||||
# Adobe Adept or B&N ePub
|
||||
decrypted_ebook = self.ePubDecrypt(path_to_ebook)
|
||||
else:
|
||||
print u"Unknown booktype {0}. Passing back to calibre unchanged".format(booktype)
|
||||
return path_to_ebook
|
||||
print u"{0} v{1}: Finished after {2:.1f} seconds".format(PLUGIN_NAME, PLUGIN_VERSION,time.time()-self.starttime)
|
||||
return decrypted_ebook
|
||||
|
||||
def is_customizable(self):
|
||||
# return true to allow customization via the Plugin->Preferences.
|
||||
return True
|
||||
|
||||
def config_widget(self):
|
||||
import calibre_plugins.dedrm.config as config
|
||||
return config.ConfigWidget(self.plugin_path, self.alfdir)
|
||||
|
||||
def save_settings(self, config_widget):
|
||||
config_widget.save_settings()
|
||||
75
dedrm_src/activitybar.py
Normal file
75
dedrm_src/activitybar.py
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import sys
|
||||
import Tkinter
|
||||
import Tkconstants
|
||||
|
||||
class ActivityBar(Tkinter.Frame):
|
||||
|
||||
def __init__(self, master, length=300, height=20, barwidth=15, interval=50, bg='white', fillcolor='orchid1',\
|
||||
bd=2, relief=Tkconstants.GROOVE, *args, **kw):
|
||||
Tkinter.Frame.__init__(self, master, bg=bg, width=length, height=height, *args, **kw)
|
||||
self._master = master
|
||||
self._interval = interval
|
||||
self._maximum = length
|
||||
self._startx = 0
|
||||
self._barwidth = barwidth
|
||||
self._bardiv = length / barwidth
|
||||
if self._bardiv < 10:
|
||||
self._bardiv = 10
|
||||
stopx = self._startx + self._barwidth
|
||||
if stopx > self._maximum:
|
||||
stopx = self._maximum
|
||||
# self._canv = Tkinter.Canvas(self, bg=self['bg'], width=self['width'], height=self['height'],\
|
||||
# highlightthickness=0, relief='flat', bd=0)
|
||||
self._canv = Tkinter.Canvas(self, bg=self['bg'], width=self['width'], height=self['height'],\
|
||||
highlightthickness=0, relief=relief, bd=bd)
|
||||
self._canv.pack(fill='both', expand=1)
|
||||
self._rect = self._canv.create_rectangle(0, 0, self._canv.winfo_reqwidth(), self._canv.winfo_reqheight(), fill=fillcolor, width=0)
|
||||
|
||||
self._set()
|
||||
self.bind('<Configure>', self._update_coords)
|
||||
self._running = False
|
||||
|
||||
def _update_coords(self, event):
|
||||
'''Updates the position of the rectangle inside the canvas when the size of
|
||||
the widget gets changed.'''
|
||||
# looks like we have to call update_idletasks() twice to make sure
|
||||
# to get the results we expect
|
||||
self._canv.update_idletasks()
|
||||
self._maximum = self._canv.winfo_width()
|
||||
self._startx = 0
|
||||
self._barwidth = self._maximum / self._bardiv
|
||||
if self._barwidth < 2:
|
||||
self._barwidth = 2
|
||||
stopx = self._startx + self._barwidth
|
||||
if stopx > self._maximum:
|
||||
stopx = self._maximum
|
||||
self._canv.coords(self._rect, 0, 0, stopx, self._canv.winfo_height())
|
||||
self._canv.update_idletasks()
|
||||
|
||||
def _set(self):
|
||||
if self._startx < 0:
|
||||
self._startx = 0
|
||||
if self._startx > self._maximum:
|
||||
self._startx = self._startx % self._maximum
|
||||
stopx = self._startx + self._barwidth
|
||||
if stopx > self._maximum:
|
||||
stopx = self._maximum
|
||||
self._canv.coords(self._rect, self._startx, 0, stopx, self._canv.winfo_height())
|
||||
self._canv.update_idletasks()
|
||||
|
||||
def start(self):
|
||||
self._running = True
|
||||
self.after(self._interval, self._step)
|
||||
|
||||
def stop(self):
|
||||
self._running = False
|
||||
self._set()
|
||||
|
||||
def _step(self):
|
||||
if self._running:
|
||||
stepsize = self._barwidth / 4
|
||||
if stepsize < 2:
|
||||
stepsize = 2
|
||||
self._startx += stepsize
|
||||
self._set()
|
||||
self.after(self._interval, self._step)
|
||||
|
|
@ -1,12 +1,32 @@
|
|||
#!/usr/bin/env python3
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# adobekey.pyw, version 7.4
|
||||
# Copyright © 2009-2022 i♥cabbages, Apprentice Harper et al.
|
||||
from __future__ import with_statement
|
||||
|
||||
# adobekey.pyw, version 6.0
|
||||
# Copyright © 2009-2010 i♥cabbages
|
||||
|
||||
# Released under the terms of the GNU General Public Licence, version 3
|
||||
# <http://www.gnu.org/licenses/>
|
||||
|
||||
# Modified 2010–2016 by several people
|
||||
|
||||
# Windows users: Before running this program, you must first install Python.
|
||||
# We recommend ActiveState Python 2.7.X for Windows (x86) from
|
||||
# http://www.activestate.com/activepython/downloads.
|
||||
# You must also install PyCrypto from
|
||||
# http://www.voidspace.org.uk/python/modules.shtml#pycrypto
|
||||
# (make certain to install the version for Python 2.7).
|
||||
# Then save this script file as adobekey.pyw and double-click on it to run it.
|
||||
# It will create a file named adobekey_1.der in in the same directory as the script.
|
||||
# This is your Adobe Digital Editions user key.
|
||||
#
|
||||
# Mac OS X users: Save this script file as adobekey.pyw. You can run this
|
||||
# program from the command line (python adobekey.pyw) or by double-clicking
|
||||
# it when it has been associated with PythonLauncher. It will create a file
|
||||
# named adobekey_1.der in the same directory as the script.
|
||||
# This is your Adobe Digital Editions user key.
|
||||
|
||||
# Revision history:
|
||||
# 1 - Initial release, for Adobe Digital Editions 1.7
|
||||
# 2 - Better algorithm for finding pLK; improved error handling
|
||||
|
|
@ -28,28 +48,32 @@
|
|||
# 5.8 - Added getkey interface for Windows DeDRM application
|
||||
# 5.9 - moved unicode_argv call inside main for Windows DeDRM compatibility
|
||||
# 6.0 - Work if TkInter is missing
|
||||
# 7.0 - Python 3 for calibre 5
|
||||
# 7.1 - Fix "failed to decrypt user key key" error (read username from registry)
|
||||
# 7.2 - Fix decryption error on Python2 if there's unicode in the username
|
||||
# 7.3 - Fix OpenSSL in Wine
|
||||
# 7.4 - Remove OpenSSL support to only support PyCryptodome
|
||||
|
||||
"""
|
||||
Retrieve Adobe ADEPT user key.
|
||||
"""
|
||||
|
||||
__license__ = 'GPL v3'
|
||||
__version__ = '7.4'
|
||||
__version__ = '6.0'
|
||||
|
||||
import sys, os, struct, getopt
|
||||
from base64 import b64decode
|
||||
|
||||
#@@CALIBRE_COMPAT_CODE@@
|
||||
|
||||
|
||||
from .utilities import SafeUnbuffered
|
||||
from .argv_utils import unicode_argv
|
||||
|
||||
# Wrap a stream so that output gets flushed immediately
|
||||
# and also make sure that any unicode strings get
|
||||
# encoded using "replace" before writing them.
|
||||
class SafeUnbuffered:
|
||||
def __init__(self, stream):
|
||||
self.stream = stream
|
||||
self.encoding = stream.encoding
|
||||
if self.encoding == None:
|
||||
self.encoding = "utf-8"
|
||||
def write(self, data):
|
||||
if isinstance(data,unicode):
|
||||
data = data.encode(self.encoding,"replace")
|
||||
self.stream.write(data)
|
||||
self.stream.flush()
|
||||
def __getattr__(self, attr):
|
||||
return getattr(self.stream, attr)
|
||||
|
||||
try:
|
||||
from calibre.constants import iswindows, isosx
|
||||
|
|
@ -57,6 +81,43 @@ except:
|
|||
iswindows = sys.platform.startswith('win')
|
||||
isosx = sys.platform.startswith('darwin')
|
||||
|
||||
def unicode_argv():
|
||||
if iswindows:
|
||||
# Uses shell32.GetCommandLineArgvW to get sys.argv as a list of Unicode
|
||||
# strings.
|
||||
|
||||
# Versions 2.x of Python don't support Unicode in sys.argv on
|
||||
# Windows, with the underlying Windows API instead replacing multi-byte
|
||||
# characters with '?'. So use shell32.GetCommandLineArgvW to get sys.argv
|
||||
# as a list of Unicode strings and encode them as utf-8
|
||||
|
||||
from ctypes import POINTER, byref, cdll, c_int, windll
|
||||
from ctypes.wintypes import LPCWSTR, LPWSTR
|
||||
|
||||
GetCommandLineW = cdll.kernel32.GetCommandLineW
|
||||
GetCommandLineW.argtypes = []
|
||||
GetCommandLineW.restype = LPCWSTR
|
||||
|
||||
CommandLineToArgvW = windll.shell32.CommandLineToArgvW
|
||||
CommandLineToArgvW.argtypes = [LPCWSTR, POINTER(c_int)]
|
||||
CommandLineToArgvW.restype = POINTER(LPWSTR)
|
||||
|
||||
cmd = GetCommandLineW()
|
||||
argc = c_int(0)
|
||||
argv = CommandLineToArgvW(cmd, byref(argc))
|
||||
if argc.value > 0:
|
||||
# Remove Python executable and commands if present
|
||||
start = argc.value - len(sys.argv)
|
||||
return [argv[i] for i in
|
||||
xrange(start, argc.value)]
|
||||
# if we don't have any arguments at all, just pass back script name
|
||||
# this should never happen
|
||||
return [u"adobekey.py"]
|
||||
else:
|
||||
argvencoding = sys.stdin.encoding
|
||||
if argvencoding == None:
|
||||
argvencoding = "utf-8"
|
||||
return [arg if (type(arg) == unicode) else unicode(arg,argvencoding) for arg in sys.argv]
|
||||
|
||||
class ADEPTError(Exception):
|
||||
pass
|
||||
|
|
@ -68,23 +129,72 @@ if iswindows:
|
|||
c_long, c_ulong
|
||||
|
||||
from ctypes.wintypes import LPVOID, DWORD, BOOL
|
||||
try:
|
||||
import winreg
|
||||
except ImportError:
|
||||
import _winreg as winreg
|
||||
import _winreg as winreg
|
||||
|
||||
try:
|
||||
from Cryptodome.Cipher import AES
|
||||
except ImportError:
|
||||
from Crypto.Cipher import AES
|
||||
def _load_crypto_libcrypto():
|
||||
from ctypes.util import find_library
|
||||
libcrypto = find_library('libeay32')
|
||||
if libcrypto is None:
|
||||
raise ADEPTError('libcrypto not found')
|
||||
libcrypto = CDLL(libcrypto)
|
||||
AES_MAXNR = 14
|
||||
c_char_pp = POINTER(c_char_p)
|
||||
c_int_p = POINTER(c_int)
|
||||
class AES_KEY(Structure):
|
||||
_fields_ = [('rd_key', c_long * (4 * (AES_MAXNR + 1))),
|
||||
('rounds', c_int)]
|
||||
AES_KEY_p = POINTER(AES_KEY)
|
||||
|
||||
def unpad(data, padding=16):
|
||||
if sys.version_info[0] == 2:
|
||||
pad_len = ord(data[-1])
|
||||
else:
|
||||
pad_len = data[-1]
|
||||
def F(restype, name, argtypes):
|
||||
func = getattr(libcrypto, name)
|
||||
func.restype = restype
|
||||
func.argtypes = argtypes
|
||||
return func
|
||||
|
||||
AES_set_decrypt_key = F(c_int, 'AES_set_decrypt_key',
|
||||
[c_char_p, c_int, AES_KEY_p])
|
||||
AES_cbc_encrypt = F(None, 'AES_cbc_encrypt',
|
||||
[c_char_p, c_char_p, c_ulong, AES_KEY_p, c_char_p,
|
||||
c_int])
|
||||
class AES(object):
|
||||
def __init__(self, userkey):
|
||||
self._blocksize = len(userkey)
|
||||
if (self._blocksize != 16) and (self._blocksize != 24) and (self._blocksize != 32) :
|
||||
raise ADEPTError('AES improper key used')
|
||||
key = self._key = AES_KEY()
|
||||
rv = AES_set_decrypt_key(userkey, len(userkey) * 8, key)
|
||||
if rv < 0:
|
||||
raise ADEPTError('Failed to initialize AES key')
|
||||
def decrypt(self, data):
|
||||
out = create_string_buffer(len(data))
|
||||
iv = ("\x00" * self._blocksize)
|
||||
rv = AES_cbc_encrypt(data, out, len(data), self._key, iv, 0)
|
||||
if rv == 0:
|
||||
raise ADEPTError('AES decryption failed')
|
||||
return out.raw
|
||||
return AES
|
||||
|
||||
def _load_crypto_pycrypto():
|
||||
from Crypto.Cipher import AES as _AES
|
||||
class AES(object):
|
||||
def __init__(self, key):
|
||||
self._aes = _AES.new(key, _AES.MODE_CBC, '\x00'*16)
|
||||
def decrypt(self, data):
|
||||
return self._aes.decrypt(data)
|
||||
return AES
|
||||
|
||||
def _load_crypto():
|
||||
AES = None
|
||||
for loader in (_load_crypto_pycrypto, _load_crypto_libcrypto):
|
||||
try:
|
||||
AES = loader()
|
||||
break
|
||||
except (ImportError, ADEPTError):
|
||||
pass
|
||||
return AES
|
||||
|
||||
AES = _load_crypto()
|
||||
|
||||
return data[:-pad_len]
|
||||
|
||||
DEVICE_KEY_PATH = r'Software\Adobe\Adept\Device'
|
||||
PRIVATE_LICENCE_KEY_PATH = r'Software\Adobe\Adept\Activation'
|
||||
|
|
@ -134,27 +244,6 @@ if iswindows:
|
|||
return GetUserName
|
||||
GetUserName = GetUserName()
|
||||
|
||||
def GetUserName2():
|
||||
try:
|
||||
from winreg import OpenKey, QueryValueEx, HKEY_CURRENT_USER
|
||||
except ImportError:
|
||||
# We're on Python 2
|
||||
try:
|
||||
# The default _winreg on Python2 isn't unicode-safe.
|
||||
# Check if we have winreg_unicode, a unicode-safe alternative.
|
||||
# Without winreg_unicode, this will fail with Unicode chars in the username.
|
||||
from adobekey_winreg_unicode import OpenKey, QueryValueEx, HKEY_CURRENT_USER
|
||||
except:
|
||||
from _winreg import OpenKey, QueryValueEx, HKEY_CURRENT_USER
|
||||
|
||||
try:
|
||||
DEVICE_KEY_PATH = r'Software\Adobe\Adept\Device'
|
||||
regkey = OpenKey(HKEY_CURRENT_USER, DEVICE_KEY_PATH)
|
||||
userREG = QueryValueEx(regkey, 'username')[0].encode('utf-16-le')[::2]
|
||||
return userREG
|
||||
except:
|
||||
return None
|
||||
|
||||
PAGE_EXECUTE_READWRITE = 0x40
|
||||
MEM_COMMIT = 0x1000
|
||||
MEM_RESERVE = 0x2000
|
||||
|
|
@ -192,54 +281,49 @@ if iswindows:
|
|||
|
||||
def __del__(self):
|
||||
if self._buf is not None:
|
||||
try:
|
||||
VirtualFree(self._buf)
|
||||
self._buf = None
|
||||
except TypeError:
|
||||
# Apparently this sometimes gets cleared on application exit
|
||||
# Causes a useless exception in the log, so let's just catch and ignore that.
|
||||
pass
|
||||
VirtualFree(self._buf)
|
||||
self._buf = None
|
||||
|
||||
if struct.calcsize("P") == 4:
|
||||
CPUID0_INSNS = (
|
||||
b"\x53" # push %ebx
|
||||
b"\x31\xc0" # xor %eax,%eax
|
||||
b"\x0f\xa2" # cpuid
|
||||
b"\x8b\x44\x24\x08" # mov 0x8(%esp),%eax
|
||||
b"\x89\x18" # mov %ebx,0x0(%eax)
|
||||
b"\x89\x50\x04" # mov %edx,0x4(%eax)
|
||||
b"\x89\x48\x08" # mov %ecx,0x8(%eax)
|
||||
b"\x5b" # pop %ebx
|
||||
b"\xc3" # ret
|
||||
"\x53" # push %ebx
|
||||
"\x31\xc0" # xor %eax,%eax
|
||||
"\x0f\xa2" # cpuid
|
||||
"\x8b\x44\x24\x08" # mov 0x8(%esp),%eax
|
||||
"\x89\x18" # mov %ebx,0x0(%eax)
|
||||
"\x89\x50\x04" # mov %edx,0x4(%eax)
|
||||
"\x89\x48\x08" # mov %ecx,0x8(%eax)
|
||||
"\x5b" # pop %ebx
|
||||
"\xc3" # ret
|
||||
)
|
||||
CPUID1_INSNS = (
|
||||
b"\x53" # push %ebx
|
||||
b"\x31\xc0" # xor %eax,%eax
|
||||
b"\x40" # inc %eax
|
||||
b"\x0f\xa2" # cpuid
|
||||
b"\x5b" # pop %ebx
|
||||
b"\xc3" # ret
|
||||
"\x53" # push %ebx
|
||||
"\x31\xc0" # xor %eax,%eax
|
||||
"\x40" # inc %eax
|
||||
"\x0f\xa2" # cpuid
|
||||
"\x5b" # pop %ebx
|
||||
"\xc3" # ret
|
||||
)
|
||||
else:
|
||||
CPUID0_INSNS = (
|
||||
b"\x49\x89\xd8" # mov %rbx,%r8
|
||||
b"\x49\x89\xc9" # mov %rcx,%r9
|
||||
b"\x48\x31\xc0" # xor %rax,%rax
|
||||
b"\x0f\xa2" # cpuid
|
||||
b"\x4c\x89\xc8" # mov %r9,%rax
|
||||
b"\x89\x18" # mov %ebx,0x0(%rax)
|
||||
b"\x89\x50\x04" # mov %edx,0x4(%rax)
|
||||
b"\x89\x48\x08" # mov %ecx,0x8(%rax)
|
||||
b"\x4c\x89\xc3" # mov %r8,%rbx
|
||||
b"\xc3" # retq
|
||||
"\x49\x89\xd8" # mov %rbx,%r8
|
||||
"\x49\x89\xc9" # mov %rcx,%r9
|
||||
"\x48\x31\xc0" # xor %rax,%rax
|
||||
"\x0f\xa2" # cpuid
|
||||
"\x4c\x89\xc8" # mov %r9,%rax
|
||||
"\x89\x18" # mov %ebx,0x0(%rax)
|
||||
"\x89\x50\x04" # mov %edx,0x4(%rax)
|
||||
"\x89\x48\x08" # mov %ecx,0x8(%rax)
|
||||
"\x4c\x89\xc3" # mov %r8,%rbx
|
||||
"\xc3" # retq
|
||||
)
|
||||
CPUID1_INSNS = (
|
||||
b"\x53" # push %rbx
|
||||
b"\x48\x31\xc0" # xor %rax,%rax
|
||||
b"\x48\xff\xc0" # inc %rax
|
||||
b"\x0f\xa2" # cpuid
|
||||
b"\x5b" # pop %rbx
|
||||
b"\xc3" # retq
|
||||
"\x53" # push %rbx
|
||||
"\x48\x31\xc0" # xor %rax,%rax
|
||||
"\x48\xff\xc0" # inc %rax
|
||||
"\x0f\xa2" # cpuid
|
||||
"\x5b" # pop %rbx
|
||||
"\xc3" # retq
|
||||
)
|
||||
|
||||
def cpuid0():
|
||||
|
|
@ -277,76 +361,54 @@ if iswindows:
|
|||
CryptUnprotectData = CryptUnprotectData()
|
||||
|
||||
def adeptkeys():
|
||||
if AES is None:
|
||||
raise ADEPTError("PyCrypto or OpenSSL must be installed")
|
||||
root = GetSystemDirectory().split('\\')[0] + '\\'
|
||||
serial = GetVolumeSerialNumber(root)
|
||||
vendor = cpuid0()
|
||||
signature = struct.pack('>I', cpuid1())[1:]
|
||||
user = GetUserName2()
|
||||
if user is None:
|
||||
user = GetUserName()
|
||||
user = GetUserName()
|
||||
entropy = struct.pack('>I12s3s13s', serial, vendor, signature, user)
|
||||
cuser = winreg.HKEY_CURRENT_USER
|
||||
try:
|
||||
regkey = winreg.OpenKey(cuser, DEVICE_KEY_PATH)
|
||||
device = winreg.QueryValueEx(regkey, 'key')[0]
|
||||
except (WindowsError, FileNotFoundError):
|
||||
except WindowsError:
|
||||
raise ADEPTError("Adobe Digital Editions not activated")
|
||||
keykey = CryptUnprotectData(device, entropy)
|
||||
userkey = None
|
||||
keys = []
|
||||
names = []
|
||||
try:
|
||||
plkroot = winreg.OpenKey(cuser, PRIVATE_LICENCE_KEY_PATH)
|
||||
except (WindowsError, FileNotFoundError):
|
||||
except WindowsError:
|
||||
raise ADEPTError("Could not locate ADE activation")
|
||||
|
||||
i = -1
|
||||
while True:
|
||||
i = i + 1 # start with 0
|
||||
for i in xrange(0, 16):
|
||||
try:
|
||||
plkparent = winreg.OpenKey(plkroot, "%04d" % (i,))
|
||||
except:
|
||||
# No more keys
|
||||
except WindowsError:
|
||||
break
|
||||
|
||||
ktype = winreg.QueryValueEx(plkparent, None)[0]
|
||||
if ktype != 'credentials':
|
||||
continue
|
||||
uuid_name = ""
|
||||
for j in range(0, 16):
|
||||
for j in xrange(0, 16):
|
||||
try:
|
||||
plkkey = winreg.OpenKey(plkparent, "%04d" % (j,))
|
||||
except (WindowsError, FileNotFoundError):
|
||||
except WindowsError:
|
||||
break
|
||||
ktype = winreg.QueryValueEx(plkkey, None)[0]
|
||||
if ktype == 'user':
|
||||
# Add Adobe UUID to key name
|
||||
uuid_name = uuid_name + winreg.QueryValueEx(plkkey, 'value')[0][9:] + "_"
|
||||
if ktype == 'username':
|
||||
# Add account type & email to key name, if present
|
||||
try:
|
||||
uuid_name = uuid_name + winreg.QueryValueEx(plkkey, 'method')[0] + "_"
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
uuid_name = uuid_name + winreg.QueryValueEx(plkkey, 'value')[0] + "_"
|
||||
except:
|
||||
pass
|
||||
if ktype == 'privateLicenseKey':
|
||||
userkey = winreg.QueryValueEx(plkkey, 'value')[0]
|
||||
userkey = unpad(AES.new(keykey, AES.MODE_CBC, b'\x00'*16).decrypt(b64decode(userkey)))[26:]
|
||||
# print ("found " + uuid_name + " key: " + str(userkey))
|
||||
keys.append(userkey)
|
||||
|
||||
if uuid_name == "":
|
||||
names.append("Unknown")
|
||||
else:
|
||||
names.append(uuid_name[:-1])
|
||||
|
||||
if ktype != 'privateLicenseKey':
|
||||
continue
|
||||
userkey = winreg.QueryValueEx(plkkey, 'value')[0]
|
||||
userkey = userkey.decode('base64')
|
||||
aes = AES(keykey)
|
||||
userkey = aes.decrypt(userkey)
|
||||
userkey = userkey[26:-ord(userkey[-1])]
|
||||
#print "found key:",userkey.encode('hex')
|
||||
keys.append(userkey)
|
||||
if len(keys) == 0:
|
||||
raise ADEPTError('Could not locate privateLicenseKey')
|
||||
print("Found {0:d} keys".format(len(keys)))
|
||||
return keys, names
|
||||
print u"Found {0:d} keys".format(len(keys))
|
||||
return keys
|
||||
|
||||
|
||||
elif isosx:
|
||||
|
|
@ -365,12 +427,12 @@ elif isosx:
|
|||
cmdline = cmdline.encode(sys.getfilesystemencoding())
|
||||
p2 = subprocess.Popen(cmdline, shell=True, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=False)
|
||||
out1, out2 = p2.communicate()
|
||||
reslst = out1.split(b'\n')
|
||||
reslst = out1.split('\n')
|
||||
cnt = len(reslst)
|
||||
ActDatPath = b"activation.dat"
|
||||
for j in range(cnt):
|
||||
ActDatPath = "activation.dat"
|
||||
for j in xrange(cnt):
|
||||
resline = reslst[j]
|
||||
pp = resline.find(b'activation.dat')
|
||||
pp = resline.find('activation.dat')
|
||||
if pp >= 0:
|
||||
ActDatPath = resline
|
||||
break
|
||||
|
|
@ -379,8 +441,6 @@ elif isosx:
|
|||
return None
|
||||
|
||||
def adeptkeys():
|
||||
# TODO: All the code to support extracting multiple activation keys
|
||||
# TODO: seems to be Windows-only currently, still needs to be added for Mac.
|
||||
actpath = findActivationDat()
|
||||
if actpath is None:
|
||||
raise ADEPTError("Could not find ADE activation.dat file.")
|
||||
|
|
@ -388,80 +448,56 @@ elif isosx:
|
|||
adept = lambda tag: '{%s}%s' % (NSMAP['adept'], tag)
|
||||
expr = '//%s/%s' % (adept('credentials'), adept('privateLicenseKey'))
|
||||
userkey = tree.findtext(expr)
|
||||
|
||||
exprUUID = '//%s/%s' % (adept('credentials'), adept('user'))
|
||||
keyName = ""
|
||||
try:
|
||||
keyName = tree.findtext(exprUUID)[9:] + "_"
|
||||
except:
|
||||
pass
|
||||
|
||||
try:
|
||||
exprMail = '//%s/%s' % (adept('credentials'), adept('username'))
|
||||
keyName = keyName + tree.find(exprMail).attrib["method"] + "_"
|
||||
keyName = keyName + tree.findtext(exprMail) + "_"
|
||||
except:
|
||||
pass
|
||||
|
||||
if keyName == "":
|
||||
keyName = "Unknown"
|
||||
else:
|
||||
keyName = keyName[:-1]
|
||||
|
||||
|
||||
|
||||
userkey = b64decode(userkey)
|
||||
userkey = userkey.decode('base64')
|
||||
userkey = userkey[26:]
|
||||
return [userkey], [keyName]
|
||||
return [userkey]
|
||||
|
||||
else:
|
||||
def adeptkeys():
|
||||
raise ADEPTError("This script only supports Windows and Mac OS X.")
|
||||
return [], []
|
||||
return []
|
||||
|
||||
# interface for Python DeDRM
|
||||
def getkey(outpath):
|
||||
keys, names = adeptkeys()
|
||||
keys = adeptkeys()
|
||||
if len(keys) > 0:
|
||||
if not os.path.isdir(outpath):
|
||||
outfile = outpath
|
||||
with open(outfile, 'wb') as keyfileout:
|
||||
with file(outfile, 'wb') as keyfileout:
|
||||
keyfileout.write(keys[0])
|
||||
print("Saved a key to {0}".format(outfile))
|
||||
print u"Saved a key to {0}".format(outfile)
|
||||
else:
|
||||
keycount = 0
|
||||
name_index = 0
|
||||
for key in keys:
|
||||
while True:
|
||||
keycount += 1
|
||||
outfile = os.path.join(outpath,"adobekey{0:d}_uuid_{1}.der".format(keycount, names[name_index]))
|
||||
outfile = os.path.join(outpath,u"adobekey_{0:d}.der".format(keycount))
|
||||
if not os.path.exists(outfile):
|
||||
break
|
||||
with open(outfile, 'wb') as keyfileout:
|
||||
with file(outfile, 'wb') as keyfileout:
|
||||
keyfileout.write(key)
|
||||
print("Saved a key to {0}".format(outfile))
|
||||
name_index += 1
|
||||
print u"Saved a key to {0}".format(outfile)
|
||||
return True
|
||||
return False
|
||||
|
||||
def usage(progname):
|
||||
print("Finds, decrypts and saves the default Adobe Adept encryption key(s).")
|
||||
print("Keys are saved to the current directory, or a specified output directory.")
|
||||
print("If a file name is passed instead of a directory, only the first key is saved, in that file.")
|
||||
print("Usage:")
|
||||
print(" {0:s} [-h] [<outpath>]".format(progname))
|
||||
print u"Finds, decrypts and saves the default Adobe Adept encryption key(s)."
|
||||
print u"Keys are saved to the current directory, or a specified output directory."
|
||||
print u"If a file name is passed instead of a directory, only the first key is saved, in that file."
|
||||
print u"Usage:"
|
||||
print u" {0:s} [-h] [<outpath>]".format(progname)
|
||||
|
||||
def cli_main():
|
||||
sys.stdout=SafeUnbuffered(sys.stdout)
|
||||
sys.stderr=SafeUnbuffered(sys.stderr)
|
||||
argv=unicode_argv("adobekey.py")
|
||||
argv=unicode_argv()
|
||||
progname = os.path.basename(argv[0])
|
||||
print("{0} v{1}\nCopyright © 2009-2020 i♥cabbages, Apprentice Harper et al.".format(progname,__version__))
|
||||
print u"{0} v{1}\nCopyright © 2009-2013 i♥cabbages and Apprentice Alf".format(progname,__version__)
|
||||
|
||||
try:
|
||||
opts, args = getopt.getopt(argv[1:], "h")
|
||||
except getopt.GetoptError as err:
|
||||
print("Error in options or arguments: {0}".format(err.args[0]))
|
||||
except getopt.GetoptError, err:
|
||||
print u"Error in options or arguments: {0}".format(err.args[0])
|
||||
usage(progname)
|
||||
sys.exit(2)
|
||||
|
||||
|
|
@ -486,82 +522,76 @@ def cli_main():
|
|||
# make sure the outpath is the
|
||||
outpath = os.path.realpath(os.path.normpath(outpath))
|
||||
|
||||
keys, names = adeptkeys()
|
||||
keys = adeptkeys()
|
||||
if len(keys) > 0:
|
||||
if not os.path.isdir(outpath):
|
||||
outfile = outpath
|
||||
with open(outfile, 'wb') as keyfileout:
|
||||
with file(outfile, 'wb') as keyfileout:
|
||||
keyfileout.write(keys[0])
|
||||
print("Saved a key to {0}".format(outfile))
|
||||
print u"Saved a key to {0}".format(outfile)
|
||||
else:
|
||||
keycount = 0
|
||||
name_index = 0
|
||||
for key in keys:
|
||||
while True:
|
||||
keycount += 1
|
||||
outfile = os.path.join(outpath,"adobekey{0:d}_uuid_{1}.der".format(keycount, names[name_index]))
|
||||
outfile = os.path.join(outpath,u"adobekey_{0:d}.der".format(keycount))
|
||||
if not os.path.exists(outfile):
|
||||
break
|
||||
with open(outfile, 'wb') as keyfileout:
|
||||
with file(outfile, 'wb') as keyfileout:
|
||||
keyfileout.write(key)
|
||||
print("Saved a key to {0}".format(outfile))
|
||||
name_index += 1
|
||||
print u"Saved a key to {0}".format(outfile)
|
||||
else:
|
||||
print("Could not retrieve Adobe Adept key.")
|
||||
print u"Could not retrieve Adobe Adept key."
|
||||
return 0
|
||||
|
||||
|
||||
def gui_main():
|
||||
try:
|
||||
import tkinter
|
||||
import tkinter.constants
|
||||
import tkinter.messagebox
|
||||
import Tkinter
|
||||
import Tkconstants
|
||||
import tkMessageBox
|
||||
import traceback
|
||||
except:
|
||||
return cli_main()
|
||||
|
||||
class ExceptionDialog(tkinter.Frame):
|
||||
class ExceptionDialog(Tkinter.Frame):
|
||||
def __init__(self, root, text):
|
||||
tkinter.Frame.__init__(self, root, border=5)
|
||||
label = tkinter.Label(self, text="Unexpected error:",
|
||||
anchor=tkinter.constants.W, justify=tkinter.constants.LEFT)
|
||||
label.pack(fill=tkinter.constants.X, expand=0)
|
||||
self.text = tkinter.Text(self)
|
||||
self.text.pack(fill=tkinter.constants.BOTH, expand=1)
|
||||
Tkinter.Frame.__init__(self, root, border=5)
|
||||
label = Tkinter.Label(self, text=u"Unexpected error:",
|
||||
anchor=Tkconstants.W, justify=Tkconstants.LEFT)
|
||||
label.pack(fill=Tkconstants.X, expand=0)
|
||||
self.text = Tkinter.Text(self)
|
||||
self.text.pack(fill=Tkconstants.BOTH, expand=1)
|
||||
|
||||
self.text.insert(tkinter.constants.END, text)
|
||||
self.text.insert(Tkconstants.END, text)
|
||||
|
||||
|
||||
argv=unicode_argv("adobekey.py")
|
||||
root = tkinter.Tk()
|
||||
argv=unicode_argv()
|
||||
root = Tkinter.Tk()
|
||||
root.withdraw()
|
||||
progpath, progname = os.path.split(argv[0])
|
||||
success = False
|
||||
try:
|
||||
keys, names = adeptkeys()
|
||||
print(keys)
|
||||
print(names)
|
||||
keys = adeptkeys()
|
||||
keycount = 0
|
||||
name_index = 0
|
||||
for key in keys:
|
||||
while True:
|
||||
keycount += 1
|
||||
outfile = os.path.join(progpath,"adobekey{0:d}_uuid_{1}.der".format(keycount, names[name_index]))
|
||||
outfile = os.path.join(progpath,u"adobekey_{0:d}.der".format(keycount))
|
||||
if not os.path.exists(outfile):
|
||||
break
|
||||
|
||||
with open(outfile, 'wb') as keyfileout:
|
||||
with file(outfile, 'wb') as keyfileout:
|
||||
keyfileout.write(key)
|
||||
success = True
|
||||
tkinter.messagebox.showinfo(progname, "Key successfully retrieved to {0}".format(outfile))
|
||||
name_index += 1
|
||||
except ADEPTError as e:
|
||||
tkinter.messagebox.showerror(progname, "Error: {0}".format(str(e)))
|
||||
tkMessageBox.showinfo(progname, u"Key successfully retrieved to {0}".format(outfile))
|
||||
except ADEPTError, e:
|
||||
tkMessageBox.showerror(progname, u"Error: {0}".format(str(e)))
|
||||
except Exception:
|
||||
root.wm_state('normal')
|
||||
root.title(progname)
|
||||
text = traceback.format_exc()
|
||||
ExceptionDialog(root, text).pack(fill=tkinter.constants.BOTH, expand=1)
|
||||
ExceptionDialog(root, text).pack(fill=Tkconstants.BOTH, expand=1)
|
||||
root.mainloop()
|
||||
if not success:
|
||||
return 1
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
#! /usr/bin/env python
|
||||
|
||||
"""
|
||||
Routines for doing AES CBC in one file
|
||||
|
|
@ -14,8 +13,6 @@
|
|||
CryptoPy Artisitic License Version 1.0
|
||||
See the wonderful pure python package cryptopy-1.2.5
|
||||
and read its LICENSE.txt for complete license details.
|
||||
|
||||
Adjusted for Python 3, September 2020
|
||||
"""
|
||||
|
||||
class CryptoError(Exception):
|
||||
|
|
@ -104,7 +101,7 @@ class BlockCipher:
|
|||
numBlocks, numExtraBytes = divmod(len(self.bytesToDecrypt), self.blockSize)
|
||||
if more == None: # no more calls to decrypt, should have all the data
|
||||
if numExtraBytes != 0:
|
||||
raise DecryptNotBlockAlignedError('Data not block aligned on decrypt')
|
||||
raise DecryptNotBlockAlignedError, 'Data not block aligned on decrypt'
|
||||
|
||||
# hold back some bytes in case last decrypt has zero len
|
||||
if (more != None) and (numExtraBytes == 0) and (numBlocks >0) :
|
||||
|
|
@ -146,7 +143,7 @@ class padWithPadLen(Pad):
|
|||
def removePad(self, paddedBinaryString, blockSize):
|
||||
""" Remove padding from a binary string """
|
||||
if not(0<len(paddedBinaryString)):
|
||||
raise DecryptNotBlockAlignedError('Expected More Data')
|
||||
raise DecryptNotBlockAlignedError, 'Expected More Data'
|
||||
return paddedBinaryString[:-ord(paddedBinaryString[-1])]
|
||||
|
||||
class noPadding(Pad):
|
||||
|
|
@ -176,8 +173,8 @@ class Rijndael(BlockCipher):
|
|||
self.blockSize = blockSize # blockSize is in bytes
|
||||
self.padding = padding # change default to noPadding() to get normal ECB behavior
|
||||
|
||||
assert( keySize%4==0 and keySize/4 in NrTable[4]),'key size must be 16,20,24,29 or 32 bytes'
|
||||
assert( blockSize%4==0 and blockSize/4 in NrTable), 'block size must be 16,20,24,29 or 32 bytes'
|
||||
assert( keySize%4==0 and NrTable[4].has_key(keySize/4)),'key size must be 16,20,24,29 or 32 bytes'
|
||||
assert( blockSize%4==0 and NrTable.has_key(blockSize/4)), 'block size must be 16,20,24,29 or 32 bytes'
|
||||
|
||||
self.Nb = self.blockSize/4 # Nb is number of columns of 32 bit words
|
||||
self.Nk = keySize/4 # Nk is the key length in 32-bit words
|
||||
|
|
@ -454,7 +451,7 @@ class AES(Rijndael):
|
|||
def __init__(self, key = None, padding = padWithPadLen(), keySize=16):
|
||||
""" Initialize AES, keySize is in bytes """
|
||||
if not (keySize == 16 or keySize == 24 or keySize == 32) :
|
||||
raise BadKeySizeError('Illegal AES key size, must be 16, 24, or 32 bytes')
|
||||
raise BadKeySizeError, 'Illegal AES key size, must be 16, 24, or 32 bytes'
|
||||
|
||||
Rijndael.__init__( self, key, padding=padding, keySize=keySize, blockSize=16 )
|
||||
|
||||
BIN
dedrm_src/alfcrypto.dll
Normal file
BIN
dedrm_src/alfcrypto.dll
Normal file
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue