├── .github
└── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── LICENSE
├── README.md
├── hooks
└── after_prepare.js
├── package.json
├── plugin.xml
└── src
├── android
└── com
│ └── crypt
│ └── cordova
│ └── DecryptResource.java
└── ios
├── CDVCrypt.h
├── CDVCrypt.m
├── CDVCryptURLProtocol.h
└── CDVCryptURLProtocol.m
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: BUG
5 | labels: bug
6 | assignees: PeterHdd
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, please do the following:
25 |
26 | 1) Add a screenshot of your problem.
27 | 2) Add a snippet of code that contains the problem.
28 | 3) Create a repository and share it here so we can check the problem
29 |
30 | **Additional context**
31 | Add any other context about the problem here.
32 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: Feature Request
5 | labels: enhancement
6 | assignees: PeterHdd
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright 2013-2015 appPlant UG, Inc.
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 | 
3 |
4 | # Cordova crypto file plugin
5 | HTML source file is encrypted at build, and decrypted at run.
6 | https://www.npmjs.com/package/cordova-plugin-crypto-file
7 |
8 | ## Add Plugin
9 | `cordova plugin add cordova-plugin-crypto-file`
10 |
11 | ## Purpose
12 |
13 | This plugin was created to solve the issue of using cordova-plugin-ionic-webview with cordova-crypt-file, refer to [#75](https://github.com/tkyaji/cordova-plugin-crypt-file/issues/75)
14 |
15 | ## Important
16 |
17 | The file `IonicWebViewEngine.java` (that is inside the ionic webview plugin) needs to be modified for this plugin to work and for the source code to be encrypted.
18 | ### Steps:
19 | 1. After adding the cordova-plugin-ionic-webview, navigate to the following location:
20 |
21 | For cordova-android@6 :
22 |
23 | **platforms/android/src/com/ionicframework/cordova/webview/IonicWebViewEngine.java**
24 |
25 | For cordova-android@7 :
26 |
27 | **platforms/android/app/src/main/java/com/ionicframework/cordova/webview/IonicWebViewEngine.java**
28 |
29 | 2. Remove the following code:
30 |
31 | ```
32 | @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
33 | @Override
34 | public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
35 | super.shouldInterceptRequest(view,request);
36 | return localServer.shouldInterceptRequest(request.getUrl());
37 | }
38 |
39 | @TargetApi(Build.VERSION_CODES.KITKAT)
40 | @Override
41 | public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
42 | return localServer.shouldInterceptRequest(Uri.parse(url));
43 | }
44 | ```
45 | 3. Add this instead:
46 |
47 | ```
48 | @Override
49 | public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
50 | return super.shouldInterceptRequest(view, request);
51 | }
52 | ```
53 |
54 | Then the plugin will work.
55 |
56 | ## Configuration
57 |
58 | You can also change the port in the `config.xml`, but it needs to be the same port as the one used in the "cordova-plugin-ionic-webview".
59 |
60 | To change the port, do the following:
61 |
62 | #### cryptoPort
63 |
64 | ```xml
65 |
66 | ```
67 |
68 | ## Encrypt
69 | `cordova build [ios / android]`
70 |
71 | ## Decrypt
72 | `cordova emulate [ios / android]`
73 | or
74 | `cordova run [ios / android]`
75 |
76 | ## Encryption subjects.
77 |
78 | ### Default
79 |
80 | * .html
81 | * .htm
82 | * .js
83 | * .css
84 |
85 | ### Edit subjects
86 |
87 | You can specify the encryption subjects by editing `plugin.xml`.
88 |
89 | **plugins/cordova-plugin-crypt-file/plugin.xml**
90 |
91 | ```
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 | ```
101 |
102 | Specify the target file as a regular expression.
103 |
104 |
105 | ## Supported platforms
106 | * iOS
107 | * Android
108 | * CrossWalk
109 |
110 |
111 | ## Based on the original cordova-crypt-file created by tkyaji
112 |
113 | https://github.com/tkyaji/cordova-plugin-crypt-file
114 |
115 | ## License
116 | Apache version 2.0
117 |
--------------------------------------------------------------------------------
/hooks/after_prepare.js:
--------------------------------------------------------------------------------
1 | module.exports = function(context) {
2 |
3 | var path = require('path'),
4 | fs = require('fs'),
5 | crypto = require('crypto'),
6 | Q = require('q'),
7 | cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util'),
8 | platforms = context.requireCordovaModule('cordova-lib/src/platforms/platforms'),
9 | ConfigParser = context.requireCordovaModule('cordova-common').ConfigParser;
10 |
11 | var deferral = new Q.defer();
12 | var projectRoot = cordova_util.cdProjectRoot();
13 |
14 | var key = crypto.randomBytes(24).toString('base64');
15 | var iv = crypto.randomBytes(12).toString('base64');
16 |
17 | console.log('key=' + key + ', iv=' + iv)
18 |
19 | var targetFiles = loadCryptFileTargets();
20 |
21 | context.opts.platforms.filter(function(platform) {
22 | var pluginInfo = context.opts.plugin.pluginInfo;
23 | return pluginInfo.getPlatformsArray().indexOf(platform) > -1;
24 |
25 | }).forEach(function(platform) {
26 | var platformPath = path.join(projectRoot, 'platforms', platform);
27 | var platformApi = platforms.getPlatformApi(platform, platformPath);
28 | var platformInfo = platformApi.getPlatformInfo();
29 | var wwwDir = platformInfo.locations.www;
30 |
31 | findCryptFiles(wwwDir).filter(function(file) {
32 | return fs.statSync(file).isFile() && isCryptFile(file.replace(wwwDir, ''));
33 | }).forEach(function(file) {
34 | var content = fs.readFileSync(file, 'utf-8');
35 | fs.writeFileSync(file, encryptData(content, key, iv), 'utf-8');
36 | console.log('encrypt: ' + file);
37 | });
38 |
39 | if (platform == 'ios') {
40 | var pluginDir;
41 | try {
42 | var ios_parser = context.requireCordovaModule('cordova-lib/src/cordova/metadata/ios_parser'),
43 | iosParser = new ios_parser(platformPath);
44 | pluginDir = path.join(iosParser.cordovaproj, 'Plugins', context.opts.plugin.id);
45 | } catch (err) {
46 | var xcodeproj_dir = fs.readdirSync(platformPath).filter(function(e) { return e.match(/\.xcodeproj$/i); })[0],
47 | xcodeproj = path.join(platformPath, xcodeproj_dir),
48 | originalName = xcodeproj.substring(xcodeproj.lastIndexOf(path.sep)+1, xcodeproj.indexOf('.xcodeproj')),
49 | cordovaproj = path.join(platformPath, originalName);
50 |
51 | pluginDir = path.join(cordovaproj, 'Plugins', context.opts.plugin.id);
52 | }
53 | replaceCryptKey_ios(pluginDir, key, iv);
54 |
55 | } else if (platform == 'android') {
56 | if(wwwDir.includes("main"))
57 | {
58 | var pluginDir = path.join(platformPath, 'app/src/main/java');
59 | }
60 | else
61 | {
62 | var pluginDir = path.join(platformPath, 'src');
63 | }
64 | replaceCryptKey_android(pluginDir, key, iv);
65 |
66 | var cfg = new ConfigParser(platformInfo.projectConfig.path);
67 | var port = cfg.getGlobalPreference("cryptoPort");
68 | if( port == '')
69 | {
70 | cfg.doc.getroot().getchildren().filter(function(child, idx, arr) {
71 | return (child.tag == 'content');
72 | }).forEach(function(child) {
73 | child.attrib.src = 'http://localhost:8080/' + child.attrib.src;
74 | });
75 | }
76 | else
77 | {
78 | cfg.doc.getroot().getchildren().filter(function(child, idx, arr) {
79 | return (child.tag == 'content');
80 | }).forEach(function(child) {
81 | child.attrib.src = 'http://localhost:' + port + '/' + child.attrib.src;
82 | });
83 | }
84 |
85 | cfg.write();
86 | }
87 | });
88 |
89 | deferral.resolve();
90 | return deferral.promise;
91 |
92 |
93 | function findCryptFiles(dir) {
94 | var fileList = [];
95 | var list = fs.readdirSync(dir);
96 | list.forEach(function(file) {
97 | fileList.push(path.join(dir, file));
98 | });
99 | // sub dir
100 | list.filter(function(file) {
101 | return fs.statSync(path.join(dir, file)).isDirectory();
102 | }).forEach(function(file) {
103 | var subDir = path.join(dir, file)
104 | var subFileList = findCryptFiles(subDir);
105 | fileList = fileList.concat(subFileList);
106 | });
107 |
108 | return fileList;
109 | }
110 |
111 | function loadCryptFileTargets() {
112 | var xmlHelpers = context.requireCordovaModule('cordova-common').xmlHelpers;
113 |
114 | var pluginXml = path.join(context.opts.plugin.dir, 'plugin.xml');
115 |
116 | var include = [];
117 | var exclude = [];
118 |
119 | var doc = xmlHelpers.parseElementtreeSync(pluginXml);
120 | var cryptfiles = doc.findall('cryptfiles');
121 | if (cryptfiles.length > 0) {
122 | cryptfiles[0]._children.forEach(function(elm) {
123 | elm._children.filter(function(celm) {
124 | return celm.tag == 'file' && celm.attrib.regex && celm.attrib.regex.trim().length > 0;
125 | }).forEach(function(celm) {
126 | if (elm.tag == 'include') {
127 | include.push(celm.attrib.regex.trim());
128 | } else if (elm.tag == 'exclude') {
129 | exclude.push(celm.attrib.regex.trim());
130 | }
131 | });
132 | })
133 | }
134 |
135 | return {'include': include, 'exclude': exclude};
136 | }
137 |
138 | function isCryptFile(file) {
139 | if (!targetFiles.include.some(function(regexStr) { return new RegExp(regexStr).test(file); })) {
140 | return false;
141 | }
142 | if (targetFiles.exclude.some(function(regexStr) { return new RegExp(regexStr).test(file); })) {
143 | return false;
144 | }
145 | return true;
146 | }
147 |
148 | function encryptData(input, key, iv) {
149 | var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
150 | var encrypted = cipher.update(input, 'utf8', 'base64') + cipher.final('base64');
151 |
152 | return encrypted;
153 | }
154 |
155 | function replaceCryptKey_ios(pluginDir, key, iv) {
156 | var sourceFile = path.join(pluginDir, 'CDVCryptURLProtocol.m');
157 | var content = fs.readFileSync(sourceFile, 'utf-8');
158 |
159 | var includeArrStr = targetFiles.include.map(function(pattern) { return '@"' + pattern.replace('\\', '\\\\') + '"'; }).join(', ');
160 | var excludeArrStr = targetFiles.exclude.map(function(pattern) { return '@"' + pattern.replace('\\', '\\\\') + '"'; }).join(', ');
161 |
162 | content = content.replace(/kCryptKey = @".*";/, 'kCryptKey = @"' + key + '";')
163 | .replace(/kCryptIv = @".*";/, 'kCryptIv = @"' + iv + '";')
164 | .replace(/kIncludeFiles\[\] = {.*};/, 'kIncludeFiles\[\] = { ' + includeArrStr + ' };')
165 | .replace(/kExcludeFiles\[\] = {.*};/, 'kExcludeFiles\[\] = { ' + excludeArrStr + ' };')
166 | .replace(/kIncludeFileLength = [0-9]+;/, 'kIncludeFileLength = ' + targetFiles.include.length + ';')
167 | .replace(/kExcludeFileLength = [0-9]+;/, 'kExcludeFileLength = ' + targetFiles.exclude.length + ';');
168 |
169 | fs.writeFileSync(sourceFile, content, 'utf-8');
170 | }
171 |
172 | function replaceCryptKey_android(pluginDir, key, iv) {
173 | var sourceFile = path.join(pluginDir, 'com/crypt/cordova/DecryptResource.java');
174 | var content = fs.readFileSync(sourceFile, 'utf-8');
175 |
176 | var includeArrStr = targetFiles.include.map(function(pattern) { return '"' + pattern.replace('\\', '\\\\') + '"'; }).join(', ');
177 | var excludeArrStr = targetFiles.exclude.map(function(pattern) { return '"' + pattern.replace('\\', '\\\\') + '"'; }).join(', ');
178 |
179 | content = content.replace(/CRYPT_KEY = ".*";/, 'CRYPT_KEY = "' + key + '";')
180 | .replace(/CRYPT_IV = ".*";/, 'CRYPT_IV = "' + iv + '";')
181 | .replace(/INCLUDE_FILES = new String\[\] {.*};/, 'INCLUDE_FILES = new String[] { ' + includeArrStr + ' };')
182 | .replace(/EXCLUDE_FILES = new String\[\] {.*};/, 'EXCLUDE_FILES = new String[] { ' + excludeArrStr + ' };');
183 |
184 | fs.writeFileSync(sourceFile, content, 'utf-8');
185 | }
186 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cordova-plugin-crypto-file",
3 | "version": "1.4.0",
4 | "description": "This plugin to encrypt/decrypt the source files.",
5 | "repository": {
6 | "type": "git",
7 | "url": "git+https://github.com/PeterHdd/cordova-plugin-crypto-file.git"
8 | },
9 | "keywords": [
10 | "ecosystem:cordova",
11 | "cordova-android",
12 | "cordova-ios"
13 | ],
14 | "author": "PeterHdd",
15 | "license": "Apache version 2.0"
16 | }
17 |
--------------------------------------------------------------------------------
/plugin.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | Crypt File
7 | Encrypts source code
8 | PeterHdd
9 | Apache 2.0 License
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/src/android/com/crypt/cordova/DecryptResource.java:
--------------------------------------------------------------------------------
1 | package com.crypt.cordova;
2 |
3 | import android.net.Uri;
4 | import android.util.Base64;
5 | import android.util.Log;
6 |
7 | import org.apache.cordova.CordovaPlugin;
8 | import org.apache.cordova.CordovaResourceApi;
9 | import org.apache.cordova.LOG;
10 | import org.apache.cordova.CordovaPreferences;
11 |
12 | import java.io.BufferedReader;
13 | import java.io.ByteArrayInputStream;
14 | import java.io.ByteArrayOutputStream;
15 | import java.io.IOException;
16 | import java.io.InputStreamReader;
17 |
18 | import javax.crypto.Cipher;
19 | import javax.crypto.SecretKey;
20 | import javax.crypto.spec.IvParameterSpec;
21 | import javax.crypto.spec.SecretKeySpec;
22 |
23 |
24 | public class DecryptResource extends CordovaPlugin {
25 |
26 | private static final String TAG = "DecryptResource";
27 |
28 | private static final String CRYPT_KEY = "";
29 | private static final String CRYPT_IV = "";
30 |
31 | private static final String[] CRYPT_FILES = {
32 | ".htm",
33 | ".html",
34 | ".js",
35 | ".css",
36 | };
37 |
38 | private String URL_PREFIX;
39 | private String launchUri;
40 |
41 | public void changingPort(CordovaPreferences preferences){
42 | String port = preferences.getString("cryptoPort","8080");
43 | URL_PREFIX = "http://localhost:" + port + "/";
44 | }
45 |
46 | @Override
47 | public Uri remapUri(Uri uri) {
48 | changingPort(preferences);
49 | this.launchUri = uri.toString();
50 | if (this.launchUri.toString().startsWith(URL_PREFIX)) {
51 | return this.toPluginUri(uri);
52 | }
53 | return uri;
54 | }
55 |
56 | @Override
57 | public CordovaResourceApi.OpenForReadResult handleOpenForRead(Uri uri) throws IOException {
58 | Uri oriUri = fromPluginUri(uri);
59 | String uriStr = this.tofileUri(oriUri.toString().split("\\?")[0]);
60 | CordovaResourceApi.OpenForReadResult readResult = this.webView.getResourceApi().openForRead(Uri.parse(uriStr), true);
61 |
62 | if (!isCryptFiles(uriStr)) {
63 | return readResult;
64 | }
65 |
66 | BufferedReader br = new BufferedReader(new InputStreamReader(readResult.inputStream));
67 | StringBuilder strb = new StringBuilder();
68 | String line = null;
69 | while ((line = br.readLine()) != null) {
70 | strb.append(line);
71 | }
72 | br.close();
73 |
74 | byte[] bytes = Base64.decode(strb.toString(), Base64.DEFAULT);
75 |
76 | LOG.d(TAG, "decrypt: " + uriStr);
77 | ByteArrayInputStream byteInputStream = null;
78 | try {
79 | SecretKey skey = new SecretKeySpec(CRYPT_KEY.getBytes("UTF-8"), "AES");
80 | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
81 | cipher.init(Cipher.DECRYPT_MODE, skey, new IvParameterSpec(CRYPT_IV.getBytes("UTF-8")));
82 |
83 | ByteArrayOutputStream bos = new ByteArrayOutputStream();
84 | bos.write(cipher.doFinal(bytes));
85 | byteInputStream = new ByteArrayInputStream(bos.toByteArray());
86 |
87 | } catch (Exception ex) {
88 | LOG.e(TAG, ex.getMessage());
89 | }
90 |
91 | return new CordovaResourceApi.OpenForReadResult(
92 | readResult.uri, byteInputStream, readResult.mimeType, readResult.length, readResult.assetFd);
93 | }
94 |
95 | private String tofileUri(String uri) {
96 | if (uri.startsWith(URL_PREFIX)) {
97 | uri = uri.replace(URL_PREFIX, "file:///android_asset/www/");
98 | }
99 | if (uri.endsWith("/")) {
100 | uri += "index.html";
101 | }
102 | return uri;
103 | }
104 |
105 | private boolean isCryptFiles(String uri) {
106 | for (String ext: CRYPT_FILES) {
107 | if (uri.endsWith(ext)) {
108 | return true;
109 | }
110 | }
111 | return false;
112 | }
113 | }
114 |
--------------------------------------------------------------------------------
/src/ios/CDVCrypt.h:
--------------------------------------------------------------------------------
1 | //
2 | // CDVCrypt.h
3 | // CordovaLib
4 | //
5 | // Created by tkyaji on 2015/07/17.
6 | //
7 | //
8 |
9 | #import
10 |
11 | @interface CDVCrypt : CDVPlugin
12 |
13 | - (void)pluginInitialize;
14 |
15 | @end
16 |
--------------------------------------------------------------------------------
/src/ios/CDVCrypt.m:
--------------------------------------------------------------------------------
1 | //
2 | // CDVCrypt.m
3 | // CordovaLib
4 | //
5 | // Created by tkyaji on 2015/07/17.
6 | //
7 | //
8 |
9 | #import "CDVCrypt.h"
10 | #import "CDVCryptURLProtocol.h"
11 |
12 | @implementation CDVCrypt
13 |
14 | - (void)pluginInitialize
15 | {
16 | [NSURLProtocol registerClass:[CDVCryptURLProtocol class]];
17 | }
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/src/ios/CDVCryptURLProtocol.h:
--------------------------------------------------------------------------------
1 | //
2 | // CDVCryptURLProtocol.h
3 | // CordovaLib
4 | //
5 | // Created by tkyaji on 2015/07/15.
6 | //
7 | //
8 |
9 | #import
10 |
11 | @interface CDVCryptURLProtocol : CDVURLProtocol
12 |
13 | @end
14 |
--------------------------------------------------------------------------------
/src/ios/CDVCryptURLProtocol.m:
--------------------------------------------------------------------------------
1 | //
2 | // CDVCryptURLProtocol.m
3 | // CordovaLib
4 | //
5 | // Created by tkyaji on 2015/07/15.
6 | //
7 | //
8 |
9 | #import "CDVCryptURLProtocol.h"
10 |
11 | #import
12 | #import
13 | #import
14 |
15 |
16 | static NSString* const kCryptKey = @"";
17 | static NSString* const kCryptIv = @"";
18 |
19 | static int const kIncludeFileLength = 0;
20 | static int const kExcludeFileLength = 0;
21 | static NSString* const kIncludeFiles[] = { };
22 | static NSString* const kExcludeFiles[] = { };
23 |
24 |
25 | @implementation CDVCryptURLProtocol
26 |
27 | + (BOOL)canInitWithRequest:(NSURLRequest*)theRequest
28 | {
29 | if ([self checkCryptFile:theRequest.URL]) {
30 | return YES;
31 | }
32 |
33 | return [super canInitWithRequest:theRequest];
34 | }
35 |
36 | - (void)startLoading
37 | {
38 | NSURL* url = self.request.URL;
39 |
40 | if ([[self class] checkCryptFile:url]) {
41 | NSString *mimeType = [self getMimeType:url];
42 |
43 | NSError* error;
44 | NSString* content = [[NSString alloc] initWithContentsOfFile:url.path encoding:NSUTF8StringEncoding error:&error];
45 | if (!error) {
46 | NSData* data = [self decryptAES256WithKey:kCryptKey iv:kCryptIv data:content];
47 | [self sendResponseWithResponseCode:200 data:data mimeType:mimeType];
48 | }
49 | }
50 |
51 | [super startLoading];
52 | }
53 |
54 | + (BOOL)checkCryptFile:(NSURL *)url {
55 | if (![url.scheme isEqual: @"file"]) {
56 | return NO;
57 | }
58 |
59 | NSLog(@"%@", url.path);
60 |
61 | NSString *wwwPath = [[NSBundle mainBundle].resourcePath stringByAppendingString:@"/www/"];
62 | NSString *checkPath = [url.path stringByReplacingOccurrencesOfString:wwwPath withString:@""];
63 |
64 | if (![self hasMatch:checkPath regexArr:kIncludeFiles length:kIncludeFileLength]) {
65 | return NO;
66 | }
67 | if ([self hasMatch:checkPath regexArr:kExcludeFiles length:kExcludeFileLength]) {
68 | return NO;
69 | }
70 |
71 | return YES;
72 | }
73 |
74 | + (BOOL)hasMatch:(NSString *)text regexArr:(NSString* const [])regexArr length:(int)length {
75 | for (int i = 0; i < length; i++) {
76 | NSString* const regex = regexArr[i];
77 | if ([self isMatch:text pattern:regex]) {
78 | return YES;
79 | }
80 | }
81 | return NO;
82 | }
83 |
84 | + (BOOL)isMatch:(NSString *)text pattern:(NSString *)pattern {
85 | NSError *error = nil;
86 | NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
87 | if (error) {
88 | return NO;
89 | }
90 | if ([regex firstMatchInString:text options:0 range:NSMakeRange(0, text.length)]) {
91 | return YES;
92 | }
93 | return NO;
94 | }
95 |
96 | - (NSString*)getMimeType:(NSURL *)url
97 | {
98 | NSString *fullPath = url.path;
99 | NSString *mimeType = nil;
100 |
101 | if (fullPath) {
102 | CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);
103 | if (typeId) {
104 | mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);
105 | if (!mimeType) {
106 | // special case for m4a
107 | if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {
108 | mimeType = @"audio/mp4";
109 | } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {
110 | mimeType = @"audio/wav";
111 | } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) {
112 | mimeType = @"text/css";
113 | }
114 | }
115 | CFRelease(typeId);
116 | }
117 | }
118 | return mimeType;
119 | }
120 |
121 | - (NSData *)decryptAES256WithKey:(NSString *)key iv:(NSString *)iv data:(NSString *)base64String {
122 |
123 | NSData *data = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
124 |
125 | size_t bufferSize = [data length] + kCCBlockSizeAES128;
126 | void *buffer = malloc(bufferSize);
127 | size_t numBytesDecrypted = 0;
128 |
129 | NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
130 | NSData *ivData = [iv dataUsingEncoding:NSUTF8StringEncoding];
131 |
132 | CCCryptorStatus status = CCCrypt(kCCDecrypt,
133 | kCCAlgorithmAES128,
134 | kCCOptionPKCS7Padding,
135 | keyData.bytes,
136 | kCCKeySizeAES256,
137 | ivData.bytes,
138 | data.bytes,
139 | data.length,
140 | buffer,
141 | bufferSize,
142 | &numBytesDecrypted);
143 |
144 | if (status == kCCSuccess) {
145 | return [NSData dataWithBytes:buffer length:numBytesDecrypted];
146 | }
147 | free(buffer);
148 |
149 | return nil;
150 | }
151 |
152 | - (NSString*)getMimeTypeFromPath:(NSString*)fullPath
153 | {
154 | NSString* mimeType = nil;
155 |
156 | if (fullPath) {
157 | CFStringRef typeId = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)[fullPath pathExtension], NULL);
158 | if (typeId) {
159 | mimeType = (__bridge_transfer NSString*)UTTypeCopyPreferredTagWithClass(typeId, kUTTagClassMIMEType);
160 | if (!mimeType) {
161 | // special case for m4a
162 | if ([(__bridge NSString*)typeId rangeOfString : @"m4a-audio"].location != NSNotFound) {
163 | mimeType = @"audio/mp4";
164 | } else if ([[fullPath pathExtension] rangeOfString:@"wav"].location != NSNotFound) {
165 | mimeType = @"audio/wav";
166 | } else if ([[fullPath pathExtension] rangeOfString:@"css"].location != NSNotFound) {
167 | mimeType = @"text/css";
168 | }
169 | }
170 | CFRelease(typeId);
171 | }
172 | }
173 | return mimeType;
174 | }
175 |
176 | - (void)sendResponseWithResponseCode:(NSInteger)statusCode data:(NSData*)data mimeType:(NSString*)mimeType
177 | {
178 | if (mimeType == nil) {
179 | mimeType = @"text/plain";
180 | }
181 |
182 | NSHTTPURLResponse* response = [[NSHTTPURLResponse alloc] initWithURL:[[self request] URL] statusCode:statusCode HTTPVersion:@"HTTP/1.1" headerFields:@{@"Content-Type" : mimeType}];
183 |
184 | [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
185 | if (data != nil) {
186 | [[self client] URLProtocol:self didLoadData:data];
187 | }
188 | [[self client] URLProtocolDidFinishLoading:self];
189 | }
190 |
191 |
192 | @end
193 |
--------------------------------------------------------------------------------