├── .github ├── CODEOWNERS ├── dependabot.yml └── workflows │ ├── release-build.yml │ ├── test-build-android.yml │ ├── test-build-linux.yml │ ├── test-build-windows.yml │ └── test-coverage.yml ├── .gitignore ├── .testcoverage.yml ├── FyneApp.toml ├── LICENSE ├── README.md ├── VERSION ├── cmd └── picogo │ ├── main.go │ └── main_test.go ├── go.mod ├── go.sum ├── icon.png ├── internal ├── encryption │ ├── ciphers.go │ ├── consistency_test.go │ ├── decrypt.go │ ├── docs │ │ └── code_architecture.md │ ├── encrypt.go │ ├── encryption.go │ ├── expected_errors_test.go │ ├── header.go │ ├── keys.go │ ├── keys_test.go │ ├── picocrypt_compatibility_test.go │ ├── picocrypt_samples │ │ ├── basefiles │ │ │ ├── base0 │ │ │ ├── base1000 │ │ │ └── base1048570 │ │ ├── headers │ │ │ ├── zerofile1024.header │ │ │ └── zerofile65498251264.header │ │ ├── keyfiles │ │ │ ├── keyfile1 │ │ │ └── keyfile2 │ │ ├── v1.47 │ │ │ ├── base0.pcv │ │ │ ├── base0_c.pcv │ │ │ ├── base0_d.pcv │ │ │ ├── base0_kf1.pcv │ │ │ ├── base0_kf12.pcv │ │ │ ├── base0_kf12o.pcv │ │ │ ├── base0_p.pcv │ │ │ ├── base0_p_r_d_kf12o.pcv │ │ │ ├── base0_r.pcv │ │ │ ├── base1000.pcv │ │ │ ├── base1000_c.pcv │ │ │ ├── base1000_c_p_r_d_kf12o.pcv │ │ │ ├── base1000_d.pcv │ │ │ ├── base1000_kf1.pcv │ │ │ ├── base1000_kf12.pcv │ │ │ ├── base1000_kf12o.pcv │ │ │ ├── base1000_p.pcv │ │ │ ├── base1000_r.pcv │ │ │ ├── base1048570.pcv │ │ │ ├── base1048570_c.pcv │ │ │ ├── base1048570_d.pcv │ │ │ ├── base1048570_kf1.pcv │ │ │ ├── base1048570_kf12.pcv │ │ │ ├── base1048570_kf12o.pcv │ │ │ ├── base1048570_p.pcv │ │ │ ├── base1048570_p_r_d_kf12o.pcv │ │ │ └── base1048570_r.pcv │ │ └── v1.48 │ │ │ ├── base0.pcv │ │ │ ├── base0_c.pcv │ │ │ ├── base0_d.pcv │ │ │ ├── base0_kf1.pcv │ │ │ ├── base0_kf12.pcv │ │ │ ├── base0_kf12o.pcv │ │ │ ├── base0_p.pcv │ │ │ ├── base0_p_r_d_kf12o.pcv │ │ │ ├── base0_r.pcv │ │ │ ├── base1000.pcv │ │ │ ├── base1000_c.pcv │ │ │ ├── base1000_d.pcv │ │ │ ├── base1000_kf1.pcv │ │ │ ├── base1000_kf12.pcv │ │ │ ├── base1000_kf12o.pcv │ │ │ ├── base1000_p.pcv │ │ │ ├── base1000_p_r_d_kf12o.pcv │ │ │ ├── base1000_r.pcv │ │ │ ├── base1048570.pcv │ │ │ ├── base1048570_c.pcv │ │ │ ├── base1048570_d.pcv │ │ │ ├── base1048570_kf1.pcv │ │ │ ├── base1048570_kf12.pcv │ │ │ ├── base1048570_kf12o.pcv │ │ │ ├── base1048570_p.pcv │ │ │ ├── base1048570_p_r_d_kf12o.pcv │ │ │ └── base1048570_r.pcv │ ├── reed_solomon.go │ └── stream.go └── ui │ ├── elements.go │ ├── elements_test.go │ ├── logger.go │ ├── state.go │ ├── test.pcv │ └── theme.go ├── picogo.go └── picogo_test.go /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | .github/* @HACKERALERT 2 | .github/workflows/* @HACKERALERT 3 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "gomod" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | -------------------------------------------------------------------------------- /.github/workflows/release-build.yml: -------------------------------------------------------------------------------- 1 | name: release-build 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | tags: 9 | - 'v[0-9].[0-9]+.[0-9]+' 10 | 11 | 12 | jobs: 13 | release-build: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | 18 | - name: Setup Go 19 | uses: actions/setup-go@v5 20 | with: 21 | go-version: '>=1.24' 22 | check-latest: true 23 | cache: false 24 | 25 | - name: Install packages 26 | run: | 27 | sudo apt update 28 | sudo apt upgrade -y 29 | sudo apt autoremove -y 30 | sudo apt install -y gcc libgl1-mesa-dev libglu1-mesa xorg-dev libgtk-3-dev libxkbcommon-dev 31 | 32 | - name: Install dependencies 33 | run: | 34 | go mod download 35 | go install -v github.com/fyne-io/fyne-cross@latest 36 | 37 | - name: Build Android 38 | run: | 39 | fyne-cross android -arch=arm64 40 | env: 41 | CGO_ENABLED: 1 42 | 43 | - name: Upload artifacts 44 | uses: actions/upload-artifact@v4 45 | with: 46 | name: PicoGo.apk 47 | path: | 48 | fyne-cross/dist/android-arm64/PicoGo.apk 49 | if-no-files-found: error 50 | compression-level: 9 51 | 52 | - name: Generate checksums 53 | run: | 54 | echo "CHECKSUM_PICOGO_APK=$(sha256sum fyne-cross/dist-android-arm64/PicoGo.apk | cut -d ' ' -f1)" >> $GITHUB_ENV 55 | 56 | - name: Release 57 | uses: softprops/action-gh-release@v2 58 | with: 59 | files: | 60 | fyne-cross/dist/android-arm64/PicoGo.apk 61 | tag_name: ${{ env.VERSION }} 62 | make_latest: true 63 | append_body: true 64 | body: | 65 | **PicoGo:** 66 | `sha256(PicoGo.apk): ${{ env.CHECKSUM_PICOGO_APK }}` -------------------------------------------------------------------------------- /.github/workflows/test-build-android.yml: -------------------------------------------------------------------------------- 1 | name: test-build-android 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | test-build-android: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | 18 | - name: Setup Go 19 | uses: actions/setup-go@v5 20 | with: 21 | go-version: '>=1.24' 22 | check-latest: true 23 | cache: false 24 | 25 | - name: Install packages 26 | run: | 27 | sudo apt update 28 | sudo apt upgrade -y 29 | sudo apt autoremove -y 30 | sudo apt install -y gcc libgl1-mesa-dev libglu1-mesa xorg-dev libgtk-3-dev libxkbcommon-dev 31 | 32 | - name: Install dependencies 33 | run: | 34 | go mod download 35 | go install -v github.com/fyne-io/fyne-cross@latest 36 | 37 | - name: Build Android 38 | run: | 39 | fyne-cross android -arch=arm64 40 | env: 41 | CGO_ENABLED: 1 42 | 43 | - name: Upload artifacts 44 | uses: actions/upload-artifact@v4 45 | with: 46 | name: TEST-BUILD-DO-NOT-USE-THIS 47 | path: | 48 | fyne-cross/dist/android-arm64/* 49 | if-no-files-found: error 50 | compression-level: 9 51 | -------------------------------------------------------------------------------- /.github/workflows/test-build-linux.yml: -------------------------------------------------------------------------------- 1 | name: test-build-linux 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | test-build-linux: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | 18 | - name: Setup Go 19 | uses: actions/setup-go@v5 20 | with: 21 | go-version: '>=1.24' 22 | check-latest: true 23 | cache: false 24 | 25 | - name: Install packages 26 | run: | 27 | sudo apt update 28 | sudo apt upgrade -y 29 | sudo apt autoremove -y 30 | sudo apt install -y gcc libgl1-mesa-dev libglu1-mesa xorg-dev libgtk-3-dev libxkbcommon-dev 31 | 32 | - name: Install dependencies 33 | run: | 34 | go mod download 35 | go install -v github.com/fyne-io/fyne-cross@latest 36 | 37 | - name: Build Linux 38 | run: | 39 | fyne-cross linux -arch=amd64 40 | env: 41 | CGO_ENABLED: 1 42 | 43 | - name: Upload artifacts 44 | uses: actions/upload-artifact@v4 45 | with: 46 | name: TEST-BUILD-DO-NOT-USE-THIS 47 | path: | 48 | fyne-cross/dist/linux-amd64/* 49 | if-no-files-found: error 50 | compression-level: 9 51 | -------------------------------------------------------------------------------- /.github/workflows/test-build-windows.yml: -------------------------------------------------------------------------------- 1 | name: test-build-windows 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | test-build-windows: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v4 17 | 18 | - name: Setup Go 19 | uses: actions/setup-go@v5 20 | with: 21 | go-version: '>=1.24' 22 | check-latest: true 23 | cache: false 24 | 25 | - name: Install packages 26 | run: | 27 | sudo apt update 28 | sudo apt upgrade -y 29 | sudo apt autoremove -y 30 | sudo apt install -y gcc libgl1-mesa-dev libglu1-mesa xorg-dev libgtk-3-dev libxkbcommon-dev 31 | 32 | - name: Install dependencies 33 | run: | 34 | go mod download 35 | go install -v github.com/fyne-io/fyne-cross@latest 36 | 37 | - name: Build Windows 38 | run: | 39 | fyne-cross windows -arch=amd64 40 | env: 41 | CGO_ENABLED: 1 42 | 43 | - name: Upload artifacts 44 | uses: actions/upload-artifact@v4 45 | with: 46 | name: TEST-BUILD-DO-NOT-USE-THIS 47 | path: | 48 | fyne-cross/dist/windows-amd64/* 49 | if-no-files-found: error 50 | compression-level: 9 51 | -------------------------------------------------------------------------------- /.github/workflows/test-coverage.yml: -------------------------------------------------------------------------------- 1 | name: test-coverage 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | push: 8 | branches: [ main ] 9 | pull_request: 10 | branches: [ main ] 11 | 12 | jobs: 13 | test-coverage: 14 | name: Go test coverage check 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | 19 | - name: Setup Go 20 | uses: actions/setup-go@v5 21 | with: 22 | go-version: '>=1.24' 23 | check-latest: true 24 | cache: false 25 | 26 | - name: Install packages 27 | run: | 28 | sudo apt update 29 | sudo apt upgrade -y 30 | sudo apt autoremove -y 31 | sudo apt install -y gcc libgl1-mesa-dev libglu1-mesa xorg-dev libgtk-3-dev libxkbcommon-dev 32 | 33 | - name: Install dependencies 34 | run: | 35 | go mod download 36 | go install -v github.com/fyne-io/fyne-cross@latest 37 | 38 | - name: generate test coverage 39 | run: go test ./... -coverprofile=./cover.out -covermode=atomic -coverpkg=./... -timeout 20m 40 | 41 | - name: check test coverage 42 | uses: vladopajic/go-test-coverage@f080863892c102695c8066abc08aae12e3e94e1b # v2.13.1 43 | with: 44 | config: ./.testcoverage.yml 45 | git-token: ${{ github.ref_name == 'main' && secrets.GITHUB_TOKEN || '' }} 46 | git-branch: badges 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | cover.out 2 | -------------------------------------------------------------------------------- /.testcoverage.yml: -------------------------------------------------------------------------------- 1 | profile: cover.out 2 | threshold: 3 | # Minimum coverage percentage required for individual files. 4 | file: 0 5 | # Minimum coverage percentage required for each package. 6 | package: 0 7 | # Minimum overall project coverage percentage required. 8 | total: 60 9 | -------------------------------------------------------------------------------- /FyneApp.toml: -------------------------------------------------------------------------------- 1 | Website = "https://github.com/Picocrypt/PicoGo" 2 | 3 | [Details] 4 | Icon = "icon.png" 5 | Name = "PicoGo" 6 | ID = "io.github.picocrypt.PicoGo" 7 | Version = "0.1.0" 8 | Build = 1 9 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PicoGo 2 | 3 | 4 | ![coverage](https://raw.githubusercontent.com/Picocrypt/PicoGo/badges/.badges/main/coverage.svg) 5 | 6 | A experimental mobile app (Android only for now) for file encryption compatible with [Picocrypt](https://www.github.com/Picocrypt/Picocrypt). 7 | 8 | This app is based on Picocrypt's encryption scheme but is not developed or endorsed by Picocrypt's author/maintainer. It is a standalone work intended to make Picocrypt files easier to access on Android devices. All credit for the original encryption scheme and corresponding code belongs to [Picocrypt](https://www.github.com/Picocrypt/Picocrypt) and its author [HACKERALERT](https://github.com/HACKERALERT). 9 | 10 | > [!CAUTION] 11 | > PicoGo is still in an experimental phase. It has not been extensively tested yet and so is not recommended for securing important files. If you do so, test the result compared to official desktop Picocrypt to be sure. If you run into any errors, please open an issue. 12 | 13 | > [!IMPORTANT] 14 | > Feedback needed! If you are willing, I am looking for early testers for the UI and starting feature set. If you could take a few minutes to try the app out and leave any comments or suggestions it would go a long way in helping PicoGo a usable app for everyone. 15 | 16 | # Features 17 | 18 | Most Picocrypt features are supported 19 | - [x] Standard encryption 20 | - [x] Comments 21 | - [x] Paranoid mode 22 | - [x] Deniability mode 23 | - [x] Keyfiles (with and without ordering) 24 | - [x] Reed Solomon redundancy 25 | - [x] Recovery mode 26 | 27 | # Installation 28 | 29 | ## Google Play 30 | 31 | Coming soon! Once I smooth out some rough edges and complete sufficient testing, I intend to make PicoGo available on the Google Play store. 32 | 33 | ## Manual Installation 34 | 35 | Download the latest [release](https://github.com/Picocrypt/PicoGo/releases) into your Android device. When the download is finished, the device should offer to automatically install the app for you. 36 | 37 | You may receive a warning message with wording like `Unsafe app blocked. This app was built for an older version of Android and doesn't include the latest privacy protections.` This warning happens because I build the app with Fyne which maintains backwards compatibility with older devices. Tap on `More details` and `Install anyway`. 38 | 39 | ## Build from source 40 | 41 | To build PicoGo from source I recommend using [fyne-cross](https://docs.fyne.io/started/cross-compiling.html). Once set up, just clone this repo and run `fyne-cross android -arch=arm64` to build the app. This should create a `PicoGo.apk` file you can install directly to an Android device. 42 | 43 | # Missing Features 44 | 45 | Unsupported features are listed below. If you would like to see any of them implemented, feel free to open a issue and we can see what features would be useful and implementable on mobile. 46 | 47 | ## What about file chunks? 48 | 49 | There are no plans to support file chunking. PicoGo is built using [Fyne.io](https://fyne.io/) which does not offer an easy way to look up files on Android by name. This would require the user to manually select each of the chunked files, which seems clumsy and unnecessarily complex. 50 | 51 | ## What about multiple files / zip / compression? 52 | 53 | Similar problem as file chunks. Fyne exposes files as content URIs, so there is no easy way to map input filenames to output filenames the way that Picocrypt does. I don't want to make the user manually select the save file for each input file, so right now I am only accepting one input file at a time. For zipping and compression, I recommend using other apps to prepare the zip file and then selecting that directly within PicoGo. 54 | 55 | ## What about iOS devices? 56 | 57 | In theory, the app is fully ready to be built for iOS. Unfortunately I do not have easy access to an apple silicon device (required to run the build process) or any iOS devices to test with. Even if both of those are solved, distributing apps for iOS devices costs about $100 per year for a developer license, which is higher than I'm willing to commit right now. Fyne doesn't even build an iOS app unless you have a developer certificate. 58 | 59 | # Credits 60 |
    61 |
  • @njhuffman: initial and primary developer of PicoGo
  • 62 |
  • @HACKERALERT: original Picocrypt developer, PicoGo CI/CD maintainer
  • 63 |
64 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | v0.1.5 -------------------------------------------------------------------------------- /cmd/picogo/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "flag" 6 | "fmt" 7 | "io" 8 | "os" 9 | "strings" 10 | 11 | "github.com/jschauma/getpass" 12 | "github.com/picocrypt/picogo/internal/encryption" 13 | "github.com/schollz/progressbar/v3" 14 | ) 15 | 16 | type args struct { 17 | reedSolomon bool 18 | paranoid bool 19 | deniability bool 20 | inFiles []string 21 | keyfiles []string 22 | keep bool 23 | ordered bool 24 | password string 25 | comments string 26 | overwrite bool 27 | encryptOnly bool 28 | decryptOnly bool 29 | } 30 | 31 | var ( 32 | reedSolomonFlag *bool 33 | paranoidFlag *bool 34 | deniabilityFlag *bool 35 | keyfilesStrFlag *string 36 | keepFlag *bool 37 | orderedFlag *bool 38 | passfromFlag *string 39 | commentsFlag *string 40 | overwriteFlag *bool 41 | encryptOnlyFlag *bool 42 | decryptOnlyFlag *bool 43 | ) 44 | 45 | func init() { 46 | flag.Usage = func() { 47 | fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [options] file1 [file2 ...]\n", os.Args[0]) 48 | fmt.Fprintf(flag.CommandLine.Output(), "\nOptions:\n") 49 | flag.PrintDefaults() 50 | } 51 | reedSolomonFlag = flag.Bool("rs", false, "(encryption) encode with Reed-Solomon bytes") 52 | paranoidFlag = flag.Bool("paranoid", false, "(encryption) use paranoid mode") 53 | deniabilityFlag = flag.Bool("deniability", false, "(encryption) use deniability mode") 54 | keyfilesStrFlag = flag.String("keyfiles", "", "list of keyfiles to use. Separate list with commas (ex: keyfile1,keyfile2,keyfile3)") 55 | keepFlag = flag.Bool("keep", false, "(decryption) keep output even if corrupted. If not set, the output file will be deleted.") 56 | orderedFlag = flag.Bool("ordered", false, "(encryption) require keyfiles in given order") 57 | passfromFlag = flag.String("passfrom", "tty", "password source. Options can be found in getpass documentation (github.com/jschauma/getpass)") 58 | commentsFlag = flag.String("comments", "", "(encryption) comments to save with the file. THESE ARE NOT ENCRYPTED. Wrap in quotes.") 59 | overwriteFlag = flag.Bool("overwrite", false, "overwrite existing files") 60 | encryptOnlyFlag = flag.Bool("encrypt-only", false, "only handle files that require encryption (only processes non-.pcv files)") 61 | decryptOnlyFlag = flag.Bool("decrypt-only", false, "only handle files that require decryption (only processes .pcv files)") 62 | 63 | } 64 | 65 | func parseArgs() (args, error) { 66 | flag.Parse() 67 | if flag.NArg() == 0 { 68 | return args{}, errors.New("no file specified") 69 | } 70 | 71 | password, err := getpass.Getpass(*passfromFlag) 72 | if err != nil { 73 | return args{}, fmt.Errorf("reading password from %s: %w", *passfromFlag, err) 74 | } 75 | keyfiles := []string{} 76 | if len(*keyfilesStrFlag) > 0 { 77 | keyfiles = strings.Split(*keyfilesStrFlag, ",") 78 | } 79 | 80 | return args{ 81 | reedSolomon: *reedSolomonFlag, 82 | paranoid: *paranoidFlag, 83 | deniability: *deniabilityFlag, 84 | inFiles: flag.Args(), 85 | keyfiles: keyfiles, 86 | keep: *keepFlag, 87 | ordered: *orderedFlag, 88 | password: password, 89 | comments: *commentsFlag, 90 | overwrite: *overwriteFlag, 91 | encryptOnly: *encryptOnlyFlag, 92 | decryptOnly: *decryptOnlyFlag, 93 | }, nil 94 | } 95 | 96 | func openFiles(inFile string, keyfiles []string, outFile string, overwrite bool) (*os.File, []*os.File, *os.File, error) { 97 | inReader, err := os.Open(inFile) 98 | if err != nil { 99 | return nil, nil, nil, fmt.Errorf("opening %s: %w", inFile, err) 100 | } 101 | keyfileReaders := []*os.File{} 102 | for _, keyfile := range keyfiles { 103 | reader, err := os.Open(keyfile) 104 | if err != nil { 105 | return nil, nil, nil, fmt.Errorf("opening %s: %w", keyfile, err) 106 | } 107 | keyfileReaders = append(keyfileReaders, reader) 108 | } 109 | _, err = os.Stat(outFile) 110 | if err == nil && !overwrite { 111 | return nil, nil, nil, fmt.Errorf("%s already exists", outFile) 112 | } 113 | outWriter, err := os.Create(outFile) 114 | if err != nil { 115 | return nil, nil, nil, fmt.Errorf("creating %s: %w", outFile, err) 116 | } 117 | return inReader, keyfileReaders, outWriter, nil 118 | } 119 | 120 | func asReaders(files []*os.File) []io.Reader { 121 | readers := make([]io.Reader, len(files)) 122 | for i, file := range files { 123 | readers[i] = file 124 | } 125 | return readers 126 | } 127 | 128 | func encrypt( 129 | inFile string, 130 | keyfiles []string, 131 | settings encryption.Settings, 132 | password string, 133 | outOf [2]int, 134 | overwrite bool, 135 | ) error { 136 | outFile := inFile + ".pcv" 137 | inReader, keyfileReaders, outWriter, err := openFiles(inFile, keyfiles, outFile, overwrite) 138 | if err != nil { 139 | return fmt.Errorf("opening files: %w", err) 140 | } 141 | defer func() { 142 | for _, reader := range append(keyfileReaders, inReader, outWriter) { 143 | reader.Close() 144 | } 145 | }() 146 | 147 | tmp := make([]byte, encryption.HeaderSize(settings)) 148 | _, err = outWriter.Write(tmp) 149 | if err != nil { 150 | return fmt.Errorf("writing blank header: %w", err) 151 | } 152 | 153 | bar := progressbar.NewOptions( 154 | -1, 155 | progressbar.OptionShowBytes(true), 156 | progressbar.OptionClearOnFinish(), 157 | progressbar.OptionUseIECUnits(true), 158 | progressbar.OptionSetDescription( 159 | fmt.Sprintf("[%d/%d] Encrypting: %s", outOf[0]+1, outOf[1], inFile), 160 | ), 161 | ) 162 | header, err := encryption.EncryptHeadless(inReader, password, asReaders(keyfileReaders), settings, io.MultiWriter(outWriter, bar)) 163 | bar.Finish() // don't catch the error, fine to ignore 164 | if err != nil { 165 | return fmt.Errorf("encrypting %s: %w", inFile, err) 166 | } 167 | 168 | _, err = outWriter.Seek(0, 0) 169 | if err != nil { 170 | return fmt.Errorf("seeking to start of %s: %w", outFile, err) 171 | } 172 | _, err = outWriter.Write(header) 173 | if err != nil { 174 | return fmt.Errorf("writing header to %s: %w", outFile, err) 175 | } 176 | fmt.Printf("[%d/%d] Encrypted %s to %s\n", outOf[0]+1, outOf[1], inFile, outFile) 177 | return nil 178 | } 179 | 180 | func decrypt( 181 | inFile string, 182 | keyfiles []string, 183 | password string, 184 | outOf [2]int, 185 | keep bool, 186 | overwrite bool, 187 | ) error { 188 | outFile := strings.TrimSuffix(inFile, ".pcv") 189 | inReader, keyfileReaders, outWriter, err := openFiles(inFile, keyfiles, outFile, overwrite) 190 | if err != nil { 191 | return fmt.Errorf("opening files: %w", err) 192 | } 193 | defer func() { 194 | for _, reader := range append(keyfileReaders, inReader, outWriter) { 195 | reader.Close() 196 | } 197 | }() 198 | 199 | bar := progressbar.NewOptions( 200 | -1, 201 | progressbar.OptionShowBytes(true), 202 | progressbar.OptionClearOnFinish(), 203 | progressbar.OptionUseIECUnits(true), 204 | progressbar.OptionSetDescription( 205 | fmt.Sprintf("[%d/%d] Decrypting: %s", outOf[0]+1, outOf[1], inFile), 206 | ), 207 | ) 208 | damaged, err := encryption.Decrypt( 209 | password, 210 | asReaders(keyfileReaders), 211 | inReader, 212 | io.MultiWriter(outWriter, bar), 213 | false, 214 | ) 215 | bar.Finish() // don't catch the error, fine to ignore 216 | if err != nil { 217 | if !keep { 218 | removeErr := os.Remove(outFile) 219 | if removeErr != nil { 220 | fmt.Printf("error removing %s: %s\n", outFile, removeErr) 221 | } 222 | } 223 | return err 224 | } 225 | if damaged { 226 | fmt.Printf("Warning: %s is damaged but recovered with reed-solomon bytes. Consider re-encrypting the file.\n", inFile) 227 | } 228 | fmt.Printf("[%d/%d] Decrypted %s to %s\n", outOf[0]+1, outOf[1], inFile, outFile) 229 | return nil 230 | } 231 | 232 | func main() { 233 | a, err := parseArgs() 234 | if err != nil { 235 | fmt.Printf("error reading args: %s\n", err) 236 | os.Exit(1) 237 | } 238 | 239 | for i, inFile := range a.inFiles { 240 | if strings.HasSuffix(inFile, ".pcv") { 241 | if a.encryptOnly { 242 | fmt.Printf("[%d/%d] Skipping %s (encrypt-only is set)\n", i+1, len(a.inFiles), inFile) 243 | continue 244 | } 245 | err := decrypt(inFile, a.keyfiles, a.password, [2]int{i, len(a.inFiles)}, a.keep, a.overwrite) 246 | if err != nil { 247 | fmt.Printf("error while decrypting %s: %s\n", inFile, err) 248 | os.Exit(1) 249 | } 250 | } else { 251 | if a.decryptOnly { 252 | fmt.Printf("[%d/%d] Skipping %s (decrypt-only is set)\n", i+1, len(a.inFiles), inFile) 253 | continue 254 | } 255 | settings := encryption.Settings{ 256 | Comments: a.comments, 257 | ReedSolomon: a.reedSolomon, 258 | Paranoid: a.paranoid, 259 | Deniability: a.deniability, 260 | } 261 | err := encrypt(inFile, a.keyfiles, settings, a.password, [2]int{i, len(a.inFiles)}, a.overwrite) 262 | if err != nil { 263 | fmt.Printf("error while encrypting %s: %s\n", inFile, err) 264 | os.Exit(1) 265 | } 266 | } 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /cmd/picogo/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "os" 5 | "testing" 6 | 7 | "github.com/picocrypt/picogo/internal/encryption" 8 | ) 9 | 10 | func argsMatch(a, b args) bool { 11 | if a.reedSolomon != b.reedSolomon { 12 | return false 13 | } 14 | if a.paranoid != b.paranoid { 15 | return false 16 | } 17 | if a.deniability != b.deniability { 18 | return false 19 | } 20 | if len(a.keyfiles) != len(b.keyfiles) { 21 | return false 22 | } 23 | for i := range a.keyfiles { 24 | if a.keyfiles[i] != b.keyfiles[i] { 25 | return false 26 | } 27 | } 28 | if a.keep != b.keep { 29 | return false 30 | } 31 | if a.ordered != b.ordered { 32 | return false 33 | } 34 | if a.password != b.password { 35 | return false 36 | } 37 | if a.comments != b.comments { 38 | return false 39 | } 40 | if a.overwrite != b.overwrite { 41 | return false 42 | } 43 | if a.encryptOnly != b.encryptOnly { 44 | return false 45 | } 46 | if a.decryptOnly != b.decryptOnly { 47 | return false 48 | } 49 | if len(a.inFiles) != len(b.inFiles) { 50 | return false 51 | } 52 | for i := range a.inFiles { 53 | if a.inFiles[i] != b.inFiles[i] { 54 | return false 55 | } 56 | } 57 | return true 58 | } 59 | 60 | func TestParseArgs(t *testing.T) { 61 | tests := []struct { 62 | name string 63 | args []string 64 | want args 65 | }{ 66 | { 67 | name: "basic case", 68 | args: []string{"-passfrom", "pass:password", "file1.txt"}, 69 | want: args{inFiles: []string{"file1.txt"}, password: "password"}, 70 | }, 71 | { 72 | name: "all args", 73 | args: []string{"-rs", "-paranoid", "-deniability", "-keyfiles", "keyfile1,keyfile2", "-keep", "-ordered", "-passfrom", "pass:password", "-comments", "test comments", "-overwrite", "-encrypt-only", "-decrypt-only", "file1.txt"}, 74 | want: args{ 75 | reedSolomon: true, 76 | paranoid: true, 77 | deniability: true, 78 | keyfiles: []string{"keyfile1", "keyfile2"}, 79 | keep: true, 80 | ordered: true, 81 | password: "password", 82 | comments: "test comments", 83 | overwrite: true, 84 | encryptOnly: true, 85 | decryptOnly: true, 86 | inFiles: []string{"file1.txt"}, 87 | }, 88 | }, 89 | } 90 | 91 | for _, tt := range tests { 92 | t.Run(tt.name, func(t *testing.T) { 93 | os.Args = append([]string{"picogo"}, tt.args...) 94 | got, err := parseArgs() 95 | if err != nil { 96 | t.Errorf("parseArgs() error = %v", err) 97 | return 98 | } 99 | if !argsMatch(got, tt.want) { 100 | t.Errorf("parseArgs() = %v, want %v", got, tt.want) 101 | } 102 | }) 103 | } 104 | } 105 | 106 | func fileExists(filename string) bool { 107 | _, err := os.Stat(filename) 108 | return !os.IsNotExist(err) 109 | } 110 | 111 | func deleteFile(filename string) { 112 | err := os.Remove(filename) 113 | if err != nil { 114 | panic(err) 115 | } 116 | } 117 | 118 | func TestDecrypt(t *testing.T) { 119 | encryptedFilename := "../../internal/encryption/picocrypt_samples/v1.48/base1000.pcv" 120 | decryptedFilename := "../../internal/encryption/picocrypt_samples/v1.48/base1000" 121 | err := decrypt( 122 | encryptedFilename, 123 | []string{}, 124 | "password", 125 | [2]int{0, 2}, 126 | false, 127 | false, 128 | ) 129 | if err != nil { 130 | t.Errorf("decrypt() error = %v", err) 131 | } 132 | if !fileExists(decryptedFilename) { 133 | t.Errorf("decrypt() did not create file %s", decryptedFilename) 134 | } 135 | deleteFile(decryptedFilename) 136 | 137 | encryptedFilename = "../../internal/encryption/picocrypt_samples/v1.48/base1000_kf12.pcv" 138 | decryptedFilename = "../../internal/encryption/picocrypt_samples/v1.48/base1000_kf12" 139 | err = decrypt( 140 | encryptedFilename, 141 | []string{ 142 | "../../internal/encryption/picocrypt_samples/keyfiles/keyfile1", 143 | "../../internal/encryption/picocrypt_samples/keyfiles/keyfile2", 144 | }, 145 | "password", 146 | [2]int{1, 2}, 147 | false, 148 | true, 149 | ) 150 | if err != nil { 151 | t.Errorf("decrypt() error = %v", err) 152 | } 153 | if !fileExists(decryptedFilename) { 154 | t.Errorf("decrypt() did not create file %s", decryptedFilename) 155 | } 156 | deleteFile(decryptedFilename) 157 | } 158 | 159 | func TestEncrypt(t *testing.T) { 160 | encryptedFilename := "../../internal/encryption/picocrypt_samples/basefiles/base1000.pcv" 161 | decryptedFilename := "../../internal/encryption/picocrypt_samples/basefiles/base1000" 162 | err := encrypt( 163 | decryptedFilename, 164 | []string{}, 165 | encryption.Settings{}, 166 | "password", 167 | [2]int{0, 2}, 168 | false, 169 | ) 170 | if err != nil { 171 | t.Errorf("encrypt() error = %v", err) 172 | } 173 | if !fileExists(encryptedFilename) { 174 | t.Errorf("encrypt() did not create file %s", encryptedFilename) 175 | } 176 | deleteFile(encryptedFilename) 177 | 178 | encryptedFilename = "../../internal/encryption/picocrypt_samples/basefiles/base1000.pcv" 179 | decryptedFilename = "../../internal/encryption/picocrypt_samples/basefiles/base1000" 180 | err = encrypt( 181 | decryptedFilename, 182 | []string{ 183 | "../../internal/encryption/picocrypt_samples/keyfiles/keyfile1", 184 | "../../internal/encryption/picocrypt_samples/keyfiles/keyfile2", 185 | }, 186 | encryption.Settings{}, 187 | "password", 188 | [2]int{1, 2}, 189 | false, 190 | ) 191 | if err != nil { 192 | t.Errorf("encrypt() error = %v", err) 193 | } 194 | if !fileExists(encryptedFilename) { 195 | t.Errorf("encrypt() did not create file %s", encryptedFilename) 196 | } 197 | deleteFile(encryptedFilename) 198 | } 199 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/picocrypt/picogo 2 | 3 | go 1.23.0 4 | 5 | toolchain go1.24.1 6 | 7 | require ( 8 | fyne.io/fyne/v2 v2.6.1 9 | github.com/Picocrypt/infectious v0.0.0-20240830233326-3a050f65f9ec 10 | github.com/Picocrypt/serpent v0.0.0-20240830233833-9ad6ab254fd7 11 | github.com/jschauma/getpass v0.2.3 12 | github.com/schollz/progressbar/v3 v3.18.0 13 | golang.org/x/crypto v0.38.0 14 | ) 15 | 16 | require ( 17 | fyne.io/systray v1.11.0 // indirect 18 | github.com/BurntSushi/toml v1.4.0 // indirect 19 | github.com/davecgh/go-spew v1.1.1 // indirect 20 | github.com/fredbi/uri v1.1.0 // indirect 21 | github.com/fsnotify/fsnotify v1.8.0 // indirect 22 | github.com/fyne-io/gl-js v0.1.0 // indirect 23 | github.com/fyne-io/glfw-js v0.2.0 // indirect 24 | github.com/fyne-io/image v0.1.1 // indirect 25 | github.com/fyne-io/oksvg v0.1.0 // indirect 26 | github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71 // indirect 27 | github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a // indirect 28 | github.com/go-text/render v0.2.0 // indirect 29 | github.com/go-text/typesetting v0.3.0 // indirect 30 | github.com/godbus/dbus/v5 v5.1.0 // indirect 31 | github.com/hack-pad/go-indexeddb v0.3.2 // indirect 32 | github.com/hack-pad/safejs v0.1.0 // indirect 33 | github.com/jeandeaual/go-locale v0.0.0-20241217141322-fcc2cadd6f08 // indirect 34 | github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25 // indirect 35 | github.com/kr/text v0.2.0 // indirect 36 | github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db // indirect 37 | github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect 38 | github.com/nicksnyder/go-i18n/v2 v2.5.1 // indirect 39 | github.com/pmezard/go-difflib v1.0.0 // indirect 40 | github.com/rivo/uniseg v0.4.7 // indirect 41 | github.com/rymdport/portal v0.4.1 // indirect 42 | github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c // indirect 43 | github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef // indirect 44 | github.com/stretchr/testify v1.10.0 // indirect 45 | github.com/yuin/goldmark v1.7.8 // indirect 46 | golang.org/x/image v0.24.0 // indirect 47 | golang.org/x/net v0.36.0 // indirect 48 | golang.org/x/sys v0.33.0 // indirect 49 | golang.org/x/term v0.32.0 // indirect 50 | golang.org/x/text v0.25.0 // indirect 51 | gopkg.in/yaml.v3 v3.0.1 // indirect 52 | ) 53 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | fyne.io/fyne/v2 v2.6.1 h1:kjPJD4/rBS9m2nHJp+npPSuaK79yj6ObMTuzR6VQ1Is= 2 | fyne.io/fyne/v2 v2.6.1/go.mod h1:YZt7SksjvrSNJCwbWFV32WON3mE1Sr7L41D29qMZ/lU= 3 | fyne.io/systray v1.11.0 h1:D9HISlxSkx+jHSniMBR6fCFOUjk1x/OOOJLa9lJYAKg= 4 | fyne.io/systray v1.11.0/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs= 5 | github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0= 6 | github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= 7 | github.com/Picocrypt/infectious v0.0.0-20240830233326-3a050f65f9ec h1:/cop0/v0HxIJm1XGDgIlzNJ3e4HhM8nIUPZi5RZ/n1w= 8 | github.com/Picocrypt/infectious v0.0.0-20240830233326-3a050f65f9ec/go.mod h1:aaFq/WMVxrU2Exl/tXbTFSXajZrqw0mgn/wi42n0fK4= 9 | github.com/Picocrypt/serpent v0.0.0-20240830233833-9ad6ab254fd7 h1:G36G2vmQAS7CVoHQrHDGAoCWll/0kPCI8Dk7mgwcJFE= 10 | github.com/Picocrypt/serpent v0.0.0-20240830233833-9ad6ab254fd7/go.mod h1:BxsgRYwUVd92aEwXnXsfXfHw8aHlD/PUyExC/wwk9oI= 11 | github.com/chengxilo/virtualterm v1.0.4 h1:Z6IpERbRVlfB8WkOmtbHiDbBANU7cimRIof7mk9/PwM= 12 | github.com/chengxilo/virtualterm v1.0.4/go.mod h1:DyxxBZz/x1iqJjFxTFcr6/x+jSpqN0iwWCOK1q10rlY= 13 | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= 14 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 15 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 16 | github.com/felixge/fgprof v0.9.3 h1:VvyZxILNuCiUCSXtPtYmmtGvb65nqXh2QFWc0Wpf2/g= 17 | github.com/felixge/fgprof v0.9.3/go.mod h1:RdbpDgzqYVh/T9fPELJyV7EYJuHB55UTEULNun8eiPw= 18 | github.com/fredbi/uri v1.1.0 h1:OqLpTXtyRg9ABReqvDGdJPqZUxs8cyBDOMXBbskCaB8= 19 | github.com/fredbi/uri v1.1.0/go.mod h1:aYTUoAXBOq7BLfVJ8GnKmfcuURosB1xyHDIfWeC/iW4= 20 | github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M= 21 | github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= 22 | github.com/fyne-io/gl-js v0.1.0 h1:8luJzNs0ntEAJo+8x8kfUOXujUlP8gB3QMOxO2mUdpM= 23 | github.com/fyne-io/gl-js v0.1.0/go.mod h1:ZcepK8vmOYLu96JoxbCKJy2ybr+g1pTnaBDdl7c3ajI= 24 | github.com/fyne-io/glfw-js v0.2.0 h1:8GUZtN2aCoTPNqgRDxK5+kn9OURINhBEBc7M4O1KrmM= 25 | github.com/fyne-io/glfw-js v0.2.0/go.mod h1:Ri6te7rdZtBgBpxLW19uBpp3Dl6K9K/bRaYdJ22G8Jk= 26 | github.com/fyne-io/image v0.1.1 h1:WH0z4H7qfvNUw5l4p3bC1q70sa5+YWVt6HCj7y4VNyA= 27 | github.com/fyne-io/image v0.1.1/go.mod h1:xrfYBh6yspc+KjkgdZU/ifUC9sPA5Iv7WYUBzQKK7JM= 28 | github.com/fyne-io/oksvg v0.1.0 h1:7EUKk3HV3Y2E+qypp3nWqMXD7mum0hCw2KEGhI1fnBw= 29 | github.com/fyne-io/oksvg v0.1.0/go.mod h1:dJ9oEkPiWhnTFNCmRgEze+YNprJF7YRbpjgpWS4kzoI= 30 | github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71 h1:5BVwOaUSBTlVZowGO6VZGw2H/zl9nrd3eCZfYV+NfQA= 31 | github.com/go-gl/gl v0.0.0-20231021071112-07e5d0ea2e71/go.mod h1:9YTyiznxEY1fVinfM7RvRcjRHbw2xLBJ3AAGIT0I4Nw= 32 | github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a h1:vxnBhFDDT+xzxf1jTJKMKZw3H0swfWk9RpWbBbDK5+0= 33 | github.com/go-gl/glfw/v3.3/glfw v0.0.0-20240506104042-037f3cc74f2a/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= 34 | github.com/go-text/render v0.2.0 h1:LBYoTmp5jYiJ4NPqDc2pz17MLmA3wHw1dZSVGcOdeAc= 35 | github.com/go-text/render v0.2.0/go.mod h1:CkiqfukRGKJA5vZZISkjSYrcdtgKQWRa2HIzvwNN5SU= 36 | github.com/go-text/typesetting v0.3.0 h1:OWCgYpp8njoxSRpwrdd1bQOxdjOXDj9Rqart9ML4iF4= 37 | github.com/go-text/typesetting v0.3.0/go.mod h1:qjZLkhRgOEYMhU9eHBr3AR4sfnGJvOXNLt8yRAySFuY= 38 | github.com/go-text/typesetting-utils v0.0.0-20241103174707-87a29e9e6066 h1:qCuYC+94v2xrb1PoS4NIDe7DGYtLnU2wWiQe9a1B1c0= 39 | github.com/go-text/typesetting-utils v0.0.0-20241103174707-87a29e9e6066/go.mod h1:DDxDdQEnB70R8owOx3LVpEFvpMK9eeH1o2r0yZhFI9o= 40 | github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= 41 | github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= 42 | github.com/google/pprof v0.0.0-20211214055906-6f57359322fd h1:1FjCyPC+syAzJ5/2S8fqdZK1R22vvA0J7JZKcuOIQ7Y= 43 | github.com/google/pprof v0.0.0-20211214055906-6f57359322fd/go.mod h1:KgnwoLYCZ8IQu3XUZ8Nc/bM9CCZFOyjUNOSygVozoDg= 44 | github.com/hack-pad/go-indexeddb v0.3.2 h1:DTqeJJYc1usa45Q5r52t01KhvlSN02+Oq+tQbSBI91A= 45 | github.com/hack-pad/go-indexeddb v0.3.2/go.mod h1:QvfTevpDVlkfomY498LhstjwbPW6QC4VC/lxYb0Kom0= 46 | github.com/hack-pad/safejs v0.1.0 h1:qPS6vjreAqh2amUqj4WNG1zIw7qlRQJ9K10eDKMCnE8= 47 | github.com/hack-pad/safejs v0.1.0/go.mod h1:HdS+bKF1NrE72VoXZeWzxFOVQVUSqZJAG0xNCnb+Tio= 48 | github.com/jeandeaual/go-locale v0.0.0-20241217141322-fcc2cadd6f08 h1:wMeVzrPO3mfHIWLZtDcSaGAe2I4PW9B/P5nMkRSwCAc= 49 | github.com/jeandeaual/go-locale v0.0.0-20241217141322-fcc2cadd6f08/go.mod h1:ZDXo8KHryOWSIqnsb/CiDq7hQUYryCgdVnxbj8tDG7o= 50 | github.com/jschauma/getpass v0.2.3 h1:tJySlkGtHpT3JO1UBjxrLDSp9qvbb0gKRlcNslec10g= 51 | github.com/jschauma/getpass v0.2.3/go.mod h1:mk40NJ7cAbcRkeDKDIajUsfQB/yweyiqjf29kyMnS18= 52 | github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25 h1:YLvr1eE6cdCqjOe972w/cYF+FjW34v27+9Vo5106B4M= 53 | github.com/jsummers/gobmp v0.0.0-20230614200233-a9de23ed2e25/go.mod h1:kLgvv7o6UM+0QSf0QjAse3wReFDsb9qbZJdfexWlrQw= 54 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= 55 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= 56 | github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= 57 | github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 58 | github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db h1:62I3jR2EmQ4l5rM/4FEfDWcRD+abF5XlKShorW5LRoQ= 59 | github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db/go.mod h1:l0dey0ia/Uv7NcFFVbCLtqEBQbrT4OCwCSKTEv6enCw= 60 | github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ= 61 | github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8= 62 | github.com/nicksnyder/go-i18n/v2 v2.5.1 h1:IxtPxYsR9Gp60cGXjfuR/llTqV8aYMsC472zD0D1vHk= 63 | github.com/nicksnyder/go-i18n/v2 v2.5.1/go.mod h1:DrhgsSDZxoAfvVrBVLXoxZn/pN5TXqaDbq7ju94viiQ= 64 | github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= 65 | github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= 66 | github.com/pkg/profile v1.7.0 h1:hnbDkaNWPCLMO9wGLdBFTIZvzDrDfBM2072E1S9gJkA= 67 | github.com/pkg/profile v1.7.0/go.mod h1:8Uer0jas47ZQMJ7VD+OHknK4YDY07LPUC6dEvqDjvNo= 68 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 69 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 70 | github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= 71 | github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= 72 | github.com/rymdport/portal v0.4.1 h1:2dnZhjf5uEaeDjeF/yBIeeRo6pNI2QAKm7kq1w/kbnA= 73 | github.com/rymdport/portal v0.4.1/go.mod h1:kFF4jslnJ8pD5uCi17brj/ODlfIidOxlgUDTO5ncnC4= 74 | github.com/schollz/progressbar/v3 v3.18.0 h1:uXdoHABRFmNIjUfte/Ex7WtuyVslrw2wVPQmCN62HpA= 75 | github.com/schollz/progressbar/v3 v3.18.0/go.mod h1:IsO3lpbaGuzh8zIMzgY3+J8l4C8GjO0Y9S69eFvNsec= 76 | github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c h1:km8GpoQut05eY3GiYWEedbTT0qnSxrCjsVbb7yKY1KE= 77 | github.com/srwiley/oksvg v0.0.0-20221011165216-be6e8873101c/go.mod h1:cNQ3dwVJtS5Hmnjxy6AgTPd0Inb3pW05ftPSX7NZO7Q= 78 | github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef h1:Ch6Q+AZUxDBCVqdkI8FSpFyZDtCVBc2VmejdNrm5rRQ= 79 | github.com/srwiley/rasterx v0.0.0-20220730225603-2ab79fcdd4ef/go.mod h1:nXTWP6+gD5+LUJ8krVhhoeHjvHTutPxMYl5SvkcnJNE= 80 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= 81 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 82 | github.com/yuin/goldmark v1.7.8 h1:iERMLn0/QJeHFhxSt3p6PeN9mGnvIKSpG9YYorDMnic= 83 | github.com/yuin/goldmark v1.7.8/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E= 84 | golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= 85 | golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= 86 | golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ= 87 | golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8= 88 | golang.org/x/net v0.36.0 h1:vWF2fRbw4qslQsQzgFqZff+BItCvGFQqKzKIzx1rmoA= 89 | golang.org/x/net v0.36.0/go.mod h1:bFmbeoIPfrw4sMHNhb4J9f6+tPziuGjq7Jk/38fxi1I= 90 | golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= 91 | golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= 92 | golang.org/x/term v0.32.0 h1:DR4lr0TjUs3epypdhTOkMmuF5CDFJ/8pOnbzMZPQ7bg= 93 | golang.org/x/term v0.32.0/go.mod h1:uZG1FhGx848Sqfsq4/DlJr3xGGsYMu/L5GW4abiaEPQ= 94 | golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4= 95 | golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA= 96 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 97 | gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= 98 | gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 99 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 100 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 101 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/icon.png -------------------------------------------------------------------------------- /internal/encryption/ciphers.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "crypto/cipher" 5 | "fmt" 6 | "io" 7 | 8 | "github.com/Picocrypt/serpent" 9 | "golang.org/x/crypto/chacha20" 10 | "golang.org/x/crypto/sha3" 11 | ) 12 | 13 | const resetNonceAt = int64(60 * (1 << 30)) 14 | 15 | type nonceManager interface { 16 | nonce(i int) ([24]byte, error) 17 | } 18 | 19 | type ivManager interface { 20 | iv(i int) ([16]byte, error) 21 | } 22 | 23 | type nonceIvManager struct { 24 | chachaNonces [][24]byte 25 | serpentIVs [][16]byte 26 | seeds *seeds 27 | hkdf io.Reader 28 | } 29 | 30 | func (nm *nonceIvManager) extendTo(i int) error { 31 | if len(nm.chachaNonces) == 0 { 32 | nm.chachaNonces = [][24]byte{nm.seeds.Nonce} 33 | nm.serpentIVs = [][16]byte{nm.seeds.SerpentIV} 34 | } 35 | for i >= len(nm.chachaNonces) { 36 | chachaNonce := [24]byte{} 37 | serpentIV := [16]byte{} 38 | _, err := io.ReadFull(nm.hkdf, chachaNonce[:]) 39 | if err != nil { 40 | return err 41 | } 42 | _, err = io.ReadFull(nm.hkdf, serpentIV[:]) 43 | if err != nil { 44 | return err 45 | } 46 | nm.chachaNonces = append(nm.chachaNonces, chachaNonce) 47 | nm.serpentIVs = append(nm.serpentIVs, serpentIV) 48 | } 49 | return nil 50 | } 51 | 52 | func (nm *nonceIvManager) nonce(i int) ([24]byte, error) { 53 | err := nm.extendTo(i) 54 | if err != nil { 55 | return [24]byte{}, err 56 | } 57 | return nm.chachaNonces[i], nil 58 | } 59 | 60 | func (nm *nonceIvManager) iv(i int) ([16]byte, error) { 61 | err := nm.extendTo(i) 62 | if err != nil { 63 | return [16]byte{}, err 64 | } 65 | return nm.serpentIVs[i], nil 66 | } 67 | 68 | func newNonceManager(hkdf io.Reader, seeds *seeds) *nonceIvManager { 69 | nm := &nonceIvManager{ 70 | seeds: seeds, 71 | hkdf: hkdf, 72 | } 73 | return nm 74 | } 75 | 76 | type denyNonceManager struct { 77 | nonces [][24]byte 78 | header *header 79 | } 80 | 81 | func (dnm *denyNonceManager) extendTo(i int) error { 82 | if len(dnm.nonces) == 0 { 83 | dnm.nonces = append(dnm.nonces, dnm.header.seeds.DenyNonce) 84 | } 85 | for i >= len(dnm.nonces) { 86 | previous := dnm.nonces[len(dnm.nonces)-1] 87 | tmp := sha3.New256() 88 | _, err := tmp.Write(previous[:]) 89 | if err != nil { 90 | return err 91 | } 92 | nonce := [24]byte{} 93 | copy(nonce[:], tmp.Sum(nil)) 94 | dnm.nonces = append(dnm.nonces, nonce) 95 | } 96 | return nil 97 | } 98 | 99 | func (dnm *denyNonceManager) nonce(i int) ([24]byte, error) { 100 | err := dnm.extendTo(i) 101 | if err != nil { 102 | return [24]byte{}, err 103 | } 104 | return dnm.nonces[i], nil 105 | } 106 | 107 | type serpentCipher struct { 108 | serpentBlock cipher.Block 109 | cipher cipher.Stream 110 | ivManager ivManager 111 | header *header 112 | } 113 | 114 | func (sc *serpentCipher) reset(i int) error { 115 | serpentIV, err := sc.ivManager.iv(i) 116 | if err != nil { 117 | return err 118 | } 119 | sc.cipher = cipher.NewCTR(sc.serpentBlock, serpentIV[:]) 120 | return nil 121 | } 122 | 123 | func (sc *serpentCipher) xor(p []byte) { 124 | sc.cipher.XORKeyStream(p, p) 125 | } 126 | 127 | type chachaCipher struct { 128 | cipher *chacha20.Cipher 129 | nonceManager nonceManager 130 | key []byte 131 | } 132 | 133 | func (cc *chachaCipher) reset(i int) error { 134 | nonce, err := cc.nonceManager.nonce(i) 135 | if err != nil { 136 | return err 137 | } 138 | cc.cipher, err = chacha20.NewUnauthenticatedCipher(cc.key[:], nonce[:]) 139 | return err 140 | } 141 | 142 | func (cc *chachaCipher) xor(p []byte) { 143 | cc.cipher.XORKeyStream(p, p) 144 | } 145 | 146 | type xorCipher interface { 147 | xor(p []byte) 148 | reset(i int) error 149 | } 150 | 151 | type rotatingCipher struct { 152 | xorCipher 153 | writtenCounter int64 154 | resetCounter int 155 | initialised bool 156 | } 157 | 158 | func (rc *rotatingCipher) stream(p []byte) ([]byte, error) { 159 | if !rc.initialised { 160 | err := rc.xorCipher.reset(0) 161 | if err != nil { 162 | return nil, err 163 | } 164 | rc.initialised = true 165 | } 166 | i := int64(0) 167 | for i < int64(len(p)) { 168 | j := int64(len(p)) - i 169 | if j > (resetNonceAt - rc.writtenCounter) { 170 | j = resetNonceAt - rc.writtenCounter 171 | } 172 | rc.xor(p[i : i+j]) 173 | rc.writtenCounter += j 174 | if rc.writtenCounter == resetNonceAt { 175 | rc.writtenCounter = 0 176 | rc.resetCounter++ 177 | err := rc.reset(rc.resetCounter) 178 | if err != nil { 179 | return nil, err 180 | } 181 | } 182 | i += j 183 | } 184 | return p, nil 185 | } 186 | 187 | func (rc *rotatingCipher) flush() ([]byte, error) { 188 | return nil, nil 189 | } 190 | 191 | func newDeniabilityStream(password string, header *header) streamerFlusher { 192 | nonceManager := denyNonceManager{header: header} 193 | denyKey := generateDenyKey(password, header.seeds.DenySalt) 194 | return &rotatingCipher{ 195 | xorCipher: &chachaCipher{ 196 | nonceManager: &nonceManager, 197 | key: denyKey[:], 198 | }, 199 | } 200 | } 201 | 202 | func newEncryptionStreams(keys keys, header *header) ([]streamerFlusher, error) { 203 | nonceIvManager := newNonceManager(keys.hkdf, &(header.seeds)) 204 | chachaStream := &rotatingCipher{ 205 | xorCipher: &chachaCipher{ 206 | nonceManager: nonceIvManager, 207 | key: keys.key[:], 208 | }, 209 | } 210 | if !header.settings.Paranoid { 211 | return []streamerFlusher{chachaStream}, nil 212 | } 213 | sb, err := serpent.NewCipher(keys.serpentKey[:]) 214 | if err != nil { 215 | return nil, fmt.Errorf("creating serpent cipher: %w", err) 216 | } 217 | serpentStream := &rotatingCipher{ 218 | xorCipher: &serpentCipher{ 219 | serpentBlock: sb, 220 | ivManager: nonceIvManager, 221 | header: header, 222 | cipher: nil, // will be set during streaming 223 | }, 224 | } 225 | return []streamerFlusher{chachaStream, serpentStream}, nil 226 | } 227 | -------------------------------------------------------------------------------- /internal/encryption/consistency_test.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "io" 7 | "log" 8 | mrand "math/rand/v2" 9 | "testing" 10 | 11 | "golang.org/x/crypto/sha3" 12 | ) 13 | 14 | func shaArgonKey(password string, salt [16]byte, iterations uint32, parallelism uint8) [32]byte { 15 | // faster stand-in for testing 16 | data := append(append(append([]byte(password), salt[:]...), byte(iterations)), byte(parallelism)) 17 | hasher := sha3.New256() 18 | _, err := hasher.Write(data) 19 | if err != nil { 20 | panic(err) 21 | } 22 | key := [32]byte{} 23 | copy(key[:], hasher.Sum(nil)) 24 | return key 25 | } 26 | 27 | func allSettings() []Settings { 28 | settings := []Settings{} 29 | for _, comments := range []string{"", "test"} { 30 | for _, reedSolomon := range []bool{true, false} { 31 | for _, paranoid := range []bool{true, false} { 32 | for _, orderedKf := range []bool{true, false} { 33 | for _, deniability := range []bool{true, false} { 34 | s := Settings{comments, reedSolomon, paranoid, orderedKf, deniability} 35 | settings = append(settings, s) 36 | } 37 | } 38 | } 39 | } 40 | } 41 | return settings 42 | } 43 | 44 | func getKeyfiles(settings Settings, numKeyfiles int, t *testing.T) ([]io.Reader, []io.Reader) { 45 | kf1, kf2 := []io.Reader{}, []io.Reader{} 46 | for i := 0; i < numKeyfiles; i++ { 47 | key1 := make([]byte, 100) 48 | _, err := rand.Read(key1) 49 | if err != nil { 50 | t.Fatal(err) 51 | } 52 | key2 := make([]byte, len(key1)) 53 | copy(key2, key1) 54 | kf1 = append(kf1, bytes.NewBuffer(key1)) 55 | kf2 = append(kf2, bytes.NewBuffer(key2)) 56 | } 57 | if !settings.OrderedKf { 58 | for i := len(kf2) - 1; i > 0; i-- { 59 | j := mrand.IntN(i + 1) 60 | kf2[i], kf2[int(j)] = kf2[int(j)], kf2[i] 61 | } 62 | } 63 | return kf1, kf2 64 | } 65 | 66 | func randomPassword() string { 67 | password := "" 68 | n := mrand.IntN(100) + 1 69 | for i := 0; i < n; i++ { 70 | char := mrand.IntN(128) 71 | password += string(byte(char)) 72 | } 73 | return password 74 | } 75 | 76 | func randomData(size int) ([]byte, error) { 77 | data := make([]byte, size) 78 | _, err := rand.Read(data) 79 | if err != nil { 80 | return nil, err 81 | } 82 | return data, nil 83 | } 84 | 85 | func buff(data []byte) *bytes.Buffer { 86 | d := make([]byte, len(data)) 87 | copy(d, data) 88 | return bytes.NewBuffer(d) 89 | } 90 | 91 | func testConsistency(settings Settings, size int, numKeyfiles int, t *testing.T) { 92 | original, err := randomData(size) 93 | if err != nil { 94 | t.Fatal("opening file:", err) 95 | } 96 | 97 | password := randomPassword() 98 | kf1, kf2 := getKeyfiles(settings, numKeyfiles, t) 99 | 100 | headless := bytes.NewBuffer([]byte{}) 101 | header, err := EncryptHeadless(buff(original), password, kf1, settings, headless) 102 | if err != nil { 103 | t.Fatal(err) 104 | } 105 | headlessLen := headless.Len() 106 | headed := bytes.NewBuffer([]byte{}) 107 | err = PrependHeader(headless, headed, header) 108 | if err != nil { 109 | t.Fatal(err) 110 | } 111 | encryptedLen := headed.Len() 112 | encrypted, err := io.ReadAll(headed) 113 | if err != nil { 114 | t.Fatal(err) 115 | } 116 | decrypted := bytes.NewBuffer([]byte{}) 117 | Decrypt(password, kf2, buff(encrypted), decrypted, false) 118 | 119 | result, err := io.ReadAll(decrypted) 120 | if err != nil { 121 | t.Fatal(err) 122 | } 123 | if !bytes.Equal(result, original) { 124 | log.Println("original length:", len(original)) 125 | log.Println("headless length:", headlessLen) 126 | log.Println("headed length:", encryptedLen) 127 | log.Println("decrypted length:", len(result)) 128 | log.Println("missing bytes:", len(original)-len(result)) 129 | t.Fatal("decryption does not match") 130 | } 131 | 132 | } 133 | 134 | func TestConsistencyEmptyFile(t *testing.T) { 135 | // test for an empty file 136 | argonKey = shaArgonKey 137 | for _, settings := range allSettings() { 138 | for numKeyfiles := range 3 { 139 | testConsistency(settings, 0, numKeyfiles, t) 140 | } 141 | } 142 | } 143 | 144 | func TestConsistencySmallFile(t *testing.T) { 145 | // test for a file size less than readSize 146 | argonKey = shaArgonKey 147 | for _, settings := range allSettings() { 148 | for numKeyfiles := range 3 { 149 | testConsistency(settings, readSize/2, numKeyfiles, t) 150 | } 151 | } 152 | } 153 | 154 | func TestConsistencyLargeFile(t *testing.T) { 155 | // test for a file size greater than readSize 156 | argonKey = shaArgonKey 157 | for _, settings := range allSettings() { 158 | for numKeyfiles := range 3 { 159 | testConsistency(settings, readSize*2+500, numKeyfiles, t) 160 | } 161 | } 162 | } 163 | 164 | func TestConsistencyReadSize(t *testing.T) { 165 | // test for a file exactly at readSize 166 | argonKey = shaArgonKey 167 | for _, settings := range allSettings() { 168 | for numKeyfiles := range 3 { 169 | testConsistency(settings, readSize, numKeyfiles, t) 170 | } 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /internal/encryption/decrypt.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "bytes" 5 | "crypto/hmac" 6 | "errors" 7 | "fmt" 8 | "hash" 9 | "io" 10 | "regexp" 11 | "strconv" 12 | "strings" 13 | 14 | "golang.org/x/crypto/blake2b" 15 | "golang.org/x/crypto/sha3" 16 | ) 17 | 18 | type damageTracker struct { 19 | damage bool 20 | } 21 | 22 | type buffer struct { 23 | size int 24 | data []byte 25 | } 26 | 27 | func (b *buffer) isFull() bool { 28 | return len(b.data) == b.size 29 | } 30 | 31 | func (b *buffer) add(p []byte) []byte { 32 | idx := len(p) 33 | if len(p) > b.size-len(b.data) { 34 | idx = b.size - len(b.data) 35 | } 36 | if idx > 0 { 37 | b.data = append(b.data, p[:idx]...) 38 | return p[idx:] 39 | } 40 | return p 41 | } 42 | 43 | func parseVersion(versionBytes []byte) (bool, string, error) { 44 | if len(versionBytes) != (versionSize * 3) { 45 | return false, "", fmt.Errorf("invalid version length: %d", len(versionBytes)) 46 | } 47 | v := make([]byte, versionSize) 48 | damaged, _, err := rsDecode(v, versionBytes[:], false) 49 | if err != nil { 50 | return damaged, "", fmt.Errorf("decoding version: %w", err) 51 | } 52 | valid, err := regexp.Match(`^v1\.\d{2}`, v) 53 | if err != nil { 54 | return damaged, "", fmt.Errorf("parsing version format: %w", err) 55 | } 56 | if !valid { 57 | return damaged, "", nil 58 | } 59 | return damaged, string(v), nil 60 | } 61 | 62 | type versionStream struct { 63 | buff buffer 64 | damageTracker *damageTracker 65 | } 66 | 67 | func (v *versionStream) stream(p []byte) ([]byte, error) { 68 | if !v.buff.isFull() { 69 | p = v.buff.add(p) 70 | if v.buff.isFull() { 71 | // check that the version is actually good 72 | damaged, version, err := parseVersion(v.buff.data) 73 | v.damageTracker.damage = v.damageTracker.damage || damaged 74 | if err != nil { 75 | return nil, fmt.Errorf("parsing version: %w", err) 76 | } 77 | if version == "" { 78 | return nil, ErrHeaderCorrupted 79 | } 80 | } 81 | } 82 | return p, nil 83 | } 84 | 85 | func makeVersionStream(damageTracker *damageTracker) *versionStream { 86 | return &versionStream{ 87 | buff: buffer{size: versionSize * 3}, 88 | damageTracker: damageTracker, 89 | } 90 | } 91 | 92 | type deniabilityStream struct { 93 | password string 94 | buff buffer 95 | deny streamer 96 | header *header 97 | } 98 | 99 | func (d *deniabilityStream) stream(p []byte) ([]byte, error) { 100 | if !d.buff.isFull() { 101 | p = d.buff.add(p) 102 | if d.buff.isFull() { 103 | // Don't catch damaged flag, it is handled by the version stream 104 | _, version, err := parseVersion(d.buff.data[:versionSize*3]) 105 | if err != nil { 106 | return nil, fmt.Errorf("parsing version: %w", err) 107 | } 108 | if version != "" { 109 | d.header.settings.Deniability = false 110 | p = append(d.buff.data, p...) 111 | } else { 112 | d.header.settings.Deniability = true 113 | salt := [16]byte{} 114 | nonce := [24]byte{} 115 | copy(salt[:], d.buff.data[:len(salt)]) 116 | copy(nonce[:], d.buff.data[len(salt):]) 117 | d.header.seeds.DenyNonce = nonce 118 | d.header.seeds.DenySalt = salt 119 | d.deny = newDeniabilityStream(d.password, d.header) 120 | } 121 | } 122 | } 123 | if d.deny != nil { 124 | var err error 125 | p, err = d.deny.stream(p) 126 | if err != nil { 127 | return nil, fmt.Errorf("denying data: %w", err) 128 | } 129 | } 130 | return p, nil 131 | } 132 | 133 | func makeHeaderDeniabilityStream(password string, header *header) *deniabilityStream { 134 | return &deniabilityStream{ 135 | password: password, 136 | buff: buffer{size: 16 + 24}, // 16 bytes for salt, 24 bytes for nonce 137 | header: header, 138 | deny: nil, // will be set during streaming 139 | } 140 | } 141 | 142 | type flagStream struct { 143 | buff buffer 144 | header *header 145 | damageTracker *damageTracker 146 | } 147 | 148 | func (f *flagStream) stream(p []byte) ([]byte, error) { 149 | if !f.buff.isFull() { 150 | p = f.buff.add(p) 151 | if f.buff.isFull() { 152 | data := make([]byte, flagsSize) 153 | damaged, corrupted, err := rsDecode(data, f.buff.data, false) 154 | f.damageTracker.damage = f.damageTracker.damage || damaged 155 | if corrupted { 156 | return nil, ErrHeaderCorrupted 157 | } 158 | if err != nil { 159 | return nil, fmt.Errorf("decoding flags: %w", err) 160 | } 161 | f.header.settings.Paranoid = data[0] == 1 162 | f.header.usesKf = data[1] == 1 163 | f.header.settings.OrderedKf = data[2] == 1 164 | f.header.settings.ReedSolomon = data[3] == 1 165 | f.header.nearMiBFlag = data[4] == 1 166 | } 167 | } 168 | return p, nil 169 | } 170 | 171 | func makeFlagStream(header *header, damageTracker *damageTracker) *flagStream { 172 | return &flagStream{buffer{size: flagsSize * 3}, header, damageTracker} 173 | } 174 | 175 | type commentStream struct { 176 | lenBuff buffer 177 | commentBuff buffer 178 | header *header 179 | damageTracker *damageTracker 180 | } 181 | 182 | func (c *commentStream) stream(p []byte) ([]byte, error) { 183 | if !c.lenBuff.isFull() { 184 | p = c.lenBuff.add(p) 185 | if c.lenBuff.isFull() { 186 | cLenRune := make([]byte, commentSize) 187 | damaged, corrupted, err := rsDecode(cLenRune, c.lenBuff.data, false) 188 | c.damageTracker.damage = c.damageTracker.damage || damaged 189 | if corrupted { 190 | return nil, ErrHeaderCorrupted 191 | } 192 | if err != nil { 193 | return nil, fmt.Errorf("decoding comment length: %w", err) 194 | } 195 | cLen, err := strconv.Atoi(string(cLenRune)) 196 | if err != nil { 197 | return nil, fmt.Errorf("parsing comment length: %w", ErrHeaderCorrupted) 198 | } 199 | if (cLen < 0) || (cLen > maxCommentsLength) { 200 | return nil, ErrHeaderCorrupted 201 | } 202 | c.commentBuff = buffer{size: cLen * 3} 203 | } 204 | } 205 | if c.lenBuff.isFull() && !c.commentBuff.isFull() { 206 | p = c.commentBuff.add(p) 207 | if c.commentBuff.isFull() { 208 | var builder strings.Builder 209 | for i := 0; i < len(c.commentBuff.data); i += 3 { 210 | value := [1]byte{} 211 | // Ignore corruption on comments, they are not critical 212 | damaged, _, err := rsDecode(value[:], c.commentBuff.data[i:i+3], false) 213 | c.damageTracker.damage = c.damageTracker.damage || damaged 214 | if err != nil { 215 | return nil, fmt.Errorf("decoding comment length: %w", err) 216 | } 217 | builder.WriteByte(value[0]) 218 | } 219 | c.header.settings.Comments = builder.String() 220 | } 221 | } 222 | return p, nil 223 | } 224 | 225 | func makeCommentStream(header *header, damageTracker *damageTracker) *commentStream { 226 | return &commentStream{ 227 | lenBuff: buffer{size: commentSize * 3}, 228 | header: header, 229 | damageTracker: damageTracker, 230 | } 231 | } 232 | 233 | type sliceStream struct { 234 | buff buffer 235 | slice []byte 236 | damageTracker *damageTracker 237 | } 238 | 239 | func (s *sliceStream) stream(p []byte) ([]byte, error) { 240 | if !s.buff.isFull() { 241 | p = s.buff.add(p) 242 | if s.buff.isFull() { 243 | data := make([]byte, len(s.slice)) 244 | damaged, corrupted, err := rsDecode(data, s.buff.data, false) 245 | s.damageTracker.damage = s.damageTracker.damage || damaged 246 | if corrupted { 247 | return nil, ErrHeaderCorrupted 248 | } 249 | if err != nil { 250 | return nil, fmt.Errorf("decoding slice: %w", err) 251 | } 252 | copy(s.slice, data) 253 | } 254 | } 255 | return p, nil 256 | } 257 | 258 | func makeSliceStream(slice []byte, damagedTracker *damageTracker) *sliceStream { 259 | return &sliceStream{buffer{size: len(slice) * 3}, slice, damagedTracker} 260 | } 261 | 262 | type headerStream struct { 263 | header *header 264 | streams []streamer 265 | isDone func() bool 266 | } 267 | 268 | func (h *headerStream) stream(p []byte) ([]byte, error) { 269 | return streamStack(h.streams, p) 270 | } 271 | 272 | func makeHeaderStream(password string, header *header, damageTracker *damageTracker) *headerStream { 273 | macTagStream := makeSliceStream(header.refs.macTag[:], damageTracker) 274 | isDone := func() bool { 275 | return macTagStream.buff.isFull() 276 | } 277 | streams := []streamer{ 278 | makeHeaderDeniabilityStream(password, header), 279 | makeVersionStream(damageTracker), 280 | makeCommentStream(header, damageTracker), 281 | makeFlagStream(header, damageTracker), 282 | makeSliceStream(header.seeds.Salt[:], damageTracker), 283 | makeSliceStream(header.seeds.HkdfSalt[:], damageTracker), 284 | makeSliceStream(header.seeds.SerpentIV[:], damageTracker), 285 | makeSliceStream(header.seeds.Nonce[:], damageTracker), 286 | makeSliceStream(header.refs.keyRef[:], damageTracker), 287 | makeSliceStream(header.refs.keyfileRef[:], damageTracker), 288 | macTagStream, 289 | } 290 | return &headerStream{header, streams, isDone} 291 | } 292 | 293 | func getHeader(r io.Reader, password string) (header, error) { 294 | h := header{} 295 | stream := makeHeaderStream(password, &h, &damageTracker{}) 296 | for { 297 | p := make([]byte, 1000) // big enough to get most headers in one read 298 | n, err := r.Read(p) 299 | eof := errors.Is(err, io.EOF) 300 | if err != nil && !eof { 301 | return header{}, fmt.Errorf("reading file: %w", err) 302 | } 303 | _, err = stream.stream(p[:n]) 304 | if err != nil { 305 | return header{}, fmt.Errorf("reading header: %w", err) 306 | } 307 | if stream.isDone() { 308 | return h, nil 309 | } 310 | if eof { 311 | return header{}, ErrFileTooShort 312 | } 313 | } 314 | } 315 | 316 | type macStream struct { 317 | mac hash.Hash 318 | encrypting bool 319 | header *header 320 | } 321 | 322 | func (ms *macStream) stream(p []byte) ([]byte, error) { 323 | _, err := ms.mac.Write(p) 324 | if err != nil { 325 | return nil, err 326 | } 327 | return p, nil 328 | } 329 | 330 | func (ms *macStream) flush() ([]byte, error) { 331 | m := ms.mac.Sum(nil) 332 | if ms.encrypting { 333 | copy(ms.header.refs.macTag[:], m) 334 | return nil, nil 335 | } 336 | if !hmac.Equal(m, ms.header.refs.macTag[:]) { 337 | return nil, ErrBodyCorrupted 338 | } 339 | return nil, nil 340 | } 341 | 342 | func newMacStream(keys keys, header *header, encrypting bool) (*macStream, error) { 343 | var mac hash.Hash 344 | if header.settings.Paranoid { 345 | mac = hmac.New(sha3.New512, keys.macKey[:]) 346 | } else { 347 | var err error 348 | mac, err = blake2b.New512(keys.macKey[:]) 349 | if err != nil { 350 | return nil, err 351 | } 352 | } 353 | return &macStream{mac: mac, header: header, encrypting: encrypting}, nil 354 | } 355 | 356 | type decryptStream struct { 357 | password string 358 | keyfiles []io.Reader 359 | headerStream *headerStream 360 | bodyStreams []streamerFlusher 361 | damageTracker *damageTracker 362 | } 363 | 364 | func (ds *decryptStream) stream(p []byte) ([]byte, error) { 365 | p, err := ds.headerStream.stream(p) 366 | if err != nil { 367 | return nil, err 368 | } 369 | if ds.headerStream.isDone() { 370 | if ds.bodyStreams == nil { 371 | ds.bodyStreams, err = ds.makeBodyStreams() 372 | if err != nil { 373 | return nil, err 374 | } 375 | } 376 | return streamStack(ds.bodyStreams, p) 377 | } 378 | return p, nil 379 | } 380 | 381 | func (ds *decryptStream) flush() ([]byte, error) { 382 | if !ds.headerStream.isDone() { 383 | return nil, ErrFileTooShort 384 | } 385 | if ds.bodyStreams == nil { 386 | return nil, nil 387 | } 388 | return flushStack(ds.bodyStreams) 389 | } 390 | 391 | func (ds *decryptStream) makeBodyStreams() ([]streamerFlusher, error) { 392 | // TODO implement keyfiles 393 | keys, err := validateKeys(ds.headerStream.header, ds.password, ds.keyfiles) 394 | if err != nil { 395 | // TODO should I include duplicate keyfiles error here? 396 | return nil, err 397 | } 398 | // TODO verify that the keyRef matches the header 399 | streams := []streamerFlusher{} 400 | // TODO: add reed solomon if configured 401 | if ds.headerStream.header.settings.ReedSolomon { 402 | streams = append(streams, makeRSDecodeStream(false, ds.headerStream.header, ds.damageTracker)) 403 | } 404 | macStream, err := newMacStream(keys, ds.headerStream.header, false) 405 | if err != nil { 406 | return nil, err 407 | } 408 | streams = append(streams, macStream) 409 | encryptionStreams, err := newEncryptionStreams(keys, ds.headerStream.header) 410 | if err != nil { 411 | return nil, err 412 | } 413 | streams = append(streams, encryptionStreams...) 414 | return streams, nil 415 | } 416 | 417 | func makeDecryptStream(password string, keyfiles []io.Reader, damageTracker *damageTracker) *decryptStream { 418 | header := header{} 419 | return &decryptStream{ 420 | password: password, 421 | keyfiles: keyfiles, 422 | headerStream: makeHeaderStream(password, &header, damageTracker), 423 | damageTracker: damageTracker, 424 | } 425 | } 426 | 427 | func validateKeys(header *header, password string, keyfiles []io.Reader) (keys, error) { 428 | if header.usesKf && len(keyfiles) == 0 { 429 | return keys{}, ErrKeyfilesRequired 430 | } 431 | if !header.usesKf && len(keyfiles) > 0 { 432 | return keys{}, ErrKeyfilesNotRequired 433 | } 434 | keys, err := newKeys(header.settings, header.seeds, password, keyfiles) 435 | if err != nil && !errors.Is(err, ErrDuplicateKeyfiles) { 436 | return keys, err 437 | } 438 | if !bytes.Equal(keys.keyRef[:], header.refs.keyRef[:]) { 439 | return keys, ErrIncorrectPassword 440 | } 441 | if header.usesKf && !bytes.Equal(keys.keyfileRef[:], header.refs.keyfileRef[:]) { 442 | if header.settings.OrderedKf { 443 | return keys, ErrIncorrectOrMisorderedKeyfiles 444 | } 445 | return keys, ErrIncorrectKeyfiles 446 | } 447 | return keys, nil 448 | } 449 | -------------------------------------------------------------------------------- /internal/encryption/docs/code_architecture.md: -------------------------------------------------------------------------------- 1 | # Code Architecture 2 | 3 | Here are some block diagrams of how the code is structured. Not all details are shown, but these diagrams give a reasonably cohesive idea of how data is passed through and modified. 4 | 5 | # Decryption 6 | ## Low Detail View 7 | 8 | Data is first passed through `Header Decryption` which is responsible for initializing the shared `Header` state with correct values, consuming all header-related bytes, and undoing any encryption from deniability mode. By the time data is passed out of `Header Decryption`, the `Header` object is fully initialized and ready to be used. Any damaged bytes are reported to the shared `DamageTracker`. 9 | 10 | Data then passes through `Body Decryption` which is responsible for decoding the file data and checking it for correctness. The data output by `Body Decryption` is fully decoded. Any damaged bytes are reported to the shared `DamageTracker`. 11 | 12 | ```mermaid 13 | flowchart TB 14 | 15 | subgraph SH[Header Decryption] 16 | direction LR 17 | 18 | SH_S1[[Deniability Wrapper]] 19 | SH_S2[[Header Fields]] 20 | 21 | SH_A[/Incoming bytes/] --> SH_S1 --> SH_S2 --> SH_B[\Outgoing bytes\] 22 | 23 | end 24 | 25 | subgraph SB[Body Decryption] 26 | direction LR 27 | 28 | SB_A[/Incoming bytes/] 29 | SB_S1[[ReedSolomon]] 30 | SB_S2[[MAC]] 31 | SB_S3[[Encryption]] 32 | SB_SB[\Outgoing bytes\] 33 | 34 | SB_A --> SB_S1 35 | SB_S1 --> SB_S2 36 | SB_S2 --> SB_S3 37 | SB_S3 --> SB_SB 38 | end 39 | 40 | A[/Encrypted data/] --> SH --> SB --> B[/Decrypted data/] 41 | 42 | HEADER[(Header)] 43 | DMG[(DamageTracker)] 44 | ``` 45 | 46 | ## High Detail View 47 | 48 | ```mermaid 49 | flowchart TB 50 | 51 | subgraph SH[Header Decryption] 52 | direction TB 53 | 54 | subgraph SH_S1[Deniability Wrapper] 55 | direction LR 56 | SH_S1_HEADER[(Header)] 57 | SH_S1_A[/Incoming bytes/] --> SH_S1_B{Are the first bytes a valid version?} 58 | SH_S1_B --> |Yes| SH_S1_C[\Outgoing bytes\] 59 | SH_S1_B --> |No| SH_S1_D[Consume the first 40 bytes] 60 | SH_S1_D -.-> |denyMode, denyNonce, denySalt| SH_S1_HEADER 61 | SH_S1_D --> SH_S1_E[ChaCha20 Cipher] 62 | SH_S1_HEADER -.-> |denyNonce, denySalt| SH_S1_E 63 | SH_S1_E --> SH_S1_C 64 | end 65 | 66 | subgraph SH_S2[Header Fields] 67 | direction LR 68 | SH_S2_HEADER[(Header)] 69 | SH_S2_DMG[(DamageTracker)] 70 | SH_S2_A[/Incoming bytes/] --> SH_S2_B{{"Loop over fields in [version, comments, flags, salt, hkdfSalt, serpentIV, nonce, keyRef, keyfileRef, macTag]"}} 71 | SH_S2_B --> |field| SH_S2_C{"Are bytes for field decodable?"} 72 | SH_S2_C --> |No| SH_S2_D(Consume all bytes) 73 | SH_S2_D -.-> |damaged| SH_S2_DMG 74 | SH_S2_C --> |Yes| SH_S2_E{Was error correction required?} 75 | SH_S2_E --> |Yes| SH_S2_F[Record damage] 76 | SH_S2_F -.-> |damaged| SH_S2_DMG 77 | SH_S2_F --> SH_S2_G[Consume field bytes] 78 | SH_S2_E --> |No| SH_S2_G 79 | SH_S2_G --> SH_S2_B 80 | SH_S2_G -.-> |field| SH_S2_HEADER 81 | SH_S2_B --> |done| SH_S2_H[\Outgoing bytes\] 82 | 83 | SH_S5_I>"Note: actual implementation unrolls the loop"] 84 | end 85 | 86 | SH_S1 --> SH_S2 87 | 88 | end 89 | 90 | subgraph SB[Body Decryption] 91 | direction TB 92 | 93 | subgraph SB_S1[ReedSolomon] 94 | SB_S1_HEADER[(Header)] 95 | SB_S1_DMG[(DamageTracker)] 96 | 97 | SB_S1_A[/Incoming bytes/] --> SB_S1_B{Has Reed Solomon encoding?} 98 | SB_S1_B --> |Yes| SB_S1_C[Break into 136 byte chunks] 99 | SB_S1_C --> SB_S1_D[Consume Reed Solomon bytes] 100 | SB_S1_D --> SB_S1_E{Is chunk decodable?} 101 | SB_S1_E --> |Yes| SB_S1_F{Was error correction required?} 102 | SB_S1_F --> |Yes| SB_S1_G[Record damage] 103 | SB_S1_G -.-> |damaged| SB_S1_DMG 104 | SB_S1_I -.-> |damaged| SB_S1_DMG 105 | SB_S1_G --> SB_S1_H[\Outgoing bytes\] 106 | SB_S1_E --> |No| SB_S1_I[Use first bytes as best guess] 107 | SB_S1_I --> SB_S1_H 108 | SB_S1_F --> |No| SB_S1_H 109 | SB_S1_HEADER -.-> |ReedSolomon| SB_S1_B 110 | SB_S1_B --> |No| SB_S1_H 111 | end 112 | 113 | subgraph SB_S2[MAC] 114 | direction LR 115 | SB_S2_HEADER[(Header)] 116 | SB_S2_DMG[(DamageTracker)] 117 | SB_S2_A[/Incoming bytes/] --> SB_S2_B{Encrypted with Paranoid mode?} 118 | SB_S2_B --> |Yes| SB_S2_C["Record to SHA3.512 (does not modify bytes)"] 119 | SB_S2_B --> |No| SB_S2_D["Record to Blake2 (does not modify bytes)"] 120 | SB_S2_E[\Outgoing bytes\] 121 | SB_S2_C --> SB_S2_E 122 | SB_S2_D --> SB_S2_E 123 | 124 | SB_S2_F{Does final sum match macTag?} 125 | SB_S2_G(Do nothing) 126 | SB_S2_H(Report error) 127 | SB_S2_C -.-> |On flush| SB_S2_F 128 | SB_S2_D -.-> |On flush| SB_S2_F 129 | SB_S2_F -.-> |Yes| SB_S2_G 130 | SB_S2_F -.-> |No| SB_S2_H 131 | SB_S2_H -.-> |damaged| SB_S2_DMG 132 | 133 | SB_S2_HEADER -.-> |paranoid| SB_S2_B 134 | SB_S2_HEADER -.-> |macTag| SB_S2_F 135 | end 136 | 137 | subgraph SB_S3[Encryption] 138 | direction LR 139 | SB_S3_HEADER[(Header)] 140 | SB_S3_A[/Incoming bytes/] 141 | SB_S3_B[ChaCha20 cipher] 142 | SB_S3_C{Is paranoid?} 143 | SB_S3_D[Serpent] 144 | SB_S3_E[\Outgoing bytes\] 145 | SB_S3_A --> SB_S3_B --> SB_S3_C 146 | SB_S3_C --> |Yes| SB_S3_D --> SB_S3_E 147 | SB_S3_C --> |No| SB_S3_E 148 | SB_S3_HEADER -.-> |nonce, salt| SB_S3_B 149 | SB_S3_HEADER -.-> |paranoid| SB_S3_C 150 | SB_S3_HEADER -.-> |iv| SB_S3_D 151 | end 152 | 153 | SB_S1 --> SB_S2 --> SB_S3 154 | 155 | end 156 | 157 | A[/Data to decrypt/] --> SH --> SB --> B[/Decrypted data/] 158 | ``` 159 | 160 | # Encryption 161 | 162 | Encryption is broken into 2 steps: encode the file itself through `Encryption Stream`, then combine the `Header` bytes with the encoded body data. These steps are separated because some header data such as the `macTag` cannot be known until the file data has been fully encrypted. The header fields required for `Encryption Stream` are initialized from the passed `Settings` and randomly generated seeds. 163 | 164 | 165 | ```mermaid 166 | flowchart LR 167 | 168 | A[Settings] 169 | B[Random Seeds] 170 | C[Header] 171 | D[[Encryption Stream]] 172 | E[/Input File/] 173 | F[header + body] 174 | H[Encrypted body data] 175 | I[\Output File\] 176 | J[Apply deniability if enabled] 177 | 178 | A -.-> C 179 | B -.-> C 180 | C -.-> D 181 | E --> D 182 | D --> H 183 | H --> |body bytes| F 184 | C --> |After body data is encrypted| J --> |header bytes| F 185 | F --> I 186 | ``` 187 | 188 | ## Low Detail View 189 | 190 | Low detail view of the `Encryption Stream`. It is very similar to running the `Decryption Stream` in reverse. Data is first passed through `Primary Encryption` (ChaCha20, plus Serpent if paranoid). Then a mac is computed and saved to the header to check against when decrypting. Then Reed-Solomon bytes are added if requested. Then everything is passed through `Deniability Wrapper` (another ChaCha20) if requested. The output bytes are the full body, ready to be appended to the header bytes, which can now be computed. 191 | 192 | ```mermaid 193 | flowchart TB 194 | 195 | subgraph SB[Body Encryption] 196 | direction LR 197 | SB_S1[[Encryption]] 198 | SB_S2[[MAC]] 199 | SB_S3[[ReedSolomon]] 200 | SB_S4[[Deniability Wrapper]] 201 | SB_S1 --> SB_S2 --> SB_S3 --> SB_S4 202 | end 203 | 204 | A[/Data to encrypt/] --> SB --> B[/Encrypted data/] 205 | ``` 206 | 207 | ## High Detail View 208 | 209 | ```mermaid 210 | flowchart TB 211 | 212 | subgraph SB[Body Encryption] 213 | direction TB 214 | 215 | subgraph SB_S1[Encryption] 216 | direction LR 217 | SB_S1_HEADER[(Header)] 218 | SB_S1_A[/Incoming bytes/] 219 | SB_S1_B[ChaCha20 cipher] 220 | SB_S1_C{Is paranoid?} 221 | SB_S1_D[Serpent] 222 | SB_S1_E[\Outgoing bytes\] 223 | SB_S1_A --> SB_S1_B --> SB_S1_C 224 | SB_S1_C --> |No| SB_S1_E 225 | SB_S1_C --> |Yes| SB_S1_D --> SB_S1_E 226 | SB_S1_HEADER -.-> |nonce, salt| SB_S1_B 227 | SB_S1_HEADER -.-> |paranoid| SB_S1_C 228 | SB_S1_HEADER -.-> |iv| SB_S1_D 229 | end 230 | 231 | subgraph SB_S2[MAC] 232 | direction LR 233 | SB_S2_HEADER[(Header)] 234 | SB_S2_A[/Incoming bytes/] --> SB_S2_B{Paranoid Mode?} 235 | SB_S2_B --> |Yes| SB_S2_C["Record to SHA3.512 (does not modify bytes)"] 236 | SB_S2_B --> |No| SB_S2_D["Record to Blake2 (does not modify bytes)"] 237 | SB_S2_E[\Outgoing bytes\] 238 | SB_S2_C --> SB_S2_E 239 | SB_S2_D --> SB_S2_E 240 | 241 | SB_S2_F(Save sum to header) 242 | SB_S2_C -.-> |On flush| SB_S2_F 243 | SB_S2_D -.-> |On flush| SB_S2_F 244 | SB_S2_F -.-> |macTag| SB_S2_HEADER 245 | 246 | SB_S2_HEADER -.-> |paranoid| SB_S2_B 247 | end 248 | 249 | subgraph SB_S3[ReedSolomon] 250 | SB_S3_HEADER[(Header)] 251 | SB_S3_A[/Incoming bytes/] --> SB_S3_B{Reed Solomon encoding?} 252 | SB_S3_B --> |Yes| SB_S3_C[Break into 128 byte chunks] 253 | SB_S3_C --> SB_S3_D[Add 8 Reed Solomon bytes per chunk] 254 | SB_S3_D --> SB_S3_E[\Outgoing bytes\] 255 | SB_S3_HEADER -.-> |ReedSolomon| SB_S3_B 256 | SB_S3_B --> |No| SB_S3_E 257 | end 258 | 259 | subgraph SB_S4[Deniability Wrapper] 260 | direction LR 261 | SH_S4_HEADER[(Header)] 262 | SH_S4_A[/Incoming bytes/] --> SH_S4_B{Deniability mode?} 263 | SH_S4_B --> |No| SH_S4_C[\Outgoing bytes\] 264 | SH_S4_B --> |Yes| SH_S4_D["ChaCha20 Cipher (seeded with mock header bytes)"] 265 | SH_S4_HEADER -.-> |denyNonce, denySalt| SH_S4_D 266 | SH_S4_D --> SH_S4_C 267 | end 268 | 269 | SB_S1 --> SB_S2 --> SB_S3 --> SB_S4 270 | 271 | end 272 | 273 | A[/Data to encrypt/] --> SB --> B[/Encrypted data/] 274 | ``` -------------------------------------------------------------------------------- /internal/encryption/encrypt.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | ) 7 | 8 | var picocryptVersion = "v1.48" 9 | 10 | type sizeStream struct { 11 | header *header 12 | counter int64 13 | } 14 | 15 | func (s *sizeStream) stream(p []byte) ([]byte, error) { 16 | s.counter += int64(len(p)) 17 | return p, nil 18 | } 19 | 20 | func (s *sizeStream) flush() ([]byte, error) { 21 | s.header.nearMiBFlag = (s.counter % (1 << 20)) > ((1 << 20) - chunkSize) 22 | return nil, nil 23 | } 24 | 25 | type encryptStream struct { 26 | header *header 27 | streams []streamerFlusher 28 | } 29 | 30 | func (es *encryptStream) stream(p []byte) ([]byte, error) { 31 | return streamStack(es.streams, p) 32 | } 33 | 34 | func (es *encryptStream) flush() ([]byte, error) { 35 | return flushStack(es.streams) 36 | } 37 | 38 | func makeEncryptStream(settings Settings, seeds seeds, password string, keyfiles []io.Reader) (*encryptStream, error) { 39 | keys, err := newKeys(settings, seeds, password, keyfiles) 40 | if err != nil { 41 | return nil, fmt.Errorf("generating keys: %w", err) 42 | } 43 | header := header{ 44 | settings: settings, 45 | seeds: seeds, 46 | refs: refs{ 47 | keyRef: keys.keyRef, 48 | keyfileRef: keys.keyfileRef, 49 | macTag: [64]byte{}, // will be filled by mac stream 50 | }, 51 | usesKf: len(keyfiles) > 0, 52 | nearMiBFlag: false, 53 | } 54 | 55 | streams := []streamerFlusher{} 56 | 57 | encryptionStreams, err := newEncryptionStreams(keys, &header) 58 | if err != nil { 59 | return nil, fmt.Errorf("creating encryption stream: %w", err) 60 | } 61 | streams = append(streams, encryptionStreams...) 62 | 63 | macStream, err := newMacStream(keys, &header, true) 64 | if err != nil { 65 | return nil, fmt.Errorf("creating mac stream: %w", err) 66 | } 67 | streams = append(streams, macStream) 68 | 69 | sizeStream := sizeStream{header: &header} 70 | streams = append(streams, &sizeStream) 71 | 72 | if settings.ReedSolomon { 73 | streams = append(streams, makeRSEncodeStream(&header)) 74 | } 75 | 76 | if settings.Deniability { 77 | deniabilityStream := newDeniabilityStream(password, &header) 78 | mockHeaderData := make([]byte, baseHeaderSize+3*len(settings.Comments)) 79 | _, err := deniabilityStream.stream(mockHeaderData) 80 | if err != nil { 81 | return nil, fmt.Errorf("seeding deniability stream: %w", err) 82 | } 83 | streams = append(streams, deniabilityStream) 84 | } 85 | 86 | return &encryptStream{ 87 | header: &header, 88 | streams: streams, 89 | }, nil 90 | } 91 | -------------------------------------------------------------------------------- /internal/encryption/encryption.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "io" 7 | ) 8 | 9 | const readSize = 1 << 20 10 | const maxCommentsLength = 99999 11 | 12 | var ErrFileTooShort = errors.New("file too short") 13 | var ErrIncorrectPassword = errors.New("incorrect password") 14 | var ErrIncorrectKeyfiles = errors.New("incorrect keyfiles") 15 | var ErrIncorrectOrMisorderedKeyfiles = errors.New("incorrect or misordered keyfiles") 16 | var ErrKeyfilesRequired = errors.New("missing required keyfiles") 17 | var ErrDuplicateKeyfiles = errors.New("duplicate keyfiles") 18 | var ErrKeyfilesNotRequired = errors.New("keyfiles not required") 19 | var ErrHeaderCorrupted = errors.New("header corrupted") 20 | var ErrBodyCorrupted = errors.New("body corrupted") 21 | var ErrCommentsTooLong = errors.New("comments exceed maximum length") 22 | 23 | type Settings struct { 24 | Comments string 25 | ReedSolomon bool 26 | Paranoid bool 27 | OrderedKf bool 28 | Deniability bool 29 | } 30 | 31 | func Decrypt( 32 | pw string, 33 | kf []io.Reader, 34 | r io.Reader, 35 | w io.Writer, 36 | skipReedSolomon bool, 37 | ) (bool, error) { 38 | 39 | damageTracker := damageTracker{} 40 | decryptStream := makeDecryptStream(pw, kf, &damageTracker) 41 | 42 | for { 43 | p := make([]byte, readSize) 44 | n, err := r.Read(p) 45 | eof := false 46 | if err != nil { 47 | if errors.Is(err, io.EOF) { 48 | eof = true 49 | } else { 50 | return false, fmt.Errorf("reading input: %w", err) 51 | } 52 | } 53 | p, err = decryptStream.stream(p[:n]) 54 | if err != nil { 55 | return damageTracker.damage, err 56 | } 57 | _, err = w.Write(p) 58 | if err != nil { 59 | return damageTracker.damage, err 60 | } 61 | if eof { 62 | p, err := decryptStream.flush() 63 | if (err == nil) || errors.Is(err, ErrBodyCorrupted) { 64 | _, e := w.Write(p) 65 | return damageTracker.damage, e 66 | } 67 | return damageTracker.damage, err 68 | } 69 | } 70 | } 71 | 72 | func GetEncryptionSettings(r io.Reader) (Settings, error) { 73 | header, err := getHeader(r, "") 74 | if errors.Is(err, ErrFileTooShort) { 75 | return Settings{Deniability: true}, nil 76 | } 77 | if err != nil { 78 | return Settings{}, fmt.Errorf("reading header: %w", err) 79 | } 80 | return header.settings, nil 81 | } 82 | 83 | func EncryptHeadless( 84 | in io.Reader, 85 | password string, 86 | keyfiles []io.Reader, 87 | settings Settings, 88 | out io.Writer, 89 | ) ([]byte, error) { 90 | if len(settings.Comments) > maxCommentsLength { 91 | return nil, ErrCommentsTooLong 92 | } 93 | seeds, err := randomSeeds() 94 | if err != nil { 95 | return nil, fmt.Errorf("generating seeds: %w", err) 96 | } 97 | return encryptWithSeeds(in, password, keyfiles, settings, out, seeds) 98 | } 99 | 100 | func encryptWithSeeds( 101 | in io.Reader, 102 | password string, 103 | keyfiles []io.Reader, 104 | settings Settings, 105 | out io.Writer, 106 | seeds seeds, 107 | ) ([]byte, error) { 108 | encryptionStream, err := makeEncryptStream(settings, seeds, password, keyfiles) 109 | if err != nil { 110 | return nil, fmt.Errorf("making encryption stream: %w", err) 111 | } 112 | 113 | buf := make([]byte, readSize) 114 | for { 115 | eof := false 116 | n, err := in.Read(buf) 117 | if err != nil { 118 | if errors.Is(err, io.EOF) { 119 | eof = true 120 | } else { 121 | return nil, fmt.Errorf("reading input: %w", err) 122 | } 123 | } 124 | p, err := encryptionStream.stream(buf[:n]) 125 | if err != nil { 126 | return nil, fmt.Errorf("encrypting input: %w", err) 127 | } 128 | _, err = out.Write(p) 129 | if err != nil { 130 | return nil, fmt.Errorf("writing output: %w", err) 131 | } 132 | if eof { 133 | break 134 | } 135 | } 136 | 137 | p, err := encryptionStream.flush() 138 | if err != nil { 139 | return nil, fmt.Errorf("closing encryptor: %w", err) 140 | } 141 | _, err = out.Write(p) 142 | if err != nil { 143 | return nil, fmt.Errorf("writing output: %w", err) 144 | } 145 | 146 | headerBytes, err := encryptionStream.header.bytes(password) 147 | if err != nil { 148 | return nil, fmt.Errorf("making header: %w", err) 149 | } 150 | return headerBytes, nil 151 | } 152 | 153 | func PrependHeader( 154 | headless io.Reader, 155 | headed io.Writer, 156 | header []byte, 157 | ) error { 158 | _, err := headed.Write(header) 159 | if err != nil { 160 | return fmt.Errorf("writing header: %w", err) 161 | } 162 | 163 | for { 164 | data := make([]byte, readSize) 165 | n, err := headless.Read(data) 166 | eof := err == io.EOF 167 | if (err != nil) && (err != io.EOF) { 168 | return fmt.Errorf("reading body data: %w", err) 169 | } 170 | data = data[:n] 171 | 172 | _, err = headed.Write(data) 173 | if err != nil { 174 | return fmt.Errorf("writing body data: %w", err) 175 | } 176 | 177 | if eof { 178 | break 179 | } 180 | } 181 | return nil 182 | } 183 | 184 | func HeaderSize(settings Settings) int { 185 | size := baseHeaderSize + 3*len(settings.Comments) 186 | if settings.Deniability { 187 | size += len(seeds{}.DenyNonce) + len(seeds{}.DenySalt) 188 | } 189 | return size 190 | } 191 | -------------------------------------------------------------------------------- /internal/encryption/expected_errors_test.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "errors" 7 | "io" 8 | "os" 9 | "testing" 10 | ) 11 | 12 | func TestFileTooShort(t *testing.T) { 13 | argonKey = argon2IDKey 14 | for size := range []int{0, 10} { 15 | invalidData := make([]byte, size) 16 | _, err := rand.Read(invalidData) 17 | if err != nil { 18 | t.Fatal("creating random data:", err) 19 | } 20 | _, err = Decrypt("password", []io.Reader{}, bytes.NewBuffer(invalidData), bytes.NewBuffer([]byte{}), false) 21 | if !errors.Is(err, ErrFileTooShort) { 22 | t.Fatal("expected ErrFileTooShort, got", err) 23 | } 24 | } 25 | } 26 | 27 | func TestHeaderCorrupted(t *testing.T) { 28 | argonKey = argon2IDKey 29 | invalidData := make([]byte, 1000) 30 | _, err := rand.Read(invalidData) 31 | if err != nil { 32 | t.Fatal("creating random data:", err) 33 | } 34 | _, err = Decrypt("password", []io.Reader{}, bytes.NewBuffer(invalidData), bytes.NewBuffer([]byte{}), false) 35 | if !errors.Is(err, ErrHeaderCorrupted) { 36 | t.Fatal("expected ErrHeaderCorrupted, got", err) 37 | } 38 | } 39 | 40 | func TestIncorrectPassword(t *testing.T) { 41 | argonKey = argon2IDKey 42 | reader, err := os.Open("picocrypt_samples/v1.48/base1000.pcv") 43 | if err != nil { 44 | t.Fatal("opening file:", err) 45 | } 46 | defer reader.Close() 47 | _, err = Decrypt("wrong-password", []io.Reader{}, reader, bytes.NewBuffer([]byte{}), false) 48 | if !errors.Is(err, ErrIncorrectPassword) { 49 | t.Fatal("expected wrong password, got", err) 50 | } 51 | } 52 | 53 | func TestIncorrectKeyfiles(t *testing.T) { 54 | argonKey = argon2IDKey 55 | reader, err := os.Open("picocrypt_samples/v1.48/base0_kf12o.pcv") 56 | if err != nil { 57 | t.Fatal("opening file:", err) 58 | } 59 | wrongKeyfileData := make([]byte, 100) 60 | rand.Read(wrongKeyfileData) 61 | defer reader.Close() 62 | _, err = Decrypt("password", []io.Reader{bytes.NewBuffer(wrongKeyfileData)}, reader, bytes.NewBuffer([]byte{}), false) 63 | if !errors.Is(err, ErrIncorrectOrMisorderedKeyfiles) { 64 | t.Fatal("expected wrong keyfieles, got", err) 65 | } 66 | } 67 | 68 | func TestKeyfilesRequired(t *testing.T) { 69 | argonKey = argon2IDKey 70 | reader, err := os.Open("picocrypt_samples/v1.48/base0_kf12o.pcv") 71 | if err != nil { 72 | t.Fatal("opening file:", err) 73 | } 74 | defer reader.Close() 75 | _, err = Decrypt("password", []io.Reader{}, reader, bytes.NewBuffer([]byte{}), false) 76 | if !errors.Is(err, ErrKeyfilesRequired) { 77 | t.Fatal("expected required keyfiles, got", err) 78 | } 79 | } 80 | 81 | func TestDuplicateKeyfiles(t *testing.T) { 82 | argonKey = argon2IDKey 83 | keyfileData := make([]byte, 100) 84 | rand.Read(keyfileData) 85 | keyfiles := []io.Reader{} 86 | for range 2 { 87 | buff := make([]byte, len(keyfileData)) 88 | copy(buff, keyfileData) 89 | keyfiles = append(keyfiles, bytes.NewBuffer(buff)) 90 | } 91 | _, err := EncryptHeadless( 92 | bytes.NewBuffer([]byte{}), 93 | "test-password", 94 | keyfiles, 95 | Settings{}, 96 | bytes.NewBuffer([]byte{}), 97 | ) 98 | if !errors.Is(err, ErrDuplicateKeyfiles) { 99 | t.Fatal("expected ErrDuplicateKeyfiles, got", err) 100 | } 101 | } 102 | 103 | func TestKeyfilesNotRequired(t *testing.T) { 104 | argonKey = argon2IDKey 105 | reader, err := os.Open("picocrypt_samples/v1.48/base1000.pcv") 106 | if err != nil { 107 | t.Fatal("opening file:", err) 108 | } 109 | defer reader.Close() 110 | _, err = Decrypt("password", []io.Reader{bytes.NewBuffer([]byte{})}, reader, bytes.NewBuffer([]byte{}), false) 111 | if !errors.Is(err, ErrKeyfilesNotRequired) { 112 | t.Fatal("expected ErrKeyfilesNotRequired, got", err) 113 | } 114 | } 115 | 116 | func TestCorrupted(t *testing.T) { 117 | argonKey = argon2IDKey 118 | reader, err := os.Open("picocrypt_samples/v1.48/base1000.pcv") 119 | if err != nil { 120 | t.Fatal("opening file:", err) 121 | } 122 | defer reader.Close() 123 | r := bytes.NewBuffer([]byte{}) 124 | _, err = io.Copy(r, reader) 125 | if err != nil { 126 | t.Fatal("reading file:", err) 127 | } 128 | rawBytes := r.Bytes() 129 | copy(rawBytes[:], []byte("corrupted")) 130 | corruptedReader := bytes.NewBuffer(rawBytes) 131 | _, err = Decrypt("qwerty", []io.Reader{}, corruptedReader, bytes.NewBuffer([]byte{}), false) 132 | if !errors.Is(err, ErrHeaderCorrupted) { 133 | t.Fatal("expected ErrHeaderCorrupted, got", err) 134 | } 135 | } 136 | 137 | func TestDamagedButRecoverable(t *testing.T) { 138 | argonKey = argon2IDKey 139 | reader, err := os.Open("picocrypt_samples/v1.48/base1000_r.pcv") 140 | if err != nil { 141 | t.Fatal("opening file:", err) 142 | } 143 | defer reader.Close() 144 | 145 | encryptedData, err := io.ReadAll(reader) 146 | if err != nil { 147 | t.Fatal("reading file:", err) 148 | } 149 | 150 | encryptedData[1000] = byte(int(encryptedData[1000]) + 1) 151 | 152 | damaged, err := Decrypt("password", []io.Reader{}, bytes.NewBuffer(encryptedData), bytes.NewBuffer([]byte{}), false) 153 | if err != nil { 154 | t.Fatal("expected no error, got", err) 155 | } 156 | if !damaged { 157 | t.Fatal("expected damage") 158 | } 159 | } 160 | 161 | func TestCommentsTooLong(t *testing.T) { 162 | argonKey = argon2IDKey 163 | comments := make([]byte, maxCommentsLength+1) 164 | _, err := EncryptHeadless( 165 | bytes.NewBuffer([]byte{}), 166 | "test-password", 167 | []io.Reader{}, 168 | Settings{Comments: string(comments)}, 169 | bytes.NewBuffer([]byte{}), 170 | ) 171 | if !errors.Is(err, ErrCommentsTooLong) { 172 | t.Fatal("expected ErrCommentsTooLong, got", err) 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /internal/encryption/header.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "encoding/binary" 7 | "fmt" 8 | "io" 9 | ) 10 | 11 | const ( 12 | baseHeaderSize = 789 13 | versionSize = 5 14 | commentSize = 5 15 | flagsSize = 5 16 | ) 17 | 18 | type seeds struct { 19 | // export to allow binary package to fill 20 | Salt [16]byte 21 | Nonce [24]byte 22 | SerpentIV [16]byte 23 | HkdfSalt [32]byte 24 | DenySalt [16]byte 25 | DenyNonce [24]byte 26 | } 27 | 28 | type refs struct { 29 | keyRef [64]byte 30 | keyfileRef [32]byte 31 | macTag [64]byte 32 | } 33 | 34 | type header struct { 35 | settings Settings 36 | seeds seeds 37 | refs refs 38 | usesKf bool 39 | nearMiBFlag bool // set when the original data is within 1 chunk of a MiB 40 | } 41 | 42 | func (header *header) bytes(password string) ([]byte, error) { 43 | data := [][]byte{[]byte(picocryptVersion)} 44 | data = append(data, []byte(fmt.Sprintf("%05d", len(header.settings.Comments)))) 45 | for _, c := range []byte(header.settings.Comments) { 46 | data = append(data, []byte{c}) 47 | } 48 | flags := []bool{ 49 | header.settings.Paranoid, 50 | header.usesKf, 51 | header.settings.OrderedKf, 52 | header.settings.ReedSolomon, 53 | header.nearMiBFlag, 54 | } 55 | flagBytes := make([]byte, len(flags)) 56 | for i, f := range flags { 57 | if f { 58 | flagBytes[i] = 1 59 | } 60 | } 61 | data = append(data, flagBytes) 62 | data = append(data, header.seeds.Salt[:]) 63 | data = append(data, header.seeds.HkdfSalt[:]) 64 | data = append(data, header.seeds.SerpentIV[:]) 65 | data = append(data, header.seeds.Nonce[:]) 66 | data = append(data, header.refs.keyRef[:]) 67 | data = append(data, header.refs.keyfileRef[:]) 68 | data = append(data, header.refs.macTag[:]) 69 | 70 | headerBytes := make([]byte, baseHeaderSize+3*len(header.settings.Comments)) 71 | written := 0 72 | for _, d := range data { 73 | err := rsEncode(headerBytes[written:written+len(d)*3], d) 74 | if err != nil { 75 | return nil, err 76 | } 77 | written += len(d) * 3 78 | } 79 | 80 | if header.settings.Deniability { 81 | denyStream := newDeniabilityStream(password, header) 82 | var err error 83 | headerBytes, err = denyStream.stream(headerBytes) 84 | if err != nil { 85 | return nil, fmt.Errorf("denying header data: %w", err) 86 | } 87 | headerBytes = append(append(header.seeds.DenySalt[:], header.seeds.DenyNonce[:]...), headerBytes...) 88 | } 89 | 90 | return headerBytes, nil 91 | } 92 | 93 | func randomSeeds() (seeds, error) { 94 | raw := make([]byte, binary.Size(seeds{})) 95 | _, err := io.ReadFull(rand.Reader, raw) 96 | if err != nil { 97 | return seeds{}, err 98 | } 99 | decoded := seeds{} 100 | err = binary.Read(bytes.NewBuffer(raw), binary.BigEndian, &decoded) 101 | return decoded, err 102 | } 103 | -------------------------------------------------------------------------------- /internal/encryption/keys.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "bytes" 5 | "errors" 6 | "fmt" 7 | "hash" 8 | "io" 9 | 10 | "golang.org/x/crypto/argon2" 11 | "golang.org/x/crypto/hkdf" 12 | "golang.org/x/crypto/sha3" 13 | ) 14 | 15 | type keys struct { 16 | key [32]byte 17 | macKey [32]byte 18 | serpentKey [32]byte 19 | denyKey [32]byte 20 | hkdf io.Reader 21 | keyRef [64]byte 22 | keyfileRef [32]byte 23 | } 24 | 25 | func xor(a, b [32]byte) [32]byte { 26 | var result [32]byte 27 | for i := range a { 28 | result[i] = a[i] ^ b[i] 29 | } 30 | return result 31 | } 32 | 33 | func generateKeyfileKey(ordered bool, keyfiles []io.Reader) ([32]byte, error) { 34 | if len(keyfiles) == 0 { 35 | return [32]byte{}, nil 36 | } 37 | 38 | hashes := make([][32]byte, len(keyfiles)) 39 | hasher := sha3.New256() 40 | for i, file := range keyfiles { 41 | if err := computeHash(hasher, file, hashes[i][:]); err != nil { 42 | return [32]byte{}, err 43 | } 44 | if !ordered { 45 | hasher.Reset() 46 | } 47 | } 48 | 49 | if ordered { 50 | key := [32]byte{} 51 | copy(key[:], hasher.Sum(nil)) 52 | return key, nil 53 | } 54 | 55 | key := [32]byte{} 56 | for _, hash := range hashes { 57 | key = xor(key, hash) 58 | } 59 | if hasDuplicates(hashes) { 60 | return key, ErrDuplicateKeyfiles 61 | } 62 | return key, nil 63 | } 64 | 65 | func hasDuplicates(hashes [][32]byte) bool { 66 | hashSet := make(map[string]struct{}, len(hashes)) 67 | for _, hash := range hashes { 68 | hashStr := string(hash[:]) 69 | if _, exists := hashSet[hashStr]; exists { 70 | return true 71 | } 72 | hashSet[hashStr] = struct{}{} 73 | } 74 | return false 75 | } 76 | 77 | func argon2IDKey(password string, salt [16]byte, iterations uint32, parallelism uint8) [32]byte { 78 | var key [32]byte 79 | copy(key[:], argon2.IDKey([]byte(password), salt[:], iterations, 1<<20, parallelism, 32)) 80 | return key 81 | } 82 | 83 | var argonKey = argon2IDKey 84 | 85 | func generatePasswordKey(password string, salt [16]byte, paranoid bool) [32]byte { 86 | iterations := uint32(4) 87 | parallelism := uint8(4) 88 | if paranoid { 89 | iterations = 8 90 | parallelism = 8 91 | } 92 | return argonKey(password, salt, iterations, parallelism) 93 | } 94 | 95 | func generateDenyKey(password string, salt [16]byte) [32]byte { 96 | return argonKey(password, salt, 4, 4) 97 | } 98 | 99 | func newKeys(settings Settings, seeds seeds, password string, keyfiles []io.Reader) (keys, error) { 100 | keyfileKey, err := generateKeyfileKey(settings.OrderedKf, keyfiles) 101 | if err != nil && !errors.Is(err, ErrDuplicateKeyfiles) { 102 | return keys{}, fmt.Errorf("creating keys: %w", err) 103 | } 104 | duplicateKeyfiles := errors.Is(err, ErrDuplicateKeyfiles) 105 | 106 | passwordKey := generatePasswordKey(password, seeds.Salt, settings.Paranoid) 107 | 108 | var keyRef [64]byte 109 | err = computeHash(sha3.New512(), bytes.NewBuffer(passwordKey[:]), keyRef[:]) 110 | if err != nil { 111 | return keys{}, fmt.Errorf("creating keys: %w", err) 112 | } 113 | var keyfileRef [32]byte 114 | if len(keyfiles) > 0 { 115 | computeHash(sha3.New256(), bytes.NewBuffer(keyfileKey[:]), keyfileRef[:]) 116 | } 117 | 118 | key := xor(keyfileKey, passwordKey) 119 | 120 | var denyKey [32]byte 121 | if settings.Deniability { 122 | denyKey = generateDenyKey(password, seeds.DenySalt) 123 | } 124 | 125 | hkdf := hkdf.New(sha3.New256, key[:], seeds.HkdfSalt[:], nil) 126 | var macKey [32]byte 127 | if _, err := io.ReadFull(hkdf, macKey[:]); err != nil { 128 | return keys{}, fmt.Errorf("filling macKey: %w", err) 129 | } 130 | var serpentKey [32]byte 131 | if _, err := io.ReadFull(hkdf, serpentKey[:]); err != nil { 132 | return keys{}, fmt.Errorf("filling serpentKey: %w", err) 133 | } 134 | 135 | keys := keys{ 136 | key: key, 137 | macKey: macKey, 138 | serpentKey: serpentKey, 139 | denyKey: denyKey, 140 | hkdf: hkdf, 141 | keyRef: keyRef, 142 | keyfileRef: keyfileRef, 143 | } 144 | 145 | if duplicateKeyfiles { 146 | return keys, ErrDuplicateKeyfiles 147 | } 148 | return keys, nil 149 | } 150 | 151 | func computeHash(hasher hash.Hash, src io.Reader, dest []byte) error { 152 | data, err := io.ReadAll(src) 153 | if err != nil { 154 | return fmt.Errorf("reading src: %w", err) 155 | } 156 | _, err = hasher.Write(data) 157 | if err != nil { 158 | return fmt.Errorf("hashing src: %w", err) 159 | } 160 | copy(dest, hasher.Sum(nil)) 161 | return nil 162 | } 163 | -------------------------------------------------------------------------------- /internal/encryption/keys_test.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "errors" 7 | "io" 8 | "testing" 9 | ) 10 | 11 | func TestXor(t *testing.T) { 12 | zeros := [32]byte{} 13 | ones := [32]byte{} 14 | for i := 0; i < len(ones); i++ { 15 | ones[i] = 255 16 | } 17 | 18 | result := xor(zeros, zeros) 19 | if !bytes.Equal(zeros[:], result[:]) { 20 | t.Fatal("xor zeros with zeros should be zero") 21 | } 22 | 23 | result = xor(ones, ones) 24 | if !bytes.Equal(zeros[:], result[:]) { 25 | t.Fatal("xor ones with ones should be zero") 26 | } 27 | 28 | result = xor(zeros, ones) 29 | if !bytes.Equal(ones[:], result[:]) { 30 | t.Fatal("xor zeros with ones should be ones") 31 | } 32 | 33 | result = xor(ones, zeros) 34 | if !bytes.Equal(ones[:], result[:]) { 35 | t.Fatal("xor ones with zeros should be zero") 36 | } 37 | } 38 | 39 | func TestGenKeyfileKeyOrdered(t *testing.T) { 40 | kf1 := make([]byte, 100) 41 | rand.Read(kf1) 42 | kf2 := make([]byte, 200) 43 | rand.Read(kf2) 44 | 45 | kf12 := []io.Reader{bytes.NewBuffer(kf1), bytes.NewBuffer(kf2)} 46 | key12, err := generateKeyfileKey(true, kf12) 47 | if err != nil { 48 | t.Fatal("generating keyfile key:", err) 49 | } 50 | 51 | kf21 := []io.Reader{bytes.NewBuffer(kf2), bytes.NewBuffer(kf1)} 52 | key21, err := generateKeyfileKey(true, kf21) 53 | if err != nil { 54 | t.Fatal("generating keyfile key:", err) 55 | } 56 | 57 | if bytes.Equal(key12[:], key21[:]) { 58 | t.Fatal("key order should change result") 59 | } 60 | } 61 | 62 | func TestGenKeyfileKeyUnordered(t *testing.T) { 63 | kf1 := make([]byte, 100) 64 | rand.Read(kf1) 65 | kf2 := make([]byte, 200) 66 | rand.Read(kf2) 67 | 68 | kf12 := []io.Reader{bytes.NewBuffer(kf1), bytes.NewBuffer(kf2)} 69 | key12, err := generateKeyfileKey(false, kf12) 70 | if err != nil { 71 | t.Fatal("generating keyfile key:", err) 72 | } 73 | 74 | kf21 := []io.Reader{bytes.NewBuffer(kf2), bytes.NewBuffer(kf1)} 75 | key21, err := generateKeyfileKey(false, kf21) 76 | if err != nil { 77 | t.Fatal("generating keyfile key:", err) 78 | } 79 | 80 | if !bytes.Equal(key12[:], key21[:]) { 81 | t.Fatal("key order should not change result") 82 | } 83 | } 84 | 85 | func TestGenKeyfileKeyDuplicated(t *testing.T) { 86 | kf1 := make([]byte, 100) 87 | kf2 := make([]byte, 100) 88 | kf3 := make([]byte, 100) 89 | rand.Read(kf1) 90 | copy(kf2[:], kf1[:]) 91 | rand.Read(kf3) 92 | key, err := generateKeyfileKey( 93 | false, 94 | []io.Reader{bytes.NewBuffer(kf1), bytes.NewBuffer(kf2), bytes.NewBuffer(kf3)}, 95 | ) 96 | if !errors.Is(err, ErrDuplicateKeyfiles) { 97 | t.Fatal("expected duplicate keyfile error") 98 | } 99 | if bytes.Equal(key[:], make([]byte, 32)) { 100 | t.Fatal("key should still be generated") 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /internal/encryption/picocrypt_compatibility_test.go: -------------------------------------------------------------------------------- 1 | // Test for combatibility with Picocrypt 2 | package encryption 3 | 4 | import ( 5 | "bytes" 6 | "crypto/sha256" 7 | "encoding/hex" 8 | "hash" 9 | "io" 10 | "log" 11 | "os" 12 | "strconv" 13 | "strings" 14 | "testing" 15 | ) 16 | 17 | var compatibilityVersions = []string{"v1.47", "v1.48"} 18 | 19 | /* Decrypt files encrypted by Picocrypt 20 | 21 | To generate the test files, choose a version of Picocrypt and rotate through each file under 22 | picocrypt_samples/basefiles. The file sizes tested are: 23 | - 0 bytes. While encrypted empyt files is not really meaningful, encryption should still work 24 | - 1000 bytes. Just a generic small file of data 25 | - 1048570 bytes. This should trigger the extra flag for Reed-Solomon encoding that Picocrypt uses 26 | 27 | Encrypt each file with password "password". Append the following strings to the filename to indicate 28 | what other encryption settings were used. Note that only the keyfile settings are actually used in 29 | the test because the others can be derived from the header data. The non-keyfile suffixes are just 30 | for reference to check what combinations of settings are being tested. 31 | - "_c" indicates that comments were used 32 | - "_p" indicates that paranoid mode was used 33 | - "_r" indicates that Reed-Solomon encoding was used 34 | - "_d" indicates that deniability mode was used 35 | - "_kf1" indicates that keyfile 1 was used 36 | - "_kf12" indicates that keyfiles 1 and 2 were used 37 | - "_kf12o" indicates that keyfiles 1 and 2 were used, and the keyfiles were ordered 38 | 39 | The encrypted files should be stored under picocrypt_samples// 40 | */ 41 | 42 | func getTestKeyfiles(name string) []io.Reader { 43 | kf := []io.Reader{} 44 | usesKf1 := strings.Contains(name, "kf1") 45 | usesKf2 := strings.Contains(name, "kf12") 46 | for i, used := range []bool{usesKf1, usesKf2} { 47 | if !used { 48 | continue 49 | } 50 | r, err := os.Open("picocrypt_samples/keyfiles/keyfile" + strconv.Itoa(i+1)) 51 | if err != nil { 52 | log.Fatal("opening keyfile: %w", err) 53 | } 54 | defer r.Close() 55 | buf := bytes.NewBuffer([]byte{}) 56 | _, err = io.Copy(buf, r) 57 | if err != nil { 58 | log.Fatal("reading keyfile: %w", err) 59 | } 60 | kf = append(kf, buf) 61 | } 62 | return kf 63 | } 64 | 65 | func getBaseData(name string) []byte { 66 | basename := strings.SplitN(name, ".", 2)[0] 67 | if strings.Contains(basename, "_") { 68 | basename = strings.SplitN(basename, "_", 2)[0] 69 | } 70 | r, err := os.Open("picocrypt_samples/basefiles/" + basename) 71 | if err != nil { 72 | log.Fatal("opening file: %w", err) 73 | } 74 | defer r.Close() 75 | buf := bytes.NewBuffer([]byte{}) 76 | _, err = io.Copy(buf, r) 77 | if err != nil { 78 | log.Fatal("reading file: %w", err) 79 | } 80 | return buf.Bytes() 81 | } 82 | 83 | func TestDecryptingPicocryptFiles(t *testing.T) { 84 | for _, version := range compatibilityVersions { 85 | files, err := os.ReadDir("picocrypt_samples/" + version) 86 | if err != nil { 87 | t.Fatal("reading directory: %w", err) 88 | } 89 | for _, file := range files { 90 | if !(strings.HasSuffix(file.Name(), ".pcv")) { 91 | continue 92 | } 93 | t.Run(version+":"+file.Name(), func(t *testing.T) { 94 | r, err := os.Open("picocrypt_samples/" + version + "/" + file.Name()) 95 | if err != nil { 96 | t.Fatal("opening encrypted file: %w", err) 97 | } 98 | defer r.Close() 99 | w := bytes.NewBuffer([]byte{}) 100 | kf := getTestKeyfiles(file.Name()) 101 | damaged, err := Decrypt("password", kf, r, w, false) 102 | if damaged { 103 | t.Fatal("damaged data") 104 | } 105 | if err != nil { 106 | t.Fatal("decrypting:", err) 107 | } 108 | result := w.Bytes() 109 | expected := getBaseData(file.Name()) 110 | if !bytes.Equal(result, expected) { 111 | t.Fatal("decrypted data does not match") 112 | } 113 | }) 114 | } 115 | } 116 | } 117 | 118 | /* Test encryption parity with Picocrypt 119 | 120 | Given the same header (seeds, settings, etc), same password, and same keyfiles, the encryption 121 | package should produce exactly the same output as Picocrypt. Run through each file in the 122 | latest version and ensure that the encrypted data matches exactly. 123 | */ 124 | 125 | func extractSettings(path string) (Settings, seeds) { 126 | r, err := os.Open(path) 127 | if err != nil { 128 | log.Fatal("opening file: %w", err) 129 | } 130 | defer r.Close() 131 | header, err := getHeader(r, "password") 132 | if err != nil { 133 | log.Fatal("reading header: %w", err) 134 | } 135 | return header.settings, header.seeds 136 | } 137 | 138 | func TestEncryptedFilesMatchPicocrypt(t *testing.T) { 139 | latestVersion := compatibilityVersions[len(compatibilityVersions)-1] 140 | files, err := os.ReadDir("picocrypt_samples/" + latestVersion) 141 | if err != nil { 142 | t.Fatal("reading directory: %w", err) 143 | } 144 | for _, file := range files { 145 | if !(strings.HasSuffix(file.Name(), ".pcv")) { 146 | continue 147 | } 148 | t.Run("encrypting:"+file.Name(), func(t *testing.T) { 149 | path := "picocrypt_samples/" + latestVersion + "/" + file.Name() 150 | settings, seeds := extractSettings(path) 151 | kf := getTestKeyfiles(file.Name()) 152 | w := bytes.NewBuffer([]byte{}) 153 | header, err := encryptWithSeeds( 154 | bytes.NewBuffer(getBaseData(file.Name())), 155 | "password", 156 | kf, 157 | settings, 158 | w, 159 | seeds, 160 | ) 161 | if err != nil { 162 | t.Fatal("encrypting:", err) 163 | } 164 | full := bytes.NewBuffer([]byte{}) 165 | err = PrependHeader(bytes.NewBuffer(w.Bytes()), full, header) 166 | if err != nil { 167 | t.Fatal("prepending header:", err) 168 | } 169 | result := full.Bytes() 170 | 171 | r, err := os.Open(path) 172 | if err != nil { 173 | t.Fatal("opening encrypted file: %w", err) 174 | } 175 | defer r.Close() 176 | buf := bytes.NewBuffer([]byte{}) 177 | _, err = io.Copy(buf, r) 178 | if err != nil { 179 | t.Fatal("reading file: %w", err) 180 | } 181 | expected := buf.Bytes() 182 | 183 | if !bytes.Equal(result, expected) { 184 | t.Fatal("encrypted data does not match") 185 | } 186 | }) 187 | } 188 | } 189 | 190 | /* Compare encryption and decryption for very large files 191 | 192 | The encryption and decryption methods rotate the nonces every 60 GB. To accurately test this, 193 | encrypt/decrypt files larger than 60 GB. Instead of adding files that large to the repository, 194 | create a test that simulates this behavior. These tests will generate files of zeros, encrypt 195 | them, and then decrypt them. The sha256 of the encrypted and decrypted files are compared against 196 | expected values generated by hand, following these steps: 197 | 198 | 1. Create a file of zeros (bash ex: dd if=/dev/zero of=zerofile bs=1M count=62464) 199 | 2. Get the sha256 of the file (bash ex: sha256sum zerofile) 200 | 3. Encrypt the file using the latest Picocrypt version. This is a long test, so only check against 201 | one version 202 | 4. Get the sha256sum of the encrypted file (bash ex: sha256sum zerofile.pcv) 203 | 5. Save the header bytes from the encrypted file (bash ex: head -c 789 zerofile.pcv > zerofile.header). 204 | 6. Create a test with the header bytes and the sha256sums 205 | */ 206 | 207 | type zeroReader struct { 208 | size int64 209 | counter int64 210 | } 211 | 212 | func (z *zeroReader) Read(p []byte) (n int, err error) { 213 | if z.counter == z.size { 214 | return 0, io.EOF 215 | } 216 | for i := range p { 217 | p[i] = 0 218 | z.counter++ 219 | if z.counter == z.size { 220 | return i + 1, nil 221 | } 222 | } 223 | return len(p), nil 224 | } 225 | 226 | type shaDecryptWriter struct { 227 | decryptStream *decryptStream 228 | encryptedSha hash.Hash 229 | decryptedSha hash.Hash 230 | } 231 | 232 | func (s *shaDecryptWriter) Write(p []byte) (int, error) { 233 | _, err := s.encryptedSha.Write(p) 234 | if err != nil { 235 | return 0, err 236 | } 237 | decoded, err := s.decryptStream.stream(p) 238 | if err != nil { 239 | return 0, err 240 | } 241 | _, err = s.decryptedSha.Write(decoded) 242 | if err != nil { 243 | return 0, err 244 | } 245 | return len(p), nil 246 | } 247 | 248 | func (s *shaDecryptWriter) shas() ([]byte, []byte, error) { 249 | decoded, err := s.decryptStream.flush() 250 | if err != nil { 251 | return nil, nil, err 252 | } 253 | _, err = s.decryptedSha.Write(decoded) 254 | if err != nil { 255 | return nil, nil, err 256 | } 257 | return s.encryptedSha.Sum(nil), s.decryptedSha.Sum(nil), nil 258 | } 259 | 260 | func compareShas( 261 | t *testing.T, 262 | password string, 263 | headerFilename string, 264 | encodedSha string, 265 | decodedSha string, 266 | zeroFileSize int64, 267 | ) { 268 | headerReader, err := os.Open(headerFilename) 269 | if err != nil { 270 | t.Fatal("opening header file:", err) 271 | } 272 | defer headerReader.Close() 273 | headerBytes, err := io.ReadAll(headerReader) 274 | if err != nil { 275 | t.Fatal("reading header:", err) 276 | } 277 | 278 | damageTracker := &damageTracker{} 279 | writer := &shaDecryptWriter{makeDecryptStream(password, nil, damageTracker), sha256.New(), sha256.New()} 280 | _, err = writer.Write(headerBytes) 281 | if err != nil { 282 | t.Fatal("writing header:", err) 283 | } 284 | if !writer.decryptStream.headerStream.isDone() { 285 | t.Fatal("header stream should be done") 286 | } 287 | 288 | _, err = encryptWithSeeds( 289 | &zeroReader{size: zeroFileSize}, 290 | password, 291 | []io.Reader{}, 292 | writer.decryptStream.headerStream.header.settings, 293 | writer, 294 | writer.decryptStream.headerStream.header.seeds, 295 | ) 296 | if err != nil { 297 | t.Fatal("encrypting:", err) 298 | } 299 | 300 | eSha, dSha, err := writer.shas() 301 | if err != nil { 302 | t.Fatal("getting shas:", err) 303 | } 304 | if hex.EncodeToString(eSha) != encodedSha { 305 | t.Fatal("encoded sha256 does not match") 306 | } 307 | if hex.EncodeToString(dSha) != decodedSha { 308 | t.Fatal("decoded sha256 does not match") 309 | } 310 | } 311 | 312 | func isLatestVersion(path string) bool { 313 | r, err := os.Open(path) 314 | if err != nil { 315 | log.Fatal("opening file: %w", err) 316 | } 317 | defer r.Close() 318 | expected := compatibilityVersions[len(compatibilityVersions)-1] 319 | buf := make([]byte, len(expected)) 320 | _, err = io.ReadFull(r, buf) 321 | if err != nil { 322 | log.Fatal("reading file: %w", err) 323 | } 324 | return string(buf) == expected 325 | } 326 | 327 | func TestSmallFileSha(t *testing.T) { 328 | // Test 1K file of zeros, for debugging 329 | path := "picocrypt_samples/headers/zerofile1024.header" 330 | if !isLatestVersion(path) { 331 | t.Fatal("header file is not latest version") 332 | } 333 | compareShas( 334 | t, 335 | "password", 336 | path, 337 | "bb8a1f6be9cfcd39cb8eedd49583ddfd7153158b8ffce541e256deb400160a98", 338 | "5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef", 339 | (1 << 10), // 1K 340 | ) 341 | } 342 | 343 | func TestLargeFileSha(t *testing.T) { 344 | // Test 65GB file of zeros 345 | path := "picocrypt_samples/headers/zerofile65498251264.header" 346 | if !isLatestVersion(path) { 347 | t.Fatal("header file is not latest version") 348 | } 349 | compareShas( 350 | t, 351 | "password", 352 | path, 353 | "451dd75500b9502e7c82fa679e698443337d33c52ddb84d5a14c3ff95032dc50", 354 | "f3f0d678fa138e4581ed15ec63f8cb965e5d7b722db7d5fc4877e763163d399c", 355 | 65498251264, 356 | ) 357 | } 358 | -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/basefiles/base0: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/basefiles/base0 -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/basefiles/base1000: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/basefiles/base1000 -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/basefiles/base1048570: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/basefiles/base1048570 -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/headers/zerofile1024.header: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/headers/zerofile1024.header -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/headers/zerofile65498251264.header: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/headers/zerofile65498251264.header -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/keyfiles/keyfile1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/keyfiles/keyfile1 -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/keyfiles/keyfile2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/keyfiles/keyfile2 -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base0.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base0.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base0_c.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base0_c.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base0_d.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base0_d.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base0_kf1.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base0_kf1.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base0_kf12.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base0_kf12.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base0_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base0_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base0_p.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base0_p.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base0_p_r_d_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base0_p_r_d_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base0_r.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base0_r.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1000.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1000.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1000_c.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1000_c.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1000_c_p_r_d_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1000_c_p_r_d_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1000_d.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1000_d.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1000_kf1.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1000_kf1.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1000_kf12.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1000_kf12.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1000_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1000_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1000_p.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1000_p.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1000_r.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1000_r.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1048570.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1048570.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1048570_c.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1048570_c.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1048570_d.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1048570_d.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1048570_kf1.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1048570_kf1.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1048570_kf12.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1048570_kf12.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1048570_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1048570_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1048570_p.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1048570_p.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1048570_p_r_d_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1048570_p_r_d_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.47/base1048570_r.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.47/base1048570_r.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base0.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base0.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base0_c.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base0_c.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base0_d.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base0_d.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base0_kf1.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base0_kf1.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base0_kf12.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base0_kf12.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base0_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base0_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base0_p.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base0_p.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base0_p_r_d_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base0_p_r_d_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base0_r.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base0_r.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1000.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1000.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1000_c.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1000_c.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1000_d.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1000_d.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1000_kf1.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1000_kf1.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1000_kf12.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1000_kf12.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1000_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1000_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1000_p.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1000_p.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1000_p_r_d_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1000_p_r_d_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1000_r.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1000_r.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1048570.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1048570.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1048570_c.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1048570_c.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1048570_d.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1048570_d.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1048570_kf1.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1048570_kf1.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1048570_kf12.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1048570_kf12.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1048570_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1048570_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1048570_p.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1048570_p.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1048570_p_r_d_kf12o.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1048570_p_r_d_kf12o.pcv -------------------------------------------------------------------------------- /internal/encryption/picocrypt_samples/v1.48/base1048570_r.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/encryption/picocrypt_samples/v1.48/base1048570_r.pcv -------------------------------------------------------------------------------- /internal/encryption/reed_solomon.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "sync" 7 | 8 | "github.com/Picocrypt/infectious" 9 | ) 10 | 11 | const ( 12 | chunkSize = 128 13 | encodedSize = 136 14 | ) 15 | 16 | var ( 17 | fecs = make(map[[2]int]*infectious.FEC) 18 | fecsMu sync.Mutex 19 | ) 20 | 21 | func getFEC(encoded, decoded []byte) (*infectious.FEC, error) { 22 | size := [2]int{len(decoded), len(encoded)} 23 | 24 | fecsMu.Lock() 25 | defer fecsMu.Unlock() 26 | 27 | fec := fecs[size] 28 | if fec != nil { 29 | return fec, nil 30 | } 31 | 32 | fec, err := infectious.NewFEC(size[0], size[1]) 33 | if err != nil { 34 | return fec, err 35 | } 36 | 37 | fecs[size] = fec 38 | return fec, nil 39 | } 40 | 41 | func rsEncode(dst, src []byte) error { 42 | fec, err := getFEC(dst, src) 43 | if err != nil { 44 | return fmt.Errorf("getting FEC: %w", err) 45 | } 46 | return fec.Encode(src, func(s infectious.Share) { dst[s.Number] = s.Data[0] }) 47 | } 48 | 49 | func rsDecode(dst, src []byte, skip bool) (bool, bool, error) { 50 | if skip { 51 | copy(dst, src[:len(dst)]) 52 | return false, false, nil 53 | } 54 | 55 | // Encoding is much faster than decoding. Try re-encoding the original 56 | // bytes and if the result matches, there must have been no corruption. 57 | recoded := make([]byte, len(src)) 58 | rsEncode(recoded, src[:len(dst)]) 59 | if bytes.Equal(recoded, src) { 60 | copy(dst, src[:len(dst)]) 61 | return false, false, nil 62 | } 63 | 64 | // Attempt to recover damaged data 65 | fec, err := getFEC(src, dst) 66 | if err != nil { 67 | return true, false, fmt.Errorf("getting FEC: %w", err) 68 | } 69 | tmp := make([]infectious.Share, fec.Total()) 70 | for i := 0; i < fec.Total(); i++ { 71 | tmp[i].Number = i 72 | tmp[i].Data = []byte{src[i]} 73 | } 74 | res, err := fec.Decode(nil, tmp) 75 | if err == nil { 76 | copy(dst, res) 77 | return true, false, nil 78 | } 79 | 80 | // Fully corrupted - use a best guess 81 | copy(dst, src[:len(dst)]) 82 | return true, true, nil 83 | } 84 | 85 | type rsEncodeStream struct { 86 | buff []byte 87 | chunksEncoded int64 88 | header *header 89 | } 90 | 91 | func (r *rsEncodeStream) stream(p []byte) ([]byte, error) { 92 | r.buff = append(r.buff, p...) 93 | nChunks := len(r.buff) / chunkSize 94 | rsData := make([]byte, nChunks*encodedSize) 95 | for i := 0; i < nChunks; i++ { 96 | err := rsEncode(rsData[i*encodedSize:(i+1)*encodedSize], r.buff[i*chunkSize:(i+1)*chunkSize]) 97 | if err != nil { 98 | return nil, err 99 | } 100 | } 101 | r.buff = r.buff[nChunks*chunkSize:] 102 | r.chunksEncoded += int64(nChunks) 103 | return rsData, nil 104 | } 105 | 106 | func (r *rsEncodeStream) flush() ([]byte, error) { 107 | // Skip if exactly the right number of chunks encoded and there is no buffer data 108 | exactMiB := r.chunksEncoded%((1<<20)/chunkSize) == 0 109 | if exactMiB && len(r.buff) == 0 { 110 | return nil, nil 111 | } 112 | padding := make([]byte, chunkSize-len(r.buff)) 113 | for i := range padding { 114 | padding[i] = byte(chunkSize - len(r.buff)) 115 | } 116 | dst := make([]byte, encodedSize) 117 | err := rsEncode(dst, append(r.buff, padding...)) 118 | if err != nil { 119 | return nil, fmt.Errorf("encoding final chunk: %w", err) 120 | } 121 | return dst, nil 122 | } 123 | 124 | type rsDecodeStream struct { 125 | buff []byte 126 | skip bool 127 | damageTracker *damageTracker 128 | header *header 129 | chunksDecoded int64 130 | } 131 | 132 | func (r *rsDecodeStream) stream(p []byte) ([]byte, error) { 133 | r.buff = append(r.buff, p...) 134 | nChunks := len(r.buff) / encodedSize 135 | // The last chunk might be padded, so keep it in the buffer for flush 136 | if ((len(r.buff) % encodedSize) == 0) && (nChunks > 0) { 137 | nChunks -= 1 138 | } 139 | rsData := make([]byte, nChunks*chunkSize) 140 | for i := 0; i < nChunks; i++ { 141 | src := r.buff[i*encodedSize : (i+1)*encodedSize] 142 | dst := rsData[i*chunkSize : (i+1)*chunkSize] 143 | damaged, _, err := rsDecode(dst, src, r.skip) 144 | r.damageTracker.damage = r.damageTracker.damage || damaged 145 | if err != nil { 146 | return nil, err 147 | } 148 | } 149 | r.chunksDecoded += int64(nChunks) 150 | r.buff = r.buff[nChunks*encodedSize:] 151 | return rsData, nil 152 | } 153 | 154 | func (r *rsDecodeStream) flush() ([]byte, error) { 155 | if len(r.buff) == 0 { 156 | return nil, nil 157 | } 158 | if len(r.buff) != encodedSize { 159 | return nil, ErrBodyCorrupted 160 | } 161 | res := make([]byte, chunkSize) 162 | damaged, _, err := rsDecode(res, r.buff, r.skip) 163 | r.damageTracker.damage = r.damageTracker.damage || damaged 164 | if err != nil { 165 | return nil, err 166 | } 167 | // The last chunk is padded unless there is an exact multiple of MiB of decoded data 168 | // and the nearMiBFlag is not set 169 | exactMiB := (r.chunksDecoded+1)%((1<<20)/chunkSize) == 0 170 | if exactMiB && !r.header.nearMiBFlag { 171 | return res, nil 172 | } 173 | keep := chunkSize - int(res[chunkSize-1]) 174 | if (keep >= 0) && (keep < chunkSize) { 175 | return res[:keep], err 176 | } 177 | return nil, ErrBodyCorrupted 178 | } 179 | 180 | func makeRSEncodeStream(header *header) *rsEncodeStream { 181 | return &rsEncodeStream{header: header} 182 | } 183 | 184 | func makeRSDecodeStream(skip bool, header *header, damageTracker *damageTracker) *rsDecodeStream { 185 | return &rsDecodeStream{skip: skip, damageTracker: damageTracker, header: header} 186 | } 187 | -------------------------------------------------------------------------------- /internal/encryption/stream.go: -------------------------------------------------------------------------------- 1 | package encryption 2 | 3 | type streamer interface { 4 | stream(p []byte) ([]byte, error) 5 | } 6 | 7 | type streamerFlusher interface { 8 | streamer 9 | flush() ([]byte, error) 10 | } 11 | 12 | func streamStack[T streamer](streams []T, p []byte) ([]byte, error) { 13 | var err error 14 | for _, stream := range streams { 15 | p, err = stream.stream(p) 16 | if err != nil { 17 | return nil, err 18 | } 19 | if len(p) == 0 { 20 | break 21 | } 22 | } 23 | return p, nil 24 | } 25 | 26 | func flushStack(streams []streamerFlusher) ([]byte, error) { 27 | p := []byte{} 28 | for _, stream := range streams { 29 | pStream, err := stream.stream(p) 30 | if err != nil { 31 | return nil, err 32 | } 33 | pFlush, err := stream.flush() 34 | if err != nil { 35 | return nil, err 36 | } 37 | p = append(pStream, pFlush...) 38 | } 39 | return p, nil 40 | } 41 | -------------------------------------------------------------------------------- /internal/ui/elements.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "crypto/rand" 5 | "errors" 6 | "fmt" 7 | "time" 8 | 9 | "fyne.io/fyne/v2" 10 | "fyne.io/fyne/v2/container" 11 | "fyne.io/fyne/v2/dialog" 12 | "fyne.io/fyne/v2/layout" 13 | "fyne.io/fyne/v2/theme" 14 | "fyne.io/fyne/v2/widget" 15 | ) 16 | 17 | func MakeInfoBtn(w fyne.Window) *widget.Button { // coverage-ignore 18 | btn := widget.NewButtonWithIcon("", theme.InfoIcon(), func() { 19 | title := "PicoGo " + PicoGoVersion 20 | message := "This app is not sponsored or supported by Picocrypt. It is a 3rd party " + 21 | "app written to make Picocrypt files more easily accessible on mobile devices.\n\n" + 22 | "If you have any problems, please report them so that they can be fixed." 23 | confirm := dialog.NewInformation(title, message, w) 24 | confirm.Show() 25 | }) 26 | return btn 27 | } 28 | 29 | func writeLogsCallback(logger *Logger, window fyne.Window) func(fyne.URIWriteCloser, error) { 30 | return func(writer fyne.URIWriteCloser, err error) { 31 | if writer != nil { 32 | defer writer.Close() 33 | } 34 | if err != nil { // coverage-ignore 35 | logger.Log("Writing logs failed", State{}, err) 36 | dialog.ShowError(fmt.Errorf("writing logs: %w", err), window) 37 | return 38 | } 39 | if writer != nil { 40 | writer.Write([]byte(logger.CsvString())) 41 | } 42 | } 43 | } 44 | 45 | func writeLogs(logger *Logger, window fyne.Window) { // coverage-ignore 46 | d := dialog.NewFileSave(writeLogsCallback(logger, window), window) 47 | d.SetFileName("picogo-logs.csv") 48 | d.Show() 49 | } 50 | 51 | func MakeLogBtn(logger *Logger, w fyne.Window) *widget.Button { // coverage-ignore 52 | btn := widget.NewButtonWithIcon("", theme.MailSendIcon(), func() { 53 | title := "Save Logs" 54 | message := "Save log data to assist with issue reporting. Sensitive data (passwords, file names, etc.) " + 55 | "will not be recorded, but you should still review the logs before sharing to ensure you are " + 56 | "comfortable with the data being shared." 57 | text := widget.NewLabel(message) 58 | text.Wrapping = fyne.TextWrapWord 59 | dialog.ShowCustomConfirm(title, "Save Logs", "Dismiss", text, func(b bool) { 60 | if b { 61 | writeLogs(logger, w) 62 | } 63 | }, w) 64 | }) 65 | return btn 66 | } 67 | 68 | func MakeSettingsBtn(settings *Settings, parent fyne.Window) *widget.Button { // coverage-ignore 69 | btn := widget.NewButtonWithIcon("", theme.SettingsIcon(), func() { 70 | dialog.ShowCustom( 71 | "Default Settings", 72 | "Close", 73 | container.New( 74 | layout.NewVBoxLayout(), 75 | settings.ReedSolomonDefault, 76 | settings.ParanoidDefault, 77 | settings.DeniabilityDefault, 78 | settings.OrderedKfDefault, 79 | ), 80 | parent, 81 | ) 82 | }) 83 | return btn 84 | } 85 | 86 | func filePickerCallback(state *State, logger *Logger, w fyne.Window) func(fyne.URIReadCloser, error) { 87 | return func(reader fyne.URIReadCloser, err error) { 88 | if reader != nil { 89 | defer reader.Close() 90 | } 91 | if err != nil { // coverage-ignore 92 | logger.Log("Choosing file to encrypt/decrypt failed", *state, err) 93 | dialog.ShowError(fmt.Errorf("choosing file: %w", err), w) 94 | return 95 | } 96 | if reader == nil { 97 | logger.Log("Choosing file to encrypt/decrypt failed", *state, errors.New("no file chosen")) 98 | return 99 | } 100 | err = state.SetInput(reader.URI()) 101 | logger.Log("Setting file to encrypt/decrypt", *state, err) 102 | if err != nil { // coverage-ignore 103 | dialog.ShowError(fmt.Errorf("choosing file: %w", err), w) 104 | } 105 | } 106 | } 107 | 108 | func MakeFilePicker(state *State, logger *Logger, w fyne.Window) *widget.Button { // coverage-ignore 109 | picker := widget.NewButtonWithIcon("Choose File", theme.FileIcon(), func() { 110 | fd := dialog.NewFileOpen(filePickerCallback(state, logger, w), w) 111 | fd.Show() 112 | }) 113 | return picker 114 | } 115 | 116 | func makeComments() *widget.Entry { 117 | comments := widget.NewMultiLineEntry() 118 | comments.Validator = nil 119 | comments.Wrapping = fyne.TextWrapWord 120 | return comments 121 | } 122 | 123 | func keyfileText() *widget.Entry { // coverage-ignore 124 | text := widget.NewMultiLineEntry() 125 | text.Disable() 126 | text.SetPlaceHolder("No keyfiles added") 127 | return text 128 | } 129 | 130 | func keyfileAddCallback(state *State, logger *Logger, window fyne.Window) func(fyne.URIReadCloser, error) { 131 | return func(reader fyne.URIReadCloser, err error) { 132 | if reader != nil { 133 | defer reader.Close() 134 | } 135 | if err != nil { // coverage-ignore 136 | logger.Log("Adding keyfile failed", *state, err) 137 | dialog.ShowError(fmt.Errorf("adding keyfile: %w", err), window) 138 | return 139 | } 140 | if reader != nil { 141 | state.AddKeyfile(reader.URI()) 142 | logger.Log("Adding keyfile complete", *state, nil) 143 | } else { 144 | logger.Log("Adding keyfile canceled", *state, nil) 145 | } 146 | } 147 | } 148 | 149 | func KeyfileAddBtn(state *State, logger *Logger, window fyne.Window) *widget.Button { // coverage-ignore 150 | btn := widget.NewButtonWithIcon("Add", theme.ContentAddIcon(), func() { 151 | fd := dialog.NewFileOpen(keyfileAddCallback(state, logger, window), window) 152 | fd.Show() 153 | }) 154 | return btn 155 | } 156 | 157 | func keyfileCreateCallback(state *State, logger *Logger, window fyne.Window) func(fyne.URIWriteCloser, error) { 158 | return func(writer fyne.URIWriteCloser, err error) { 159 | if writer != nil { 160 | defer writer.Close() 161 | } 162 | if err != nil { // coverage-ignore 163 | logger.Log("Creating keyfile failed", *state, err) 164 | dialog.ShowError(fmt.Errorf("creating keyfile: %w", err), window) 165 | return 166 | } 167 | if writer != nil { 168 | data := make([]byte, 32) 169 | _, err := rand.Read(data) 170 | if err != nil { // coverage-ignore 171 | logger.Log("Creating keyfile data failed", *state, err) 172 | dialog.ShowError(fmt.Errorf("creating keyfile: %w", err), window) 173 | return 174 | } 175 | _, err = writer.Write(data) 176 | if err != nil { // coverage-ignore 177 | logger.Log("Writing keyfile failed", *state, err) 178 | dialog.ShowError(fmt.Errorf("writing keyfile: %w", err), window) 179 | return 180 | } 181 | state.AddKeyfile(writer.URI()) 182 | logger.Log("Created keyfile", *state, nil) 183 | } else { 184 | logger.Log("Creating keyfile canceled", *state, nil) 185 | } 186 | } 187 | } 188 | 189 | func KeyfileCreateBtn(state *State, logger *Logger, window fyne.Window) *widget.Button { // coverage-ignore 190 | btn := widget.NewButtonWithIcon("Create", theme.ContentAddIcon(), func() { 191 | fd := dialog.NewFileSave(keyfileCreateCallback(state, logger, window), window) 192 | fd.SetFileName("Keyfile") 193 | fd.Show() 194 | }) 195 | return btn 196 | } 197 | 198 | func keyfileClearCallback(state *State, logger *Logger) func() { 199 | return func() { 200 | logger.Log("Clearing keyfiles", *state, nil) 201 | state.ClearKeyfiles() 202 | } 203 | } 204 | 205 | func KeyfileClearBtn(state *State, logger *Logger) *widget.Button { // coverage-ignore 206 | btn := widget.NewButtonWithIcon("Clear", theme.ContentClearIcon(), keyfileClearCallback(state, logger)) 207 | return btn 208 | } 209 | 210 | func makePassword() *widget.Entry { 211 | password := widget.NewPasswordEntry() 212 | password.SetPlaceHolder("Password") 213 | password.Validator = nil 214 | return password 215 | } 216 | 217 | func makeConfirmPassword() *widget.Entry { 218 | confirm := widget.NewPasswordEntry() 219 | confirm.SetPlaceHolder("Confirm password") 220 | confirm.Validator = nil 221 | return confirm 222 | } 223 | 224 | func WorkBtnCallback(state *State, logger *Logger, w fyne.Window, encrypt func(), decrypt func()) func() { 225 | return func() { 226 | if !(state.IsEncrypting() || state.IsDecrypting()) { 227 | // This should never happen (the button should be hidden), but check in case 228 | // there is a race condition 229 | logger.Log("Encrypt/Decrypt button pressed", *state, errors.New("button should be hidden")) 230 | dialog.ShowError(errors.New("no file chosen"), w) 231 | return 232 | } 233 | if state.IsEncrypting() { 234 | if state.Password.Text != state.ConfirmPassword.Text { 235 | logger.Log("Encrypt/Decrypt button pressed", *state, errors.New("passwords do not match")) 236 | dialog.ShowError(errors.New("passwords do not match"), w) 237 | } else if state.Password.Text == "" { 238 | logger.Log("Encrypt/Decrypt button pressed", *state, errors.New("password cannot be blank")) 239 | dialog.ShowError(errors.New("password cannot be blank"), w) 240 | } else { 241 | logger.Log("Encrypt/Decrypt button pressed (encrypting)", *state, nil) 242 | encrypt() 243 | } 244 | return 245 | } 246 | logger.Log("Encrypt/Decrypt button pressed (decrypting)", *state, nil) 247 | decrypt() 248 | } 249 | } 250 | 251 | type ByteCounter struct { 252 | total int64 253 | startTime int64 254 | endTime int64 255 | } 256 | 257 | func (bc *ByteCounter) Read(p []byte) (int, error) { 258 | bc.total += int64(len(p)) 259 | if bc.startTime == 0 { 260 | bc.startTime = time.Now().Unix() 261 | } 262 | bc.endTime = time.Now().Unix() 263 | return len(p), nil 264 | } 265 | 266 | func (bc *ByteCounter) Write(p []byte) (int, error) { 267 | return bc.Read(p) 268 | } 269 | 270 | func (bc *ByteCounter) stringify(n float64) string { 271 | for i, prefix := range []string{"B", "KB", "MB", "GB"} { 272 | scale := 1 << (10 * i) 273 | if n < float64(scale<<10) { 274 | return fmt.Sprintf("%.2f %s", n/float64(scale), prefix) 275 | } 276 | } 277 | return fmt.Sprintf("%.2f TB", n/(1<<40)) 278 | } 279 | 280 | func (bc *ByteCounter) Total() string { 281 | return bc.stringify(float64(bc.total)) 282 | } 283 | 284 | func (bc *ByteCounter) Rate() string { 285 | elapsed := bc.endTime - bc.startTime 286 | if elapsed == 0 { 287 | return "0 B/s" 288 | } 289 | rate := float64(bc.total) / float64(elapsed) 290 | return bc.stringify(rate) + "/s" 291 | } 292 | -------------------------------------------------------------------------------- /internal/ui/elements_test.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "log" 5 | "testing" 6 | 7 | "fyne.io/fyne/v2" 8 | "fyne.io/fyne/v2/storage" 9 | "fyne.io/fyne/v2/test" 10 | ) 11 | 12 | func MakeURI(name string) fyne.URI { 13 | uri, err := storage.ParseURI("file://" + name) 14 | if err != nil { 15 | log.Println("Error creating URI:", err) 16 | panic(err) 17 | } 18 | return uri 19 | } 20 | 21 | type TestReadWriteCloser struct { 22 | bytesWritten int 23 | bytesRead int 24 | isClosed bool 25 | } 26 | 27 | func (t *TestReadWriteCloser) Read(p []byte) (n int, err error) { 28 | t.bytesRead += len(p) 29 | return len(p), nil 30 | } 31 | 32 | func (t *TestReadWriteCloser) Write(p []byte) (n int, err error) { 33 | t.bytesWritten += len(p) 34 | return len(p), nil 35 | } 36 | 37 | func (t *TestReadWriteCloser) Close() error { 38 | t.isClosed = true 39 | return nil 40 | } 41 | 42 | func (t *TestReadWriteCloser) URI() fyne.URI { 43 | return MakeURI("test") 44 | } 45 | 46 | func TestWriteLogsCallback(t *testing.T) { 47 | logger := Logger{} 48 | app := test.NewApp() 49 | window := app.NewWindow("Test Window") 50 | callback := writeLogsCallback(&logger, window) 51 | 52 | test := TestReadWriteCloser{} 53 | callback(&test, nil) 54 | if !test.isClosed { 55 | t.Errorf("Expected TestReadWriteCloser to be closed, but it was not.") 56 | } 57 | if test.bytesWritten == 0 { 58 | t.Errorf("Expected some bytes to be written, but none were.") 59 | } 60 | } 61 | 62 | func TestFilePickerCallback(t *testing.T) { 63 | logger := Logger{} 64 | app := test.NewApp() 65 | window := app.NewWindow("Test Window") 66 | state := NewState(app) 67 | callback := filePickerCallback(state, &logger, window) 68 | test := TestReadWriteCloser{} 69 | 70 | // Test canceling the file picker 71 | if state.Input() != nil { 72 | t.Errorf("State should not be initialized with an input") 73 | } 74 | callback(nil, nil) 75 | if state.Input() != nil { 76 | t.Errorf("State should not be updated with an input") 77 | } 78 | 79 | if state.Input() != nil { 80 | t.Errorf("State should not be initialized with an input") 81 | } 82 | callback(&test, nil) 83 | if !test.isClosed { 84 | t.Errorf("Resource must be closed") 85 | } 86 | if test.bytesRead != 0 { 87 | t.Errorf("Chosen file should not be read yet") 88 | } 89 | if state.Input() == nil { 90 | t.Errorf("State should be updated with an input") 91 | } 92 | } 93 | 94 | func TestFilename(t *testing.T) { 95 | state := NewState(test.NewApp()) 96 | if state.FileName.Text != "" { 97 | t.Errorf("Filename should be empty") 98 | } 99 | 100 | state.SetInput(MakeURI("test-filename")) 101 | if state.FileName.Text != "test-filename" { 102 | t.Errorf("Filname should match input") 103 | } 104 | 105 | state.SetInput(MakeURI("test-filename-2")) 106 | if state.FileName.Text != "test-filename-2" { 107 | t.Errorf("Filname should match input") 108 | } 109 | } 110 | 111 | func TestComments(t *testing.T) { 112 | state := NewState(test.NewApp()) 113 | 114 | state.SetInput(MakeURI("test")) 115 | if !state.IsEncrypting() { 116 | t.Errorf("State should be encrypting") 117 | } 118 | if state.Comments.Text != "" { 119 | t.Errorf("Comments should be empty") 120 | } 121 | if state.Comments.Disabled() { 122 | t.Errorf("Comments should be enabled") 123 | } 124 | if state.Comments.PlaceHolder != "Comments are not encrypted" { 125 | t.Errorf("Comments should warn user that they are not encrypted") 126 | } 127 | 128 | // Choosing deniability should disable comments 129 | state.Deniability.SetChecked(true) 130 | if state.Comments.Text != "" { 131 | t.Errorf("Comments should be empty") 132 | } 133 | if !state.Comments.Disabled() { 134 | t.Errorf("Comments should be disabled") 135 | } 136 | if state.Comments.PlaceHolder != "Comments are disabled in deniability mode" { 137 | t.Errorf("Comments should warn user that they are disabled") 138 | } 139 | if state.Comments.Text != "" { 140 | t.Errorf("State should be updated with comments") 141 | } 142 | 143 | // Switching to decrypting mode should disable comments 144 | err := state.SetInput(MakeURI("test.pcv")) 145 | if err != nil { 146 | t.Errorf("Error setting input: %v", err) 147 | } 148 | if !state.IsDecrypting() { 149 | t.Errorf("State should be decrypting") 150 | } 151 | if state.Comments.Text != "" { 152 | t.Errorf("Comments should be empty") 153 | } 154 | if !state.Comments.Disabled() { 155 | t.Errorf("Comments should be disabled") 156 | } 157 | } 158 | 159 | func TestKeyfileAddCallback(t *testing.T) { 160 | app := test.NewApp() 161 | window := app.NewWindow("Test Window") 162 | state := NewState(app) 163 | logger := Logger{} 164 | callback := keyfileAddCallback(state, &logger, window) 165 | 166 | callback(nil, nil) 167 | reader := TestReadWriteCloser{} 168 | callback(&reader, nil) 169 | if !reader.isClosed { 170 | t.Errorf("Expected TestReadWriteCloser to be closed, but it was not.") 171 | } 172 | if reader.bytesRead != 0 { 173 | t.Errorf("Keyfile should not be read yet") 174 | } 175 | if len(state.Keyfiles) != 1 { 176 | t.Errorf("Expected one keyfile to be added, but got %d", len(state.Keyfiles)) 177 | } 178 | } 179 | 180 | func TestKeyfileCreateCallback(t *testing.T) { 181 | state := NewState(test.NewApp()) 182 | app := test.NewApp() 183 | window := app.NewWindow("Test Window") 184 | logger := Logger{} 185 | callback := keyfileCreateCallback(state, &logger, window) 186 | 187 | callback(nil, nil) 188 | reader := TestReadWriteCloser{} 189 | callback(&reader, nil) 190 | if !reader.isClosed { 191 | t.Errorf("Expected TestReadWriteCloser to be closed, but it was not.") 192 | } 193 | if reader.bytesWritten != 32 { 194 | t.Errorf("Should have written 32 bytes, but wrote %d", reader.bytesWritten) 195 | } 196 | if len(state.Keyfiles) != 1 { 197 | t.Errorf("Expected one keyfile to be added, but got %d", len(state.Keyfiles)) 198 | } 199 | } 200 | 201 | func TestKeyfileClearCallback(t *testing.T) { 202 | state := NewState(test.NewApp()) 203 | logger := Logger{} 204 | callback := keyfileClearCallback(state, &logger) 205 | 206 | state.AddKeyfile(MakeURI("test-keyfile")) 207 | if len(state.Keyfiles) != 1 { 208 | t.Errorf("Expected one keyfile, but got %d", len(state.Keyfiles)) 209 | } 210 | callback() 211 | if len(state.Keyfiles) != 0 { 212 | t.Errorf("Expected no keyfiles, but got %d", len(state.Keyfiles)) 213 | } 214 | } 215 | 216 | func TestKeyfileTextUpdate(t *testing.T) { 217 | state := NewState(test.NewApp()) 218 | if state.KeyfileText.Text != "" { 219 | t.Errorf("Text should be empty") 220 | } 221 | 222 | state.AddKeyfile(MakeURI("test-keyfile-1")) 223 | state.AddKeyfile(MakeURI("test-keyfile-2")) 224 | if state.KeyfileText.Text != "test-keyfile-1\ntest-keyfile-2" { 225 | t.Errorf("Text should be updated to show keyfiles") 226 | } 227 | } 228 | 229 | func TestPasswordEntry(t *testing.T) { 230 | state := NewState(test.NewApp()) 231 | if state.Password.Text != "" { 232 | t.Errorf("Password should be empty") 233 | } 234 | 235 | // Test enabling / disabling 236 | state.SetInput(MakeURI("test.pcv")) 237 | if state.Password.Disabled() { 238 | t.Errorf("Password should be enabled") 239 | } 240 | state.SetInput(MakeURI("test")) 241 | if state.Password.Disabled() { 242 | t.Errorf("Password should be enabled") 243 | } 244 | } 245 | 246 | func TestConfirmEntry(t *testing.T) { 247 | state := NewState(test.NewApp()) 248 | if state.ConfirmPassword.Text != "" { 249 | t.Errorf("Confirm should be empty") 250 | } 251 | 252 | // Test enabling / disabling 253 | state.SetInput(MakeURI("test.pcv")) 254 | if !state.IsDecrypting() { 255 | t.Errorf("State should be decrypting") 256 | } 257 | if !state.ConfirmPassword.Disabled() { 258 | t.Errorf("Confirm should not be enabled for decrypting") 259 | } 260 | state.SetInput(MakeURI("test")) 261 | if !state.IsEncrypting() { 262 | t.Errorf("State should be encrypting") 263 | } 264 | if !state.ConfirmPassword.Visible() { 265 | t.Errorf("Confirm should be visible for encrypting") 266 | } 267 | } 268 | 269 | func TestWorkBtn(t *testing.T) { 270 | logger := Logger{} 271 | app := test.NewApp() 272 | window := app.NewWindow("Test Window") 273 | state := NewState(app) 274 | encryptCalled := false 275 | encrypt := func() { 276 | encryptCalled = true 277 | } 278 | decryptCalled := false 279 | decrypt := func() { 280 | decryptCalled = true 281 | } 282 | state.WorkBtn.OnTapped = WorkBtnCallback(state, &logger, window, encrypt, decrypt) 283 | 284 | // Set state to encrypting 285 | state.SetInput(MakeURI("test")) 286 | if state.WorkBtn.Disabled() { 287 | t.Errorf("Work button should be enabled") 288 | } 289 | if state.WorkBtn.Text != "Encrypt" { 290 | t.Errorf("Work button should say 'Encrypt'") 291 | } 292 | 293 | // Test mismatched passwords 294 | state.Password.Text = "test-password" 295 | state.ConfirmPassword.Text = "test-confirm" 296 | test.Tap(state.WorkBtn) 297 | if encryptCalled || decryptCalled { 298 | t.Errorf("Encrypt or decrypt should not be called") 299 | } 300 | 301 | // Match passwords 302 | state.ConfirmPassword.Text = "test-password" 303 | test.Tap(state.WorkBtn) 304 | if !encryptCalled || decryptCalled { 305 | t.Errorf("Only encrypt should be called") 306 | } 307 | 308 | // Set state to decrypting 309 | err := state.SetInput(MakeURI("test.pcv")) 310 | if err != nil { 311 | t.Errorf("Error setting input: %v", err) 312 | } 313 | if state.WorkBtn.Disabled() { 314 | t.Errorf("Work button should be visible") 315 | } 316 | if state.WorkBtn.Text != "Decrypt" { 317 | t.Errorf("Work button should say 'Decrypt'") 318 | } 319 | 320 | // Test decrypting 321 | encryptCalled = false 322 | decryptCalled = false 323 | test.Tap(state.WorkBtn) 324 | if encryptCalled || !decryptCalled { 325 | t.Errorf("Only decrypt should be called") 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /internal/ui/logger.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "strconv" 5 | "strings" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | func redactedFile(f *fileDesc) string { 11 | if f == nil { 12 | return "null" 13 | } 14 | redactedUri := "parsing-error-" + strconv.Itoa(f.id) 15 | splitIdx := strings.Index(f.uri, ":") 16 | if splitIdx != -1 { 17 | redactedUri = f.uri[:splitIdx+1] + "redacted-" + strconv.Itoa(f.id) 18 | } 19 | return "{\"Uri\":\"" + redactedUri + "\"}" 20 | } 21 | 22 | func redactedString(s string) string { 23 | if len(s) > 0 { 24 | return "non-empty-string" 25 | } 26 | return "" 27 | } 28 | 29 | func stateJson(state State) string { 30 | keyfiles := []string{} 31 | for _, k := range state.Keyfiles { 32 | keyfiles = append(keyfiles, redactedFile(&k)) 33 | } 34 | keyfilesJson := "[" + strings.Join(keyfiles, ",") + "]" 35 | fields := []string{ 36 | "\"Input\":" + redactedFile(state.Input()), 37 | "\"SaveAs\":" + redactedFile(state.SaveAs), 38 | "\"Comments\":\"" + redactedString(state.Comments.Text) + "\"", 39 | "\"ReedSolomon\":" + strconv.FormatBool(state.ReedSolomon.Checked), 40 | "\"Deniability\":" + strconv.FormatBool(state.Deniability.Checked), 41 | "\"Paranoid\":" + strconv.FormatBool(state.Paranoid.Checked), 42 | "\"Keyfiles\":" + keyfilesJson, 43 | } 44 | return "{" + strings.Join(fields, ",") + "}" 45 | } 46 | 47 | type logLine struct { 48 | time string 49 | action string 50 | state string 51 | err string 52 | } 53 | 54 | type Logger struct { 55 | lines []logLine 56 | mutex sync.Mutex 57 | } 58 | 59 | func (l *Logger) Log(action string, state State, err error) { 60 | errMsg := "" 61 | if err != nil { 62 | errMsg = err.Error() 63 | } 64 | line := logLine{ 65 | time: time.Now().Format("15:04:05.000"), 66 | action: action, 67 | state: stateJson(state), 68 | err: errMsg, 69 | } 70 | l.mutex.Lock() 71 | defer l.mutex.Unlock() 72 | l.lines = append(l.lines, line) 73 | } 74 | 75 | func (l *Logger) CsvString() string { 76 | logLines := []string{"Time,Action,State,Error," + PicoGoVersion} 77 | for _, line := range l.lines { 78 | fields := []string{ 79 | "\"" + line.time + "\"", 80 | "\"" + line.action + "\"", 81 | "\"" + line.state + "\"", 82 | "\"" + line.err + "\"", 83 | } 84 | logLines = append(logLines, strings.Join(fields, ",")) 85 | } 86 | return strings.Join(logLines, "\n") 87 | } 88 | -------------------------------------------------------------------------------- /internal/ui/state.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | "sync" 7 | 8 | "fyne.io/fyne/v2" 9 | "fyne.io/fyne/v2/storage" 10 | "fyne.io/fyne/v2/widget" 11 | 12 | "github.com/picocrypt/picogo/internal/encryption" 13 | ) 14 | 15 | const PicoGoVersion = "v0.1.5" 16 | 17 | var fileDescCount int 18 | var fileDescMutex sync.Mutex 19 | 20 | func nextFileDescID() int { 21 | fileDescMutex.Lock() 22 | defer fileDescMutex.Unlock() 23 | fileDescCount++ 24 | return fileDescCount 25 | } 26 | 27 | type fileDesc struct { 28 | name string 29 | uri string 30 | id int 31 | } 32 | 33 | func (f *fileDesc) Name() string { 34 | return f.name 35 | } 36 | 37 | func (f *fileDesc) Uri() string { 38 | return f.uri 39 | } 40 | 41 | func NewFileDesc(uri fyne.URI) fileDesc { 42 | return fileDesc{ 43 | name: uri.Name(), 44 | uri: uri.String(), 45 | id: nextFileDescID(), 46 | } 47 | } 48 | 49 | type Settings struct { 50 | ReedSolomonDefault *widget.Check 51 | ParanoidDefault *widget.Check 52 | OrderedKfDefault *widget.Check 53 | DeniabilityDefault *widget.Check 54 | } 55 | 56 | func (s *Settings) Save(app fyne.App) { 57 | preferences := app.Preferences() 58 | preferences.SetBool("ReedSolomonDefault", s.ReedSolomonDefault.Checked) 59 | preferences.SetBool("ParanoidDefault", s.ParanoidDefault.Checked) 60 | preferences.SetBool("OrderedKfDefault", s.OrderedKfDefault.Checked) 61 | preferences.SetBool("DeniabilityDefault", s.DeniabilityDefault.Checked) 62 | } 63 | 64 | func NewSettings(app fyne.App) *Settings { 65 | s := Settings{} 66 | s.ReedSolomonDefault = widget.NewCheck("Reed-Solomon", func(bool) { s.Save(app) }) 67 | s.ParanoidDefault = widget.NewCheck("Paranoid", func(bool) { s.Save(app) }) 68 | s.OrderedKfDefault = widget.NewCheck("Ordered Keyfiles", func(bool) { s.Save(app) }) 69 | s.DeniabilityDefault = widget.NewCheck("Deniability", func(bool) { s.Save(app) }) 70 | 71 | reedSolomon := app.Preferences().Bool("ReedSolomonDefault") 72 | orderedKf := app.Preferences().Bool("OrderedKfDefault") 73 | paranoid := app.Preferences().Bool("ParanoidDefault") 74 | deniability := app.Preferences().Bool("DeniabilityDefault") 75 | 76 | s.ReedSolomonDefault.SetChecked(reedSolomon) 77 | s.ParanoidDefault.SetChecked(paranoid) 78 | s.OrderedKfDefault.SetChecked(orderedKf) 79 | s.DeniabilityDefault.SetChecked(deniability) 80 | return &s 81 | } 82 | 83 | type State struct { 84 | FileName *widget.Label 85 | input *fileDesc 86 | SaveAs *fileDesc 87 | Comments *widget.Entry 88 | ReedSolomon *widget.Check 89 | Deniability *widget.Check 90 | Paranoid *widget.Check 91 | OrderedKeyfiles *widget.Check 92 | Keyfiles []fileDesc 93 | KeyfileText *widget.Entry 94 | Password *widget.Entry 95 | ConfirmPassword *widget.Entry 96 | WorkBtn *widget.Button 97 | Settings *Settings 98 | } 99 | 100 | func NewState(app fyne.App) *State { 101 | state := State{ 102 | FileName: widget.NewLabel(""), 103 | input: nil, 104 | SaveAs: nil, 105 | Comments: makeComments(), 106 | ReedSolomon: widget.NewCheck("Reed-Solomon", nil), 107 | Deniability: widget.NewCheck("Deniability", nil), 108 | Paranoid: widget.NewCheck("Paranoid", nil), 109 | OrderedKeyfiles: widget.NewCheck("Require correct order", nil), 110 | Keyfiles: []fileDesc{}, 111 | KeyfileText: keyfileText(), 112 | Password: makePassword(), 113 | ConfirmPassword: makeConfirmPassword(), 114 | WorkBtn: widget.NewButton("Encrypt", nil), 115 | Settings: NewSettings(app), 116 | } 117 | 118 | state.Deniability.OnChanged = func(checked bool) { state.updateComments() } 119 | 120 | state.ReedSolomon.SetChecked(state.Settings.ReedSolomonDefault.Checked) 121 | state.Paranoid.SetChecked(state.Settings.ParanoidDefault.Checked) 122 | state.OrderedKeyfiles.SetChecked(state.Settings.OrderedKfDefault.Checked) 123 | state.Deniability.SetChecked(state.Settings.DeniabilityDefault.Checked) 124 | 125 | return &state 126 | } 127 | 128 | func (s *State) updateComments() { 129 | if s.Deniability.Checked { 130 | s.Comments.SetText("") 131 | s.Comments.SetPlaceHolder("Comments are disabled in deniability mode") 132 | s.Comments.Disable() 133 | } else { 134 | s.Comments.SetPlaceHolder("Comments are not encrypted") 135 | s.Comments.Enable() 136 | } 137 | } 138 | 139 | func (s *State) Input() *fileDesc { 140 | return s.input 141 | } 142 | 143 | func (s *State) IsEncrypting() bool { 144 | if s.input == nil { 145 | return false 146 | } 147 | return !strings.HasSuffix(s.input.Name(), ".pcv") 148 | } 149 | 150 | func (s *State) IsDecrypting() bool { 151 | if s.input == nil { 152 | return false 153 | } 154 | return strings.HasSuffix(s.input.Name(), ".pcv") 155 | } 156 | 157 | func (s *State) SetInput(input fyne.URI) error { 158 | inputDesc := NewFileDesc(input) 159 | s.input = &inputDesc 160 | 161 | settings := encryption.Settings{ 162 | Comments: "", 163 | ReedSolomon: s.Settings.ReedSolomonDefault.Checked, 164 | Deniability: s.Settings.DeniabilityDefault.Checked, 165 | Paranoid: s.Settings.ParanoidDefault.Checked, 166 | } 167 | if s.IsDecrypting() { 168 | reader, err := storage.Reader(input) 169 | if reader != nil { 170 | defer reader.Close() 171 | } 172 | if err != nil { 173 | return fmt.Errorf("failed to open file: %w", err) 174 | } 175 | settings, err = encryption.GetEncryptionSettings(reader) 176 | if err != nil { 177 | return fmt.Errorf("failed to get encryption settings: %w", err) 178 | } 179 | } 180 | 181 | s.FileName.SetText(s.input.Name()) 182 | 183 | // Set Deniability before Comments to overwrite the result of the callback 184 | s.ReedSolomon.SetChecked(settings.ReedSolomon) 185 | s.Deniability.SetChecked(settings.Deniability) 186 | s.Paranoid.SetChecked(settings.Paranoid) 187 | if s.IsEncrypting() { 188 | s.ReedSolomon.Enable() 189 | s.Deniability.Enable() 190 | s.Paranoid.Enable() 191 | } else { 192 | s.ReedSolomon.Disable() 193 | s.Deniability.Disable() 194 | s.Paranoid.Disable() 195 | } 196 | 197 | s.Comments.SetText(settings.Comments) 198 | if s.IsEncrypting() { 199 | if settings.Deniability { 200 | s.Comments.SetText("") 201 | s.Comments.SetPlaceHolder("Comments are disabled in deniability mode") 202 | s.Comments.Disable() 203 | } else { 204 | s.Comments.SetPlaceHolder("Comments are not encrypted") 205 | s.Comments.Enable() 206 | } 207 | } else { 208 | s.Comments.SetPlaceHolder("") 209 | s.Comments.SetPlaceHolder("") 210 | s.Comments.Disable() 211 | } 212 | 213 | s.OrderedKeyfiles.Enable() 214 | 215 | if s.IsEncrypting() { 216 | s.ConfirmPassword.SetPlaceHolder("Confirm password") 217 | s.ConfirmPassword.Enable() 218 | } else { 219 | s.ConfirmPassword.SetPlaceHolder("Not required") 220 | s.ConfirmPassword.Disable() 221 | } 222 | 223 | if s.IsEncrypting() { 224 | s.WorkBtn.SetText("Encrypt") 225 | s.WorkBtn.Enable() 226 | } else { 227 | s.WorkBtn.SetText("Decrypt") 228 | s.WorkBtn.Enable() 229 | } 230 | 231 | return nil 232 | } 233 | 234 | func (s *State) AddKeyfile(uri fyne.URI) { 235 | s.Keyfiles = append(s.Keyfiles, NewFileDesc(uri)) 236 | names := []string{} 237 | for _, kf := range s.Keyfiles { 238 | names = append(names, kf.Name()) 239 | } 240 | msg := strings.Join(names, "\n") 241 | fyne.Do(func() { s.KeyfileText.SetText(msg) }) 242 | } 243 | 244 | func (s *State) ClearKeyfiles() { 245 | s.Keyfiles = []fileDesc{} 246 | fyne.Do(func() { s.KeyfileText.SetText("No keyfiles added") }) 247 | } 248 | 249 | func (s *State) Clear() { 250 | s.input = nil 251 | s.SaveAs = nil 252 | s.Keyfiles = nil 253 | fyne.DoAndWait(func() { 254 | s.FileName.SetText("") 255 | s.Comments.SetText("") 256 | s.ReedSolomon.SetChecked(s.Settings.ReedSolomonDefault.Checked) 257 | s.Deniability.SetChecked(s.Settings.DeniabilityDefault.Checked) 258 | s.Paranoid.SetChecked(s.Settings.ParanoidDefault.Checked) 259 | s.OrderedKeyfiles.SetChecked(s.Settings.OrderedKfDefault.Checked) 260 | s.Password.SetText("") 261 | s.ConfirmPassword.SetText("") 262 | }) 263 | } 264 | -------------------------------------------------------------------------------- /internal/ui/test.pcv: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Picocrypt/PicoGo/9b085ba5deeac01a33d6af9f2bfe1edef53fc109/internal/ui/test.pcv -------------------------------------------------------------------------------- /internal/ui/theme.go: -------------------------------------------------------------------------------- 1 | package ui 2 | 3 | import ( 4 | "image/color" 5 | 6 | "fyne.io/fyne/v2" 7 | "fyne.io/fyne/v2/theme" 8 | ) 9 | 10 | type Theme struct { 11 | Scale float32 12 | } 13 | 14 | func (t Theme) Color(name fyne.ThemeColorName, variant fyne.ThemeVariant) color.Color { 15 | switch name { 16 | case theme.ColorNameDisabled: 17 | return color.NRGBA{R: 0x80, G: 0x80, B: 0x80, A: 0xff} 18 | default: 19 | return theme.DarkTheme().Color(name, variant) 20 | } 21 | } 22 | func (t Theme) Font(style fyne.TextStyle) fyne.Resource { 23 | return theme.DarkTheme().Font(style) 24 | } 25 | func (t Theme) Icon(name fyne.ThemeIconName) fyne.Resource { 26 | return theme.DarkTheme().Icon(name) 27 | } 28 | func (t Theme) Size(name fyne.ThemeSizeName) float32 { 29 | return theme.DarkTheme().Size(name) * t.Scale 30 | } 31 | 32 | func NewTheme(scale float32) Theme { 33 | return Theme{Scale: scale} 34 | } 35 | -------------------------------------------------------------------------------- /picogo.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "image/color" 7 | "io" 8 | "strconv" 9 | "time" 10 | 11 | "fyne.io/fyne/v2" 12 | "fyne.io/fyne/v2/app" 13 | "fyne.io/fyne/v2/canvas" 14 | "fyne.io/fyne/v2/container" 15 | "fyne.io/fyne/v2/dialog" 16 | "fyne.io/fyne/v2/layout" 17 | "fyne.io/fyne/v2/storage" 18 | "fyne.io/fyne/v2/widget" 19 | 20 | "github.com/picocrypt/picogo/internal/encryption" 21 | "github.com/picocrypt/picogo/internal/ui" 22 | ) 23 | 24 | func uriReadCloser(uri string) (fyne.URIReadCloser, error) { 25 | fullUri, err := storage.ParseURI(uri) 26 | if err != nil { 27 | return nil, err 28 | } 29 | return storage.Reader(fullUri) 30 | } 31 | 32 | func uriWriteCloser(uri string) (fyne.URIWriteCloser, error) { 33 | fullUri, err := storage.ParseURI(uri) 34 | if err != nil { 35 | return nil, err 36 | } 37 | return storage.Writer(fullUri) 38 | } 39 | 40 | func clearFile(uri fyne.URI) error { 41 | writer, err := storage.Writer(uri) 42 | if writer != nil { 43 | defer writer.Close() 44 | } 45 | if err != nil { 46 | return err 47 | } 48 | _, err = writer.Write(make([]byte, 1)) 49 | return err 50 | } 51 | 52 | func getHeadlessURI(app fyne.App) (fyne.URI, error) { 53 | return storage.Child(app.Storage().RootURI(), "headless") 54 | } 55 | 56 | func clearHeadlessFile(app fyne.App) error { 57 | headlessURI, err := getHeadlessURI(app) 58 | if err != nil { 59 | return err 60 | } 61 | return clearFile(headlessURI) 62 | } 63 | 64 | func getOutputURI(app fyne.App) (fyne.URI, error) { 65 | return storage.Child(app.Storage().RootURI(), "output") 66 | } 67 | 68 | func clearOutputFile(app fyne.App) error { 69 | outputURI, err := getOutputURI(app) 70 | if err != nil { 71 | return err 72 | } 73 | return clearFile(outputURI) 74 | } 75 | 76 | func chooseSaveAs(logger *ui.Logger, state *ui.State, window fyne.Window, app fyne.App) { 77 | d := dialog.NewFileSave(func(writer fyne.URIWriteCloser, err error) { 78 | if writer != nil { 79 | defer writer.Close() 80 | } 81 | if err != nil { 82 | logger.Log("Failed while choosing where to save output", *state, err) 83 | dialog.ShowError(fmt.Errorf("choosing output file: %w", err), window) 84 | return 85 | } 86 | if writer != nil { 87 | saveAs := ui.NewFileDesc(writer.URI()) 88 | state.SaveAs = &saveAs 89 | logger.Log("Chose where to save output", *state, nil) 90 | go func() { 91 | saveOutput(logger, state, window, app) 92 | }() 93 | } else { 94 | logger.Log("Canceled choosing where to save output", *state, nil) 95 | } 96 | }, window) 97 | if input := state.Input(); input == nil { 98 | logger.Log("Failed to seed filename", *state, errors.New("input is nil")) 99 | } else { 100 | if state.IsEncrypting() { 101 | d.SetFileName(input.Name() + ".pcv") 102 | } else { 103 | d.SetFileName(input.Name()[:len(state.Input().Name())-4]) 104 | 105 | } 106 | } 107 | fyne.Do(d.Show) 108 | } 109 | 110 | func saveOutput(logger *ui.Logger, state *ui.State, window fyne.Window, app fyne.App) { 111 | defer func() { state.SaveAs = nil }() 112 | outputURI, err := getOutputURI(app) 113 | if err != nil { 114 | logger.Log("Get output uri", *state, err) 115 | dialog.ShowError(fmt.Errorf("finding output file: %w", err), window) 116 | return 117 | } 118 | output, err := storage.Reader(outputURI) 119 | if output != nil { 120 | defer output.Close() 121 | } 122 | if err != nil { 123 | logger.Log("Get output reader", *state, err) 124 | dialog.ShowError(fmt.Errorf("opening output file: %w", err), window) 125 | return 126 | } 127 | saveAs, err := uriWriteCloser(state.SaveAs.Uri()) 128 | if saveAs != nil { 129 | defer saveAs.Close() 130 | } 131 | if err != nil { 132 | logger.Log("Get save as writer", *state, err) 133 | dialog.ShowError(fmt.Errorf("opening save-as file: %w", err), window) 134 | return 135 | } 136 | errCh := make(chan error) 137 | counter := ui.ByteCounter{} 138 | go func() { 139 | _, err := io.Copy(io.MultiWriter(&counter, saveAs), output) 140 | errCh <- err 141 | }() 142 | 143 | progress := widget.NewLabel("") 144 | d := dialog.NewCustomWithoutButtons( 145 | "Saving", 146 | container.New(layout.NewVBoxLayout(), progress), 147 | window, 148 | ) 149 | fyne.Do(d.Show) 150 | 151 | // Block until completion 152 | for { 153 | select { 154 | case err := <-errCh: 155 | fyne.Do(d.Dismiss) 156 | if err != nil { 157 | logger.Log("Saving output", *state, err) 158 | dialog.ShowError(fmt.Errorf("copying output: %w", err), window) 159 | } 160 | err = clearOutputFile(app) 161 | if err != nil { 162 | logger.Log("Clearing output file", *state, err) 163 | dialog.ShowError(fmt.Errorf("cleaning tmp file: %w", err), window) 164 | } 165 | state.Clear() 166 | return 167 | default: 168 | time.Sleep(time.Second / 4) 169 | fyne.Do(func() { 170 | progress.SetText("Total: " + counter.Total() + "\nRate: " + counter.Rate()) 171 | }) 172 | } 173 | } 174 | } 175 | 176 | func encrypt(logger *ui.Logger, state *ui.State, win fyne.Window, app fyne.App) { 177 | errCh := make(chan error) 178 | counter := ui.ByteCounter{} 179 | 180 | go func() { 181 | logger.Log("Start encryption routine", *state, nil) 182 | headlessURI, err := getHeadlessURI(app) 183 | if err != nil { 184 | logger.Log("Get headless URI", *state, err) 185 | errCh <- err 186 | return 187 | } 188 | input, err := uriReadCloser(state.Input().Uri()) 189 | if input != nil { 190 | defer input.Close() 191 | } 192 | if err != nil { 193 | logger.Log("Get input reader", *state, err) 194 | errCh <- err 195 | return 196 | } 197 | 198 | headlessWriter, err := storage.Writer(headlessURI) 199 | if headlessWriter != nil { 200 | defer clearHeadlessFile(app) 201 | defer headlessWriter.Close() 202 | } 203 | if err != nil { 204 | logger.Log("Get headless writer", *state, err) 205 | errCh <- err 206 | return 207 | } 208 | 209 | keyfiles := []io.Reader{} 210 | for i := 0; i < len(state.Keyfiles); i++ { 211 | r, err := uriReadCloser(state.Keyfiles[i].Uri()) 212 | if r != nil { 213 | defer r.Close() 214 | } 215 | if err != nil { 216 | logger.Log("Get keyfile reader "+strconv.Itoa(i), *state, err) 217 | errCh <- err 218 | return 219 | } 220 | keyfiles = append(keyfiles, r) 221 | } 222 | settings := encryption.Settings{ 223 | Comments: state.Comments.Text, 224 | ReedSolomon: state.ReedSolomon.Checked, 225 | Paranoid: state.Paranoid.Checked, 226 | OrderedKf: state.OrderedKeyfiles.Checked, 227 | Deniability: state.Deniability.Checked, 228 | } 229 | header, err := encryption.EncryptHeadless( 230 | input, state.Password.Text, keyfiles, settings, io.MultiWriter(headlessWriter, &counter), 231 | ) 232 | if err != nil { 233 | logger.Log("Encrypt headless", *state, err) 234 | errCh <- err 235 | return 236 | } 237 | 238 | headlessReader, err := storage.Reader(headlessURI) 239 | if headlessReader != nil { 240 | defer headlessReader.Close() 241 | } 242 | if err != nil { 243 | logger.Log("Get headless reader", *state, err) 244 | errCh <- err 245 | return 246 | } 247 | 248 | outputURI, err := getOutputURI(app) 249 | if err != nil { 250 | logger.Log("Get output uri", *state, err) 251 | errCh <- err 252 | return 253 | } 254 | output, err := storage.Writer(outputURI) 255 | if output != nil { 256 | defer output.Close() 257 | } 258 | if err != nil { 259 | logger.Log("Get output writer", *state, err) 260 | errCh <- err 261 | return 262 | } 263 | 264 | err = encryption.PrependHeader(headlessReader, output, header) 265 | if err != nil { 266 | logger.Log("Prepend header", *state, err) 267 | } 268 | errCh <- err 269 | }() 270 | 271 | progress := widget.NewLabel("") 272 | d := dialog.NewCustomWithoutButtons("Encrypting", container.New(layout.NewVBoxLayout(), progress), win) 273 | fyne.Do(d.Show) 274 | var encryptErr error 275 | for { 276 | doBreak := false 277 | select { 278 | case err := <-errCh: 279 | fyne.Do(d.Dismiss) 280 | encryptErr = err 281 | doBreak = true 282 | default: 283 | time.Sleep(time.Second / 4) 284 | fyne.Do(func() { progress.SetText("Total: " + counter.Total() + "\nRate: " + counter.Rate()) }) 285 | } 286 | if doBreak { 287 | break 288 | } 289 | } 290 | logger.Log("Complete encryption", *state, encryptErr) 291 | if encryptErr != nil { 292 | dialog.ShowError(fmt.Errorf("encrypting: %w", encryptErr), win) 293 | return 294 | } 295 | text := widget.NewLabel(state.Input().Name() + " has been encrypted.") 296 | text.Wrapping = fyne.TextWrapWord 297 | fyne.Do(func() { 298 | dialog.ShowCustomConfirm( 299 | "Encryption Complete", 300 | "Save", 301 | "Cancel", 302 | text, 303 | func(b bool) { 304 | if b { 305 | chooseSaveAs(logger, state, win, app) 306 | } 307 | }, 308 | win, 309 | ) 310 | }) 311 | } 312 | 313 | func tryDecrypt( 314 | logger *ui.Logger, 315 | state *ui.State, 316 | recoveryMode bool, 317 | w fyne.Window, 318 | app fyne.App, 319 | ) (bool, error) { 320 | input, err := uriReadCloser(state.Input().Uri()) 321 | if err != nil { 322 | logger.Log("Get input reader", *state, err) 323 | return false, err 324 | } 325 | defer input.Close() 326 | 327 | keyfiles := []io.Reader{} 328 | for i := 0; i < len(state.Keyfiles); i++ { 329 | r, err := uriReadCloser(state.Keyfiles[i].Uri()) 330 | if err != nil { 331 | logger.Log("Get keyfile reader "+strconv.Itoa(i), *state, err) 332 | return false, err 333 | } 334 | defer r.Close() 335 | keyfiles = append(keyfiles, r) 336 | } 337 | 338 | outputURI, err := getOutputURI(app) 339 | if err != nil { 340 | logger.Log("Get output URI", *state, err) 341 | return false, err 342 | } 343 | output, err := uriWriteCloser(outputURI.String()) 344 | if err != nil { 345 | logger.Log("Get output writer", *state, err) 346 | return false, err 347 | } 348 | defer output.Close() 349 | 350 | errCh := make(chan struct { 351 | bool 352 | error 353 | }) 354 | counter := ui.ByteCounter{} 355 | go func() { 356 | logger.Log("Decryption routine start", *state, nil) 357 | damaged, err := encryption.Decrypt( 358 | state.Password.Text, 359 | keyfiles, 360 | input, 361 | io.MultiWriter(output, &counter), 362 | recoveryMode, 363 | ) 364 | errCh <- struct { 365 | bool 366 | error 367 | }{damaged, err} 368 | }() 369 | 370 | // Block until completion 371 | progress := widget.NewLabel("") 372 | d := dialog.NewCustomWithoutButtons("Decrypting", container.New(layout.NewVBoxLayout(), progress), w) 373 | fyne.Do(d.Show) 374 | for { 375 | select { 376 | case err := <-errCh: 377 | fyne.Do(d.Dismiss) 378 | logger.Log("Decryption routine end", *state, err.error) 379 | return err.bool, err.error 380 | default: 381 | time.Sleep(time.Second / 4) 382 | fyne.Do(func() { 383 | progress.SetText("Total: " + counter.Total() + "\nRate: " + counter.Rate()) 384 | }) 385 | } 386 | } 387 | } 388 | 389 | func decrypt(logger *ui.Logger, state *ui.State, win fyne.Window, app fyne.App) { 390 | damaged, err := tryDecrypt(logger, state, false, win, app) 391 | recoveryMode := false 392 | recoveryCanceled := false 393 | if errors.Is(err, encryption.ErrBodyCorrupted) { 394 | // Offer to try again in recovery mode 395 | text := widget.NewLabel("The file is damaged. Would you like to try again in recovery mode?") 396 | text.Wrapping = fyne.TextWrapWord 397 | doneCh := make(chan struct{}) 398 | dialog.ShowCustomConfirm( 399 | "Damaged File", 400 | "Recover", 401 | "Cancel", 402 | text, 403 | func(b bool) { 404 | if b { 405 | logger.Log("Retrying decryption in recovery mode", *state, nil) 406 | recoveryMode = true 407 | damaged, err = tryDecrypt(logger, state, true, win, app) 408 | } else { 409 | recoveryCanceled = true 410 | } 411 | doneCh <- struct{}{} 412 | }, 413 | win, 414 | ) 415 | <-doneCh 416 | } 417 | if recoveryCanceled { 418 | return 419 | } 420 | 421 | logger.Log("Handle decryption result (damaged:"+strconv.FormatBool(damaged)+")", *state, err) 422 | msg := "" 423 | save := false 424 | if err == nil && !damaged { 425 | msg = state.Input().Name() + " has been decrypted." 426 | save = true 427 | } else if err == nil && damaged { 428 | msg = state.Input().Name() + " has been decrypted successfully, but it is damaged. Consider re-encryting and replacing the damaged file." 429 | save = true 430 | } else { 431 | switch { 432 | case errors.Is(err, encryption.ErrBodyCorrupted): 433 | if recoveryMode { 434 | msg = "The file is too damaged to recover. Would you like to save the partially recovered file?" 435 | save = true 436 | } else { 437 | msg = "The file is too damaged to recover." 438 | save = false 439 | } 440 | case errors.Is(err, encryption.ErrIncorrectKeyfiles): 441 | msg = "One or more keyfiles are incorrect." 442 | save = false 443 | case errors.Is(err, encryption.ErrIncorrectPassword): 444 | msg = "The password is incorrect." 445 | save = false 446 | case errors.Is(err, encryption.ErrKeyfilesNotRequired): 447 | msg = "Keyfiles are not required to decrypt this file. Please remove them and try again." 448 | save = false 449 | case errors.Is(err, encryption.ErrKeyfilesRequired): 450 | msg = "Keyfiles are required to decrypt this file. Please add them and try again." 451 | save = false 452 | default: 453 | msg = "Error while decrypting: " + err.Error() 454 | } 455 | } 456 | if save { 457 | text := widget.NewLabel(msg) 458 | text.Wrapping = fyne.TextWrapWord 459 | dialog.ShowCustomConfirm( 460 | "Decryption Complete", 461 | "Save", 462 | "Cancel", 463 | text, 464 | func(b bool) { 465 | if b { 466 | chooseSaveAs(logger, state, win, app) 467 | } 468 | }, 469 | win, 470 | ) 471 | } else { 472 | dialog.ShowError(errors.New(msg), win) 473 | } 474 | } 475 | 476 | func wrapWithBorder(c fyne.CanvasObject) *fyne.Container { 477 | border := canvas.NewRectangle(color.White) 478 | border.FillColor = color.Transparent 479 | border.StrokeColor = color.White 480 | border.StrokeWidth = 1 481 | return container.New( 482 | layout.NewStackLayout(), 483 | border, 484 | container.NewPadded(c), 485 | ) 486 | } 487 | 488 | var developmentWarningShown = false 489 | 490 | func developmentWarning(win fyne.Window) { 491 | if !developmentWarningShown { 492 | dialog.ShowInformation( 493 | "Warning", 494 | "This app is in early development and has not been thoroughly tested", 495 | win, 496 | ) 497 | developmentWarningShown = true 498 | } 499 | } 500 | 501 | func main() { 502 | a := app.New() 503 | theme := ui.NewTheme(1.0) 504 | a.Settings().SetTheme(theme) 505 | w := a.NewWindow("PicoGo") 506 | state := ui.NewState(a) 507 | 508 | logger := ui.Logger{} 509 | logger.Log("Starting PicoGo", *state, nil) 510 | 511 | infoBtn := ui.MakeInfoBtn(w) 512 | logBtn := ui.MakeLogBtn(&logger, w) 513 | info_row := container.New( 514 | layout.NewHBoxLayout(), 515 | infoBtn, 516 | logBtn, 517 | ui.MakeSettingsBtn(state.Settings, w), 518 | layout.NewSpacer(), 519 | ) 520 | 521 | picker := ui.MakeFilePicker(state, &logger, w) 522 | fileRow := wrapWithBorder( 523 | container.New( 524 | layout.NewFormLayout(), 525 | widget.NewLabel("File"), container.NewPadded(container.NewPadded(state.FileName)), 526 | widget.NewLabel("Comments"), container.NewPadded(container.NewPadded(state.Comments)), 527 | ), 528 | ) 529 | 530 | // Advanced encryption settings 531 | advSettingsRow := wrapWithBorder( 532 | container.New( 533 | layout.NewVBoxLayout(), 534 | container.New( 535 | layout.NewVBoxLayout(), 536 | widget.NewRichTextFromMarkdown("### Settings"), 537 | container.New( 538 | layout.NewHBoxLayout(), 539 | state.ReedSolomon, 540 | state.Paranoid, 541 | state.Deniability, 542 | ), 543 | ), 544 | ), 545 | ) 546 | keyfiles := wrapWithBorder( 547 | container.New( 548 | layout.NewVBoxLayout(), 549 | widget.NewRichTextFromMarkdown("### Keyfiles"), 550 | container.NewPadded( 551 | container.NewBorder( 552 | nil, 553 | nil, 554 | container.New( 555 | layout.NewVBoxLayout(), 556 | ui.KeyfileAddBtn(state, &logger, w), 557 | ui.KeyfileCreateBtn(state, &logger, w), 558 | ui.KeyfileClearBtn(state, &logger), 559 | ), 560 | nil, 561 | container.NewPadded( 562 | container.New( 563 | layout.NewVBoxLayout(), 564 | state.OrderedKeyfiles, 565 | state.KeyfileText, 566 | ), 567 | ), 568 | ), 569 | ), 570 | ), 571 | ) 572 | 573 | passwordRow := wrapWithBorder( 574 | container.NewPadded(container.NewPadded( 575 | container.New( 576 | layout.NewVBoxLayout(), 577 | state.Password, 578 | state.ConfirmPassword, 579 | ), 580 | )), 581 | ) 582 | 583 | state.WorkBtn.OnTapped = ui.WorkBtnCallback( 584 | state, 585 | &logger, 586 | w, 587 | func() { go func() { encrypt(&logger, state, w, a) }() }, 588 | func() { go func() { decrypt(&logger, state, w, a) }() }, 589 | ) 590 | 591 | body := container.New( 592 | layout.NewVBoxLayout(), 593 | info_row, 594 | picker, 595 | fileRow, 596 | advSettingsRow, 597 | keyfiles, 598 | passwordRow, 599 | state.WorkBtn, 600 | ) 601 | minSize := body.MinSize() 602 | w.SetContent( 603 | container.New( 604 | layout.NewVBoxLayout(), 605 | body, 606 | ), 607 | ) 608 | 609 | go func() { 610 | for { 611 | // On android, users can change device settings that will scale the size 612 | // of the widgets. This can lead to parts of the app going off screen. 613 | // To work around this, continuously check the size of the window and scale 614 | // the theme to fit. 615 | // - continuous checking is required for desktop because the user may change 616 | // the window size. On android, the app is always full screen, so this should 617 | // only have effect the first loop. 618 | // - only update the theme if the scale is more than 1% different from the current 619 | // scale. This is to prevent constant updates to the theme. 620 | time.Sleep(time.Second / 10.0) 621 | currentSize := w.Canvas().Content().Size() 622 | targetScale := min(currentSize.Width/minSize.Width, currentSize.Height/minSize.Height) 623 | currentScale := theme.Scale 624 | if targetScale > currentScale*1.01 || targetScale < currentScale*0.99 { 625 | theme.Scale = targetScale 626 | fyne.Do(func() { a.Settings().SetTheme(theme) }) 627 | } 628 | } 629 | }() 630 | fyne.Do(func() { developmentWarning(w) }) 631 | w.ShowAndRun() 632 | } 633 | -------------------------------------------------------------------------------- /picogo_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "os" 7 | "testing" 8 | 9 | "github.com/picocrypt/picogo/internal/ui" 10 | ) 11 | 12 | func TestVersion(t *testing.T) { 13 | r, err := os.Open("VERSION") 14 | if err != nil { 15 | t.Fatal(err) 16 | } 17 | defer r.Close() 18 | version, err := io.ReadAll(r) 19 | if err != nil { 20 | t.Fatal(err) 21 | } 22 | if !bytes.Equal(version, []byte(ui.PicoGoVersion)) { 23 | t.Fatal(version, "does not match", []byte(ui.PicoGoVersion), "for version", ui.PicoGoVersion) 24 | } 25 | } 26 | --------------------------------------------------------------------------------