├── .github └── workflows │ ├── ci.yaml │ └── codeql-analysis.yml ├── .gitignore ├── LICENSE ├── README.md ├── icon.png ├── requirements.txt ├── screenshot.png └── src ├── .gitignore ├── pyRanoid ├── .gitignore ├── __init__.py ├── cli.py ├── gui.py └── utils.py └── tests └── test_utils.py /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | on: 3 | push: 4 | branches: 5 | - master 6 | pull_request: 7 | branches: 8 | - master 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Install Python 3 16 | uses: actions/setup-python@v1 17 | with: 18 | python-version: 3.9 19 | - name: Install dependencies 20 | run: | 21 | python -m pip install --upgrade pip 22 | pip install -r requirements.txt 23 | - name: Run tests with pytest 24 | run: pytest 25 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | name: "CodeQL" 7 | 8 | on: 9 | push: 10 | branches: [master] 11 | pull_request: 12 | # The branches below must be a subset of the branches above 13 | branches: [master] 14 | schedule: 15 | - cron: '0 5 * * 4' 16 | 17 | jobs: 18 | analyze: 19 | name: Analyze 20 | runs-on: ubuntu-latest 21 | 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | # Override automatic language detection by changing the below list 26 | # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] 27 | language: ['python'] 28 | # Learn more... 29 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection 30 | 31 | steps: 32 | - name: Checkout repository 33 | uses: actions/checkout@v2 34 | 35 | # Initializes the CodeQL tools for scanning. 36 | - name: Initialize CodeQL 37 | uses: github/codeql-action/init@v1 38 | with: 39 | languages: ${{ matrix.language }} 40 | # If you wish to specify custom queries, you can do so here or in a config file. 41 | # By default, queries listed here will override any specified in a config file. 42 | # Prefix the list here with "+" to use these queries and those in the config file. 43 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 44 | 45 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 46 | # If this step fails, then you should remove it and run the build manually (see below) 47 | - name: Autobuild 48 | uses: github/codeql-action/autobuild@v1 49 | 50 | # ℹ️ Command-line programs to run using the OS shell. 51 | # 📚 https://git.io/JvXDl 52 | 53 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 54 | # and modify them (or add more) to build your code if your project 55 | # uses a compiled language 56 | 57 | #- run: | 58 | # make bootstrap 59 | # make release 60 | 61 | - name: Perform CodeQL Analysis 62 | uses: github/codeql-action/analyze@v1 63 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | output.png 2 | __pycache__ 3 | .vscode 4 | *.pem 5 | *.tar.gz* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyRanoid :lock: ![Tests](https://github.com/omnone/pyRanoid/workflows/Tests/badge.svg) ![CodeQL](https://github.com/omnone/pyRanoid/workflows/CodeQL/badge.svg) 2 | **PyRanoid** is a Python program designed to provide advanced encryption and steganography capabilities for your files. It utilizes AES 256 encryption to securely encrypt your files and then employs steganography techniques to hide the encrypted data within an image. Currently tested with Python 3.9. 3 | 4 | 5 | 6 | ## Requirements 7 |
    8 |
  • Python 3.9 or higher
  • 9 |
  • Dependencies (listed in the requirements.txt file)
  • 10 |
  • OpenSSL
  • 11 |
12 | 13 | ## Contributing 14 | Contributions to PyRanoid are welcome! If you encounter any issues or have ideas for enhancements, please feel free to submit a pull request or create an issue in the project's repository. 15 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/omnone/pyRanoid/277df01354ca9d4fc6b83e8c8b9b3d72e99640ac/icon.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Pillow 2 | pyfiglet==0.8.post1 3 | InquirerPy 4 | pytest==6.1.1 5 | prompt-toolkit 6 | tqdm==4.43.0 7 | ttkthemes==3.1.1 8 | termcolor==1.1.0 9 | -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/omnone/pyRanoid/277df01354ca9d4fc6b83e8c8b9b3d72e99640ac/screenshot.png -------------------------------------------------------------------------------- /src/.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | *.tar.gz -------------------------------------------------------------------------------- /src/pyRanoid/.gitignore: -------------------------------------------------------------------------------- 1 | /__pycache__ 2 | *.png 3 | *.pem 4 | *.png 5 | *.jpg -------------------------------------------------------------------------------- /src/pyRanoid/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/omnone/pyRanoid/277df01354ca9d4fc6b83e8c8b9b3d72e99640ac/src/pyRanoid/__init__.py -------------------------------------------------------------------------------- /src/pyRanoid/cli.py: -------------------------------------------------------------------------------- 1 | import utils as utils 2 | import pyfiglet 3 | from InquirerPy import prompt 4 | from InquirerPy.validator import PathValidator 5 | import sys 6 | from termcolor import colored 7 | 8 | 9 | print("\------------------------------------------------------------------------------------------------") 10 | print(pyfiglet.figlet_format("pyRanoid")+"\n") 11 | print(colored("(github.com/omnone/pyRanoid)", "cyan")) 12 | print("\------------------------------------------------------------------------------------------------") 13 | 14 | questions = [ 15 | { 16 | "type": "list", 17 | "name": "op", 18 | "message": "Select an operation:", 19 | "choices": ["Encrypt to an image", "Decrypt from an image", "Quit"], 20 | }, 21 | { 22 | "type": "input", 23 | "name": "image_path", 24 | "message": "Enter image path:", 25 | "validate": PathValidator("Path is not valid"), 26 | "when": lambda user_input: user_input["op"] != "Quit" 27 | 28 | }, 29 | { 30 | "type": "input", 31 | "name": "target_path", 32 | "message": "Enter target path:", 33 | "validate": PathValidator("Path is not valid"), 34 | "when": lambda user_input: user_input["op"] != "Decrypt from an image" and 35 | user_input["op"] != "Quit" 36 | }, 37 | { 38 | "type": "password", 39 | "name": "passw", 40 | "message": "Enter password:", 41 | "when": lambda user_input: user_input["op"] != "Quit" 42 | 43 | }, 44 | { 45 | "type": "password", 46 | "name": "passw_verify", 47 | "message": "Reenter password:", 48 | "when": lambda user_input: user_input["op"] != "Quit" 49 | 50 | } 51 | 52 | ] 53 | 54 | user_input = prompt(questions) 55 | 56 | if user_input["op"] == "Encrypt to an image": 57 | 58 | if user_input["passw"] == user_input["passw_verify"]: 59 | utils.encrypt_image( 60 | user_input["image_path"], user_input["target_path"], 61 | password=user_input["passw"]) 62 | else: 63 | print("Passwords dont match") 64 | 65 | 66 | elif user_input["op"] == "Decrypt from an image": 67 | 68 | decrypted_msg = utils.decrypt_image( 69 | user_input["image_path"], password=user_input["passw"]) 70 | 71 | else: 72 | sys.exit(0) 73 | -------------------------------------------------------------------------------- /src/pyRanoid/gui.py: -------------------------------------------------------------------------------- 1 | # ============================================================================================ 2 | # MIT License 3 | # Copyright (c) 2020 Konstantinos Bourantas 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | # ============================================================================================ 23 | import utils 24 | import tkinter as tk 25 | import tkinter.ttk as ttk 26 | from tkinter import filedialog 27 | import threading 28 | from ttkthemes import ThemedTk 29 | import sys 30 | import pyfiglet 31 | from PIL import ImageTk, Image 32 | import os 33 | 34 | import logging 35 | logging.basicConfig(level=logging.DEBUG) 36 | # ============================================================================================ 37 | 38 | 39 | class pyRanoid: 40 | def __init__(self, root, image=None): 41 | 42 | root.minsize(1000, 500) 43 | root.title("PyRanoid") 44 | root.resizable(False, False) 45 | 46 | # icon made by : https://www.flaticon.com/authors/becris 47 | self.base_path = os.path.dirname(__file__) 48 | icon_path = os.path.join(self.base_path, "../../icon.png") 49 | 50 | try: 51 | ico = Image.open(os.path.abspath(os.path.realpath(icon_path))) 52 | except Exception: 53 | logging.error("Exception:", exc_info=True) 54 | else: 55 | photo = ImageTk.PhotoImage(ico) 56 | root.wm_iconphoto(False, photo) 57 | 58 | self.export_checkbox = None 59 | self.export_opt = 0 60 | self.image_path = None 61 | self.target_path = None 62 | self.rsa_key_path = None 63 | self.target_to_encrypt = None 64 | 65 | self.root = root 66 | 67 | self.inputs_frame = ttk.Frame(root, borderwidth=1, relief=tk.SUNKEN) 68 | self.inputs_frame.grid(row=0, column=0, pady=10, 69 | padx=30, sticky=tk.W+tk.E) 70 | self.inputs_frame["padding"] = (5, 20, 5, 20) 71 | 72 | self.output_frame = ttk.Frame(root, borderwidth=1, relief=tk.SUNKEN) 73 | self.output_frame.grid(row=6, column=0, rowspan=8, 74 | pady=5, padx=10, sticky=tk.W+tk.E) 75 | self.output_frame["padding"] = (5, 0, 5, 0) 76 | self.output_frame.columnconfigure(0, weight=1) 77 | 78 | self.image_frame = ttk.Frame(self.inputs_frame) 79 | self.image_frame.grid(row=2, column=2, rowspan=10, 80 | columnspan=10, pady=30, padx=30) 81 | 82 | # ----------------------------------------------- 83 | # operation type combobox 84 | self.op_type = tk.StringVar() 85 | self.op_label = ttk.Label( 86 | self.inputs_frame, text="Operation Type:") 87 | self.op_label.grid(row=0, column=0, sticky=tk.W) 88 | self.op_dropdown = ttk.Combobox( 89 | self.inputs_frame, textvariable=self.op_type, 90 | state="readonly", width=27) 91 | self.op_dropdown.grid(row=1, column=0, sticky=tk.W) 92 | self.op_dropdown["values"] = ("encrypt", "decrypt") 93 | self.op_dropdown.current(0) 94 | self.op_dropdown.bind( 95 | "<>", lambda _: self.op_type_changed()) 96 | 97 | # -------------------------------------------------------------------------------------------- 98 | # Input type combobox 99 | self.input_type = tk.StringVar() 100 | self.input_label = ttk.Label(self.inputs_frame, text="Input Type:") 101 | self.input_label.grid(row=0, column=1, sticky=tk.W) 102 | self.input_dropdown = ttk.Combobox( 103 | self.inputs_frame, textvariable=self.input_type, 104 | state="readonly", width=27) 105 | self.input_dropdown.grid(row=1, column=1, sticky=tk.W) 106 | self.input_dropdown["values"] = ("File", ) 107 | self.input_dropdown.current(0) 108 | self.input_dropdown.bind( 109 | "<>", lambda _: self.input_type_changed()) 110 | 111 | # -------------------------------------------------------------------------------------------- 112 | # Image selection 113 | self.source_img_path_label = ttk.Label( 114 | self.inputs_frame, text="Image Path:") 115 | self.source_img_path_label.grid(row=2, column=0, sticky=tk.W) 116 | 117 | self.source_img_path_input = ttk.Entry(self.inputs_frame, width="50") 118 | self.source_img_path_input.grid(row=3, column=0, sticky=tk.W) 119 | 120 | self.img_picker_btn = ttk.Button(self.inputs_frame, text="Open", width=8, 121 | command=lambda: self.select_image_file()) 122 | self.img_picker_btn.grid(row=3, column=1, sticky=tk.W) 123 | 124 | # -------------------------------------------------------------------------------------------- 125 | # target file selection 126 | self.target_path_label = ttk.Label( 127 | self.inputs_frame, text="Target Path:") 128 | self.target_path_label.grid(row=4, column=0, sticky=tk.W) 129 | 130 | self.target_path_entry = ttk.Entry(self.inputs_frame, width="50") 131 | self.target_path_entry.grid(row=5, column=0, sticky=tk.W) 132 | 133 | self.target_picker_btn = ttk.Button(self.inputs_frame, text="Open", width=8, 134 | command=lambda: self.select_target_file()) 135 | self.target_picker_btn.grid(row=5, column=1, sticky=tk.W) 136 | 137 | self.text_msg_label = ttk.Label( 138 | self.inputs_frame, text="Text Message:") 139 | self.text_msg_entry = ttk.Entry(self.inputs_frame, width="50") 140 | # -------------------------------------------------------------------------------------------- 141 | # password input 142 | self.password_label = ttk.Label(self.inputs_frame, text="Password:") 143 | self.password_label.grid(row=6, column=0, sticky=tk.W) 144 | 145 | self.password_entry = ttk.Entry( 146 | self.inputs_frame, show="*", width="30") 147 | self.password_entry.grid(row=7, column=0, sticky=tk.W) 148 | 149 | # -------------------------------------------------------------------------------------------- 150 | # Text area 151 | self.text_area = tk.Text(self.output_frame, height=18, 152 | width=95, bg="black", fg="darkorchid1", 153 | insertbackground="darkorchid1") 154 | self.text_area.config(state="normal") 155 | self.text_area.grid(row=8, column=0, rowspan=2, 156 | sticky=tk.W+tk.E+tk.N+tk.S, pady=5) 157 | 158 | self.text_area.columnconfigure(0, weight=1) 159 | self.output_frame.columnconfigure(0, weight=1) 160 | self.root.columnconfigure(0, weight=1) 161 | 162 | # # -------------------------------------------------------------------------------------------- 163 | # # ascii banner 164 | self.ascii_banner = pyfiglet.figlet_format("pyRanoid") 165 | self.text_area.insert( 166 | tk.END, f"{self.ascii_banner}\n*Stay safe, use a strong password!\n-------------------------------------------------------------------------------------------") 167 | 168 | # # -------------------------------------------------------------------------------------------- 169 | # progress bar 170 | self.progress_bar = ttk.Progressbar( 171 | self.output_frame, orient="horizontal", 172 | length=650, mode="indeterminate") 173 | self.progress_bar.columnconfigure(0, weight=1) 174 | 175 | # # -------------------------------------------------------------------------------------------- 176 | # # cancel button 177 | self.cancel_btn = ttk.Button(self.output_frame, text="Exit", width=8, 178 | command=lambda: sys.exit(0)) 179 | self.cancel_btn.grid(row=13, column=3, sticky=tk.E, pady=10) 180 | 181 | self.op_type_changed() 182 | self.input_type_changed() 183 | 184 | self.root.mainloop() 185 | # -------------------------------------------------------------------------------------------- 186 | 187 | def op_handler(self): 188 | """encrypt/decrypt operations on selected image""" 189 | if self.input_type.get() == "Text": 190 | self.target_to_encrypt = self.text_msg_entry.get() 191 | else: 192 | self.target_to_encrypt = self.target_path 193 | 194 | if self.op_type.get() == "encrypt": 195 | password_score = self.password_score( 196 | self.password_entry.get().strip("\n")) 197 | 198 | if password_score <= 3: 199 | utils.log_handler( 200 | self, f"[!]Caution your password is weak!") 201 | 202 | utils.log_handler( 203 | self, f"[*]Encrypting {self.target_to_encrypt}...") 204 | self.worker_thread = threading.Thread( 205 | target=utils.encrypt_image, args=(self.source_img_path_input.get(), 206 | self.target_to_encrypt, self)) 207 | 208 | else: 209 | utils.log_handler(self, f"[*]Decrypting {self.image_path}") 210 | 211 | self.worker_thread = threading.Thread( 212 | target=utils.decrypt_image, args=(self.source_img_path_input.get(), self)) 213 | 214 | self.progress_bar.grid(row=5, column=0, sticky=tk.W) 215 | self.progress_bar.start() 216 | 217 | self.worker_thread.daemon = True 218 | self.worker_thread.start() 219 | self.root.after(100, self.progress_handler) 220 | # -------------------------------------------------------------------------------------------- 221 | 222 | def progress_handler(self): 223 | 224 | if (self.worker_thread.is_alive()): 225 | self.root.after(100, self.progress_handler) 226 | return 227 | else: 228 | self.progress_bar.stop() 229 | self.progress_bar.grid_remove() 230 | 231 | # -------------------------------------------------------------------------------------------- 232 | 233 | def input_type_changed(self): 234 | if (self.input_type.get() == "Text"): 235 | self.text_msg_label.grid(row=4, column=0, sticky=tk.W) 236 | self.text_msg_entry.grid(row=5, column=0, sticky=tk.W) 237 | self.target_path_label.grid_remove() 238 | self.target_path_entry.grid_remove() 239 | self.target_picker_btn.grid_remove() 240 | else: 241 | self.target_path_label.grid(row=4, column=0, sticky=tk.W) 242 | self.target_path_entry.grid(row=5, column=0, sticky=tk.W) 243 | self.target_picker_btn.grid(row=5, column=1, sticky=tk.W) 244 | self.text_msg_label.grid_remove() 245 | self.text_msg_entry.grid_remove() 246 | # -------------------------------------------------------------------------------------------- 247 | 248 | def op_type_changed(self): 249 | selected_op = self.op_type.get() 250 | if selected_op == "encrypt": 251 | if self.export_checkbox: 252 | self.export_checkbox.grid_remove() 253 | self.input_type_changed() 254 | else: 255 | self.target_path_label.grid_remove() 256 | self.target_path_entry.grid_remove() 257 | self.target_picker_btn.grid_remove() 258 | self.text_msg_entry.grid_remove() 259 | self.text_msg_label.grid_remove() 260 | 261 | # encrypt/decrypt button 262 | self.image_op_btn = ttk.Button(self.inputs_frame, text=selected_op, width=8, 263 | command=lambda: self.op_handler(), 264 | state="normal" if self.image_path else "disabled") 265 | self.image_op_btn.grid(row=1, column=2) 266 | 267 | # -------------------------------------------------------------------------------------------- 268 | 269 | def select_image_file(self): 270 | """Open an image from a directory""" 271 | # Select the Imagename from a folder 272 | tk.Tk().withdraw() 273 | self.image_path = filedialog.askopenfilename(title="Open Image", filetypes=[ 274 | ("Image Files", ".png .jpg .jpeg")]) 275 | self.source_img_path_input.delete(0, tk.END) 276 | self.source_img_path_input.insert(tk.INSERT, self.image_path) 277 | 278 | # opens the image 279 | source_image = Image.open(self.image_path) 280 | 281 | max_width = 300 282 | width, height = source_image.size 283 | aspect_ratio = width / height 284 | scaled_width = min(width, max_width) 285 | scaled_height = int(scaled_width / aspect_ratio) 286 | 287 | # resize the image and apply a high-quality down sampling filter 288 | source_image = source_image.resize( 289 | (scaled_width, scaled_height), Image.ANTIALIAS) 290 | 291 | # PhotoImage class is used to add image to widgets, icons etc 292 | source_image = ImageTk.PhotoImage(source_image) 293 | 294 | # create a label 295 | self.panel = ttk.Label(self.image_frame, image=source_image) 296 | 297 | # set the image as source_image 298 | self.panel.image = source_image 299 | self.panel.grid(row=6, column=3, padx=5) 300 | 301 | try: 302 | self.image_op_btn["state"] = "normal" 303 | except Exception: 304 | logging.error("Exception:", exc_info=True) 305 | 306 | # -------------------------------------------------------------------------------------------- 307 | 308 | def select_target_file(self): 309 | """Select file to encrypt from a directory""" 310 | tk.Tk().withdraw() 311 | self.target_path = filedialog.askopenfilename(title="Select File") 312 | self.target_path_entry.delete(0, tk.END) 313 | self.target_path_entry.insert(tk.INSERT, self.target_path) 314 | 315 | try: 316 | self.image_op_btn["state"] = "normal" 317 | except Exception: 318 | logging.error("Exception:", exc_info=True) 319 | 320 | # -------------------------------------------------------------------------------------------- 321 | 322 | def password_score(self, password): 323 | score = 0 324 | 325 | if len(password) >= 8: 326 | score += 1 327 | 328 | if any(char.isupper() for char in password): 329 | score += 1 330 | if any(char.islower() for char in password): 331 | score += 1 332 | if any(char.isdigit() for char in password): 333 | score += 1 334 | if any(not char.isalnum() for char in password): 335 | score += 1 336 | 337 | unique_chars = set(password) 338 | if len(unique_chars) >= len(password) / 2: 339 | score += 1 340 | 341 | return score 342 | 343 | 344 | if __name__ == "__main__": 345 | root = ThemedTk(background=True, theme="equilux") 346 | pyRanoid(root) 347 | -------------------------------------------------------------------------------- /src/pyRanoid/utils.py: -------------------------------------------------------------------------------- 1 | # ============================================================================================ 2 | # MIT License 3 | # Copyright (c) 2020 Konstantinos Bourantas 4 | 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | # Part of the code was taken from: 23 | # https://itnext.io/steganography-101-lsb-introduction-with-python-4c4803e08041 24 | # ============================================================================================ 25 | 26 | import datetime 27 | from hashlib import pbkdf2_hmac 28 | import subprocess 29 | import tarfile 30 | from PIL import Image 31 | import tkinter as tk 32 | import os 33 | from shutil import which 34 | 35 | buffer_size = 64 * 1024 36 | _OPENSSL_EXECUTABLE = which("openssl") 37 | 38 | if not _OPENSSL_EXECUTABLE: 39 | raise Exception("You need to install openssl!") 40 | 41 | TAR_FILE_PATH = "output.tar.gz" 42 | FINAL_PNG_PATH = "output.png" 43 | ENCR_FILE_PATH = "output.prnd" 44 | 45 | # -------------------------------------------------------------------------------------------- 46 | 47 | 48 | def file_to_bin(file_path): 49 | with open(file_path, "rb") as file: 50 | file_data = file.read() 51 | return "".join(format(byte, "08b") for byte in file_data) 52 | # -------------------------------------------------------------------------------------------- 53 | 54 | 55 | def str_to_bin(input): 56 | return "".join(format(ord(char), "08b") for char in input) 57 | 58 | # -------------------------------------------------------------------------------------------- 59 | 60 | 61 | def int_to_bin(x): 62 | return "{0:b}".format(x) 63 | 64 | 65 | # -------------------------------------------------------------------------------------------- 66 | 67 | 68 | def log_handler(gui, msg): 69 | msg = f"\n[{datetime.datetime.now()}] {msg}" 70 | if gui: 71 | gui.text_area.insert(tk.END, msg) 72 | else: 73 | print(msg) 74 | 75 | # -------------------------------------------------------------------------------------------- 76 | 77 | 78 | def encrypt_image(image_path, target_path, gui=None, **kwargs): 79 | 80 | output_path = None 81 | 82 | try: 83 | if os.path.isfile(target_path): 84 | password = gui.password_entry.get().strip( 85 | "\n") if gui else kwargs["password"] 86 | 87 | output_path, err = encryption_handler(target_path, 88 | password) 89 | 90 | if err: 91 | raise Exception("Encryption failed!") 92 | 93 | log_handler(gui, "[+]Encryption finished!") 94 | else: 95 | return 96 | 97 | except Exception as e: 98 | log_handler(gui, f"[-]Exception occured: {e}") 99 | 100 | return 101 | 102 | try: 103 | log_handler(gui, f"[*]Writing encrypted file to image {image_path}") 104 | 105 | file_contents = file_to_bin(output_path) 106 | file_total_bytes = len(file_contents) 107 | file_length = int_to_bin(file_total_bytes) 108 | 109 | # save all information in order to be able to locate the hidden data 110 | data_to_hide = format(len(file_length), "b").zfill(8) + \ 111 | file_length + file_contents 112 | 113 | with Image.open(image_path) as img: 114 | width, height = img.size 115 | bit_counter = pixel_count = 0 116 | image_capacity = (width*height*3)//8 117 | pixels_needed = (file_total_bytes * 8) // 3 118 | 119 | log_handler(gui, f"[*]Going to need {pixels_needed} pixels") 120 | 121 | if image_capacity < file_total_bytes: 122 | raise Exception( 123 | f'[-]You need a bigger image! your file is {file_total_bytes} bytes but your image fits up to {image_capacity}.') 124 | 125 | for x in range(0, width): 126 | for y in range(0, height): 127 | if pixel_count >= pixels_needed: 128 | break 129 | 130 | pixel = list(img.getpixel((x, y))) 131 | 132 | for n in range(0, 3): 133 | if (bit_counter < len(data_to_hide)): 134 | pixel[n] = pixel[n] & 0 | int( 135 | data_to_hide[bit_counter]) 136 | bit_counter += 1 137 | 138 | img.putpixel((x, y), tuple(pixel)) 139 | pixel_count += 1 140 | 141 | final_img_path = os.path.join(os.path.dirname( 142 | image_path), FINAL_PNG_PATH) 143 | 144 | img.save(final_img_path, "PNG") 145 | 146 | log_handler( 147 | gui, "[+]Encryption finished!") 148 | 149 | except Exception as e: 150 | log_handler(gui, f"[-]Exception occured: {e}") 151 | else: 152 | log_handler(gui, f"[+]Final image ready {final_img_path}") 153 | finally: 154 | if output_path and os.path.exists(output_path): 155 | os.remove(output_path) 156 | 157 | if gui: 158 | gui.image_op_btn["state"] = "normal" 159 | else: 160 | return True 161 | 162 | # -------------------------------------------------------------------------------------------- 163 | 164 | 165 | def decrypt_image(image_path, gui=None, **kwargs): 166 | 167 | password = gui.password_entry.get().strip( 168 | "\n") if gui else kwargs["password"] 169 | 170 | if gui: 171 | gui.image_op_btn["state"] = "disable" 172 | 173 | try: 174 | extracted_bin = [] 175 | 176 | with Image.open(image_path) as img: 177 | width, height = img.size 178 | extraction_completed = False 179 | length = length_of_data = None 180 | 181 | for x in range(0, width): 182 | if extraction_completed: 183 | break 184 | 185 | for y in range(0, height): 186 | pixel = list(img.getpixel((x, y))) 187 | 188 | for n in range(0, 3): 189 | extracted_bin.append(pixel[n] & 1) 190 | 191 | if length is None and len(extracted_bin) >= 8: 192 | length = int( 193 | "".join([str(i) for i in extracted_bin[0:8]]), 2) 194 | 195 | if length is not None and \ 196 | len(extracted_bin) >= 8 + length: 197 | length_of_data = int("".join([str(i) 198 | for i in extracted_bin[8:length+8]]), 2) 199 | 200 | if length_of_data is not None and \ 201 | len(extracted_bin) >= 8 + length + length_of_data: 202 | extraction_completed = True 203 | 204 | if extraction_completed: 205 | break 206 | 207 | if length is not None: 208 | binary_msg = int( 209 | "".join([str(extracted_bin[i+8+length]) for i in range(length_of_data)]), 2) 210 | else: 211 | raise Exception( 212 | f"[-]Couldn't extract hidden file from {image_path}, image file is corrupted!") 213 | 214 | decrypted_msg = binary_msg.to_bytes( 215 | (binary_msg.bit_length() + 7) // 8, "big") 216 | 217 | with open(ENCR_FILE_PATH, "wb") as f: 218 | f.write(decrypted_msg) 219 | 220 | _, err = encryption_handler(ENCR_FILE_PATH, password, decrypt=True) 221 | 222 | if err: 223 | raise Exception("Decryption failed!") 224 | 225 | except Exception as e: 226 | log_handler(gui, f"[-]Exception occured: {e}") 227 | else: 228 | extract_tar_archive(TAR_FILE_PATH, ".") 229 | 230 | log_handler( 231 | gui, f"[+]Hidden file has been exported succesfuly to {os.getcwd()}") 232 | finally: 233 | if os.path.exists(TAR_FILE_PATH): 234 | os.remove(TAR_FILE_PATH) 235 | 236 | if os.path.exists(ENCR_FILE_PATH): 237 | os.remove(ENCR_FILE_PATH) 238 | 239 | if gui: 240 | gui.image_op_btn["state"] = "normal" 241 | 242 | # -------------------------------------------------------------------------------------------- 243 | 244 | 245 | def create_tar_archive(source_file, filename): 246 | tar_path = filename.split(".")[0] 247 | 248 | with tarfile.open(tar_path, "w") as tar: 249 | tar.add(source_file, arcname=filename) 250 | 251 | return tar_path 252 | 253 | # -------------------------------------------------------------------------------------------- 254 | 255 | 256 | def extract_tar_archive(archive_file, output_directory): 257 | with tarfile.open(archive_file, "r") as tar: 258 | tar.extractall(output_directory) 259 | 260 | # -------------------------------------------------------------------------------------------- 261 | 262 | 263 | def encryption_handler(target_filepath, password, decrypt=False): 264 | 265 | target_filename = os.path.basename(target_filepath) 266 | 267 | open_ssl_cmd = [_OPENSSL_EXECUTABLE, "enc"] 268 | 269 | if decrypt: 270 | open_ssl_cmd.append("-d") 271 | else: 272 | target_filename = create_tar_archive(target_filepath, target_filename) 273 | 274 | final_path = target_filename.split( 275 | ".prnd")[0]+".tar.gz" if decrypt else target_filename + ".prnd" 276 | 277 | open_ssl_cmd.extend(["-aes-256-cbc", "-in", target_filename, 278 | "-out", final_path, "-md", "sha256", 279 | "-pass", "stdin"]) 280 | 281 | password = password.encode("utf8") 282 | 283 | process = subprocess.Popen(open_ssl_cmd, 284 | stdin=subprocess.PIPE, 285 | stdout=subprocess.PIPE, 286 | stderr=subprocess.PIPE) 287 | encr_key = pbkdf2_hmac( 288 | "sha256", password, password[::-1], 20000) 289 | 290 | _, stderr = process.communicate(input=encr_key) 291 | 292 | if not decrypt: 293 | os.remove(target_filename) 294 | 295 | if process.returncode != 0: 296 | return None, stderr.decode("utf-8") 297 | 298 | return final_path, None 299 | -------------------------------------------------------------------------------- /src/tests/test_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import sys 3 | import os 4 | from PIL import Image 5 | 6 | test_dir = os.path.dirname(__file__) 7 | src_dir = "../" 8 | sys.path.insert(0, os.path.abspath(os.path.join(test_dir, src_dir))) 9 | 10 | # fmt: off 11 | import pyRanoid.utils as utils 12 | # fmt: on 13 | 14 | 15 | class Testutils(unittest.TestCase): 16 | 17 | @classmethod 18 | def tearDownClass(self): 19 | try: 20 | os.remove("output.png") 21 | except FileNotFoundError: 22 | pass 23 | 24 | def tearDown(self): 25 | if os.path.exists("test_file.txt"): 26 | os.remove("test_file.txt") 27 | 28 | if os.path.exists("test_image.png"): 29 | os.remove("test_image.png") 30 | 31 | if os.path.exists("output.tar.gz"): 32 | os.remove("output.tar.gz") 33 | 34 | def setUp(self): 35 | # Create a test file 36 | self.file_path = "test_file.txt" 37 | with open(self.file_path, "w") as file: 38 | file.write("This is a test file.") 39 | 40 | # Create a test image 41 | self.image_path = "test_image.png" 42 | image = Image.new("RGB", (1000, 1000), color=(255, 255, 255)) 43 | image.save(self.image_path) 44 | 45 | def test_utils1(self): 46 | """ 47 | Test that image encrypt works. 48 | """ 49 | utils.encrypt_image( 50 | self.image_path, self.file_path, password="test") 51 | 52 | self.assertTrue(os.path.exists("output.png")) 53 | 54 | def test_utils2(self): 55 | """ 56 | Test that image decrypt works and hidden file is exported 57 | """ 58 | utils.decrypt_image("output.png", password="test") 59 | 60 | with open(self.file_path, "r") as f: 61 | self.assertEqual(f.read(), "This is a test file.") 62 | 63 | 64 | if __name__ == "__main__": 65 | unittest.main() 66 | --------------------------------------------------------------------------------