├── .github └── workflows │ └── test-and-build.yml ├── .golangci.yml ├── History.md ├── LICENSE ├── Makefile ├── README.md ├── examples_test.go ├── go.mod ├── go.sum ├── keys.go ├── keys_test.go ├── openssl.go ├── openssl_test.go ├── stream.go └── stream_test.go /.github/workflows/test-and-build.yml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | name: test-and-build 4 | on: 5 | push: 6 | branches: ['*'] 7 | tags: ['v*'] 8 | 9 | jobs: 10 | test-and-build: 11 | defaults: 12 | run: 13 | shell: bash 14 | 15 | container: 16 | image: luzifer/archlinux 17 | env: 18 | CGO_ENABLED: 0 19 | GOPATH: /go 20 | 21 | runs-on: ubuntu-latest 22 | 23 | steps: 24 | - name: Enable custom AUR package repo 25 | run: echo -e "[luzifer]\nSigLevel = Never\nServer = https://archrepo.hub.luzifer.io/\$arch" >>/etc/pacman.conf 26 | 27 | - name: Install required packages 28 | run: | 29 | pacman -Syy --noconfirm \ 30 | git \ 31 | go \ 32 | golangci-lint-bin \ 33 | make \ 34 | trivy 35 | 36 | - uses: actions/checkout@v3 37 | 38 | - name: Marking workdir safe 39 | run: git config --global --add safe.directory /__w/go-openssl/go-openssl 40 | 41 | - name: Lint and test code 42 | run: make lint test 43 | 44 | - name: Record benchmark 45 | run: make benchmark 46 | 47 | - name: Execute Trivy scan 48 | run: make trivy 49 | 50 | ... 51 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | # Derived from https://github.com/golangci/golangci-lint/blob/master/.golangci.example.yml 2 | 3 | --- 4 | 5 | run: 6 | # timeout for analysis, e.g. 30s, 5m, default is 1m 7 | timeout: 5m 8 | # Force readonly modules usage for checking 9 | modules-download-mode: readonly 10 | 11 | output: 12 | formats: 13 | - format: tab 14 | path: stdout 15 | 16 | issues: 17 | # This disables the included exclude-list in golangci-lint as that 18 | # list for example fully hides G304 gosec rule, errcheck, exported 19 | # rule of revive and other errors one really wants to see. 20 | # Smme detail: https://github.com/golangci/golangci-lint/issues/456 21 | exclude-use-default: false 22 | # Don't limit the number of shown issues: Report ALL of them 23 | max-issues-per-linter: 0 24 | max-same-issues: 0 25 | 26 | linters: 27 | disable-all: true 28 | enable: 29 | - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers [fast: true, auto-fix: false] 30 | - bidichk # Checks for dangerous unicode character sequences [fast: true, auto-fix: false] 31 | - bodyclose # checks whether HTTP response body is closed successfully [fast: true, auto-fix: false] 32 | - containedctx # containedctx is a linter that detects struct contained context.Context field [fast: true, auto-fix: false] 33 | - contextcheck # check the function whether use a non-inherited context [fast: false, auto-fix: false] 34 | - copyloopvar # copyloopvar is a linter detects places where loop variables are copied [fast: true, auto-fix: false] 35 | - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) [fast: true, auto-fix: false] 36 | - durationcheck # check for two durations multiplied together [fast: false, auto-fix: false] 37 | - errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases [fast: false, auto-fix: false] 38 | - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. [fast: false, auto-fix: false] 39 | - forbidigo # Forbids identifiers [fast: true, auto-fix: false] 40 | - funlen # Tool for detection of long functions [fast: true, auto-fix: false] 41 | - gocognit # Computes and checks the cognitive complexity of functions [fast: true, auto-fix: false] 42 | - goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false] 43 | - gocritic # The most opinionated Go source code linter [fast: true, auto-fix: false] 44 | - gocyclo # Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false] 45 | - godox # Tool for detection of FIXME, TODO and other comment keywords [fast: true, auto-fix: false] 46 | - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true] 47 | - gofumpt # Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true] 48 | - goimports # Goimports does everything that gofmt does. Additionally it checks unused imports [fast: true, auto-fix: true] 49 | - gosec # Inspects source code for security problems [fast: true, auto-fix: false] 50 | - gosimple # Linter for Go source code that specializes in simplifying a code [fast: true, auto-fix: false] 51 | - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: true, auto-fix: false] 52 | - ineffassign # Detects when assignments to existing variables are not used [fast: true, auto-fix: false] 53 | - misspell # Finds commonly misspelled English words in comments [fast: true, auto-fix: true] 54 | - mnd # An analyzer to detect magic numbers. [fast: true, auto-fix: false] 55 | - nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false] 56 | - nilerr # Finds the code that returns nil even if it checks that the error is not nil. [fast: false, auto-fix: false] 57 | - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false] 58 | - noctx # noctx finds sending http request without context.Context [fast: true, auto-fix: false] 59 | - nolintlint # Reports ill-formed or insufficient nolint directives [fast: true, auto-fix: false] 60 | - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false] 61 | - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks [fast: true, auto-fix: false] 62 | - stylecheck # Stylecheck is a replacement for golint [fast: true, auto-fix: false] 63 | - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 [fast: false, auto-fix: false] 64 | - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code [fast: true, auto-fix: false] 65 | - unconvert # Remove unnecessary type conversions [fast: true, auto-fix: false] 66 | - unused # Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false] 67 | - wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false] 68 | - wrapcheck # Checks that errors returned from external packages are wrapped [fast: false, auto-fix: false] 69 | 70 | linters-settings: 71 | funlen: 72 | lines: 100 73 | statements: 60 74 | 75 | gocyclo: 76 | # minimal code complexity to report, 30 by default (but we recommend 10-20) 77 | min-complexity: 15 78 | 79 | gomnd: 80 | ignored-functions: 'strconv.(?:Format|Parse)\B+' 81 | 82 | revive: 83 | rules: 84 | #- name: add-constant # Suggests using constant for magic numbers and string literals 85 | # Opinion: Makes sense for strings, not for numbers but checks numbers 86 | #- name: argument-limit # Specifies the maximum number of arguments a function can receive | Opinion: Don't need this 87 | - name: atomic # Check for common mistaken usages of the `sync/atomic` package 88 | - name: banned-characters # Checks banned characters in identifiers 89 | arguments: 90 | - ';' # Greek question mark 91 | - name: bare-return # Warns on bare returns 92 | - name: blank-imports # Disallows blank imports 93 | - name: bool-literal-in-expr # Suggests removing Boolean literals from logic expressions 94 | - name: call-to-gc # Warns on explicit call to the garbage collector 95 | #- name: cognitive-complexity # Sets restriction for maximum Cognitive complexity. 96 | # There is a dedicated linter for this 97 | - name: confusing-naming # Warns on methods with names that differ only by capitalization 98 | - name: confusing-results # Suggests to name potentially confusing function results 99 | - name: constant-logical-expr # Warns on constant logical expressions 100 | - name: context-as-argument # `context.Context` should be the first argument of a function. 101 | - name: context-keys-type # Disallows the usage of basic types in `context.WithValue`. 102 | #- name: cyclomatic # Sets restriction for maximum Cyclomatic complexity. 103 | # There is a dedicated linter for this 104 | #- name: datarace # Spots potential dataraces 105 | # Is not (yet) available? 106 | - name: deep-exit # Looks for program exits in funcs other than `main()` or `init()` 107 | - name: defer # Warns on some [defer gotchas](https://blog.learngoprogramming.com/5-gotchas-of-defer-in-go-golang-part-iii-36a1ab3d6ef1) 108 | - name: dot-imports # Forbids `.` imports. 109 | - name: duplicated-imports # Looks for packages that are imported two or more times 110 | - name: early-return # Spots if-then-else statements that can be refactored to simplify code reading 111 | - name: empty-block # Warns on empty code blocks 112 | - name: empty-lines # Warns when there are heading or trailing newlines in a block 113 | - name: errorf # Should replace `errors.New(fmt.Sprintf())` with `fmt.Errorf()` 114 | - name: error-naming # Naming of error variables. 115 | - name: error-return # The error return parameter should be last. 116 | - name: error-strings # Conventions around error strings. 117 | - name: exported # Naming and commenting conventions on exported symbols. 118 | arguments: ['sayRepetitiveInsteadOfStutters'] 119 | #- name: file-header # Header which each file should have. 120 | # Useless without config, have no config for it 121 | - name: flag-parameter # Warns on boolean parameters that create a control coupling 122 | #- name: function-length # Warns on functions exceeding the statements or lines max 123 | # There is a dedicated linter for this 124 | #- name: function-result-limit # Specifies the maximum number of results a function can return 125 | # Opinion: Don't need this 126 | - name: get-return # Warns on getters that do not yield any result 127 | - name: identical-branches # Spots if-then-else statements with identical `then` and `else` branches 128 | - name: if-return # Redundant if when returning an error. 129 | #- name: imports-blacklist # Disallows importing the specified packages 130 | # Useless without config, have no config for it 131 | - name: import-shadowing # Spots identifiers that shadow an import 132 | - name: increment-decrement # Use `i++` and `i--` instead of `i += 1` and `i -= 1`. 133 | - name: indent-error-flow # Prevents redundant else statements. 134 | #- name: line-length-limit # Specifies the maximum number of characters in a lined 135 | # There is a dedicated linter for this 136 | #- name: max-public-structs # The maximum number of public structs in a file. 137 | # Opinion: Don't need this 138 | - name: modifies-parameter # Warns on assignments to function parameters 139 | - name: modifies-value-receiver # Warns on assignments to value-passed method receivers 140 | #- name: nested-structs # Warns on structs within structs 141 | # Opinion: Don't need this 142 | - name: optimize-operands-order # Checks inefficient conditional expressions 143 | #- name: package-comments # Package commenting conventions. 144 | # Opinion: Don't need this 145 | - name: range # Prevents redundant variables when iterating over a collection. 146 | - name: range-val-address # Warns if address of range value is used dangerously 147 | - name: range-val-in-closure # Warns if range value is used in a closure dispatched as goroutine 148 | - name: receiver-naming # Conventions around the naming of receivers. 149 | - name: redefines-builtin-id # Warns on redefinitions of builtin identifiers 150 | #- name: string-format # Warns on specific string literals that fail one or more user-configured regular expressions 151 | # Useless without config, have no config for it 152 | - name: string-of-int # Warns on suspicious casts from int to string 153 | - name: struct-tag # Checks common struct tags like `json`,`xml`,`yaml` 154 | - name: superfluous-else # Prevents redundant else statements (extends indent-error-flow) 155 | - name: time-equal # Suggests to use `time.Time.Equal` instead of `==` and `!=` for equality check time. 156 | - name: time-naming # Conventions around the naming of time variables. 157 | - name: unconditional-recursion # Warns on function calls that will lead to (direct) infinite recursion 158 | - name: unexported-naming # Warns on wrongly named un-exported symbols 159 | - name: unexported-return # Warns when a public return is from unexported type. 160 | - name: unhandled-error # Warns on unhandled errors returned by funcion calls 161 | arguments: 162 | - "fmt.(Fp|P)rint(f|ln|)" 163 | - name: unnecessary-stmt # Suggests removing or simplifying unnecessary statements 164 | - name: unreachable-code # Warns on unreachable code 165 | - name: unused-parameter # Suggests to rename or remove unused function parameters 166 | - name: unused-receiver # Suggests to rename or remove unused method receivers 167 | #- name: use-any # Proposes to replace `interface{}` with its alias `any` 168 | # Is not (yet) available? 169 | - name: useless-break # Warns on useless `break` statements in case clauses 170 | - name: var-declaration # Reduces redundancies around variable declaration. 171 | - name: var-naming # Naming rules. 172 | - name: waitgroup-by-value # Warns on functions taking sync.WaitGroup as a by-value parameter 173 | 174 | ... 175 | -------------------------------------------------------------------------------- /History.md: -------------------------------------------------------------------------------- 1 | # 4.2.4 / 2024-12-12 2 | 3 | * Update linter config, increase supported Go version 4 | 5 | # 4.2.3 / 2024-12-12 6 | 7 | * Update `golang.org/x/crypto` 8 | 9 | # 4.2.2 / 2023-12-19 10 | 11 | * Update dependencies 12 | 13 | # 4.2.1 / 2023-09-11 14 | 15 | * Fix panic when reading incomplete blocks from underlying reader (#27) 16 | 17 | # 4.2.0 / 2023-08-22 18 | 19 | * Add support for stream writer and reader (#26) 20 | * [ci] Add automated code checks through Github Actions 21 | * [ci] Fix linter errors, simplify tests 22 | * [docs] Update documentation to use modules format 23 | 24 | # 4.1.0 / 2020-06-13 25 | 26 | * Add pre-defined generators and compatibility tests for SHA384 and SHA512 27 | 28 | # 4.0.0 / 2020-06-13 29 | 30 | * Breaking: Implement PBKFD2 key derivation (#18) 31 | 32 | # 3.1.0 / 2019-04-29 33 | 34 | * Add encrypt/decrypt without base64 encoding (thanks [@mcgillowen](https://github.com/mcgillowen)) 35 | * Test: Drop support for pre-1.10, add 1.12 36 | * Test: Simplify / cleanup test file 37 | 38 | # 3.0.1 / 2019-01-29 39 | 40 | * Fix: v3 versions require another go-modules name 41 | 42 | # 3.0.0 / 2018-11-02 43 | 44 | * Breaking: Fix race condition with guessing messagedigest 45 | 46 | # 2.0.2 / 2018-09-18 47 | 48 | * Fix: v2 versions require another go-modules name 49 | 50 | # 2.0.1 / 2018-09-18 51 | 52 | * Add modules file 53 | * Fix some linter warnings 54 | * Add benchmarks 55 | 56 | # 2.0.0 / 2018-09-11 57 | 58 | * Make digest function configurable on encrypt, add tests 59 | * message digest support sha1 and sha256 (thanks @yoozoo) 60 | 61 | # 1.2.0 / 2018-04-26 62 | 63 | * Add byte-operations, remove import path comment 64 | 65 | # 1.1.0 / 2017-09-18 66 | 67 | * Add salt validation and improve comments 68 | * Added ability to pass custom salt to everyencrypt call (thanks @VojtechBartos) 69 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2015- Knut Ahlers 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | default: 2 | 3 | benchmark: 4 | go test -bench=. ./... 5 | 6 | lint: 7 | golangci-lint run ./... 8 | 9 | test: 10 | go test -cover -v ./... 11 | 12 | # -- Vulnerability scanning -- 13 | 14 | trivy: 15 | trivy fs . \ 16 | --dependency-tree \ 17 | --exit-code 1 \ 18 | --format table \ 19 | --ignore-unfixed \ 20 | --quiet \ 21 | --scanners config,license,secret,vuln \ 22 | --severity HIGH,CRITICAL \ 23 | --skip-dirs docs 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![](https://badges.fyi/static/godoc/reference/5272B4)](https://pkg.go.dev/github.com/Luzifer/go-openssl/v4) 2 | [![Go Report Card](https://goreportcard.com/badge/github.com/Luzifer/go-openssl)](https://goreportcard.com/report/github.com/Luzifer/go-openssl) 3 | ![](https://badges.fyi/github/license/Luzifer/go-openssl) 4 | ![](https://badges.fyi/github/latest-tag/Luzifer/go-openssl) 5 | [![](https://travis-ci.org/Luzifer/go-openssl.svg?branch=master)](https://travis-ci.org/Luzifer/go-openssl) 6 | 7 | # Luzifer / go-openssl 8 | 9 | `go-openssl` is a small library wrapping the `crypto/aes` functions in a way the output is compatible to OpenSSL / CryptoJS. For all encryption / decryption processes AES256 is used so this library will not be able to decrypt messages generated with other than `openssl aes-256-cbc`. If you're using CryptoJS to process the data you also need to use AES256 on that side. 10 | 11 | ## Version support 12 | 13 | For this library only the latest major version is supported. All prior major versions should no longer be used. 14 | 15 | The versioning is following [SemVer](https://semver.org/) which means upgrading to a newer major version will break your code! 16 | 17 | ## OpenSSL compatibility 18 | 19 | ### 1.1.0c 20 | 21 | Starting with `v2.0.0` `go-openssl` generates the encryption keys using `sha256sum` algorithm. This is the default introduced in OpenSSL 1.1.0c. When encrypting data you can choose which digest method to use and therefore also continue to use `md5sum`. When decrypting OpenSSL encrypted data `md5sum`, `sha1sum` and `sha256sum` are supported. 22 | 23 | ### 1.1.1 24 | 25 | Starting with `v4.0.0` `go-openssl` is capable of using the PBKDF2 key derivation method for encryption. You can choose to use it by passing the corresponding `CredsGenerator`. 26 | 27 | ## Installation 28 | 29 | ```bash 30 | # Get the latest version 31 | go get github.com/Luzifer/go-openssl/v4 32 | ``` 33 | 34 | ## Usage example 35 | 36 | The usage is quite simple as you don't need any special knowledge about OpenSSL and/or AES256: 37 | 38 | ### Encrypt 39 | 40 | ```go 41 | import ( 42 | "fmt" 43 | openssl "github.com/Luzifer/go-openssl/v4" 44 | ) 45 | 46 | func main() { 47 | plaintext := "Hello World!" 48 | passphrase := "z4yH36a6zerhfE5427ZV" 49 | 50 | o := openssl.New() 51 | 52 | enc, err := o.EncryptBytes(passphrase, []byte(plaintext), PBKDF2SHA256) 53 | if err != nil { 54 | fmt.Printf("An error occurred: %s\n", err) 55 | } 56 | 57 | fmt.Printf("Encrypted text: %s\n", string(enc)) 58 | } 59 | ``` 60 | 61 | ### Decrypt 62 | 63 | ```go 64 | import ( 65 | "fmt" 66 | openssl "github.com/Luzifer/go-openssl/v4" 67 | ) 68 | 69 | func main() { 70 | opensslEncrypted := "U2FsdGVkX19ZM5qQJGe/d5A/4pccgH+arBGTp+QnWPU=" 71 | passphrase := "z4yH36a6zerhfE5427ZV" 72 | 73 | o := openssl.New() 74 | 75 | dec, err := o.DecryptBytes(passphrase, []byte(opensslEncrypted), BytesToKeyMD5) 76 | if err != nil { 77 | fmt.Printf("An error occurred: %s\n", err) 78 | } 79 | 80 | fmt.Printf("Decrypted text: %s\n", string(dec)) 81 | } 82 | ``` 83 | 84 | ## Testing 85 | 86 | To execute the tests for this library you need to be on a system having `/bin/bash` and `openssl` available as the compatibility of the output is tested directly against the `openssl` binary. The library itself should be usable on all operating systems supported by Go and `crypto/aes`. 87 | -------------------------------------------------------------------------------- /examples_test.go: -------------------------------------------------------------------------------- 1 | package openssl 2 | 3 | import "fmt" 4 | 5 | // #nosec G101 -- Contains harcoded test passphrase 6 | func ExampleOpenSSL_EncryptBytes() { 7 | plaintext := "Hello World!" 8 | passphrase := "z4yH36a6zerhfE5427ZV" 9 | 10 | o := New() 11 | 12 | enc, err := o.EncryptBytes(passphrase, []byte(plaintext), PBKDF2SHA256) 13 | if err != nil { 14 | fmt.Printf("An error occurred: %s\n", err) 15 | } 16 | 17 | fmt.Printf("Encrypted text: %s\n", string(enc)) 18 | } 19 | 20 | // #nosec G101 -- Contains harcoded test passphrase 21 | func ExampleOpenSSL_DecryptBytes() { 22 | opensslEncrypted := "U2FsdGVkX19ZM5qQJGe/d5A/4pccgH+arBGTp+QnWPU=" 23 | passphrase := "z4yH36a6zerhfE5427ZV" 24 | 25 | o := New() 26 | 27 | dec, err := o.DecryptBytes(passphrase, []byte(opensslEncrypted), BytesToKeyMD5) 28 | if err != nil { 29 | fmt.Printf("An error occurred: %s\n", err) 30 | } 31 | 32 | fmt.Printf("Decrypted text: %s\n", string(dec)) 33 | 34 | // Output: 35 | // Decrypted text: hallowelt 36 | } 37 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/Luzifer/go-openssl/v4 2 | 3 | go 1.22 4 | 5 | require ( 6 | github.com/stretchr/testify v1.8.4 7 | golang.org/x/crypto v0.31.0 8 | ) 9 | 10 | require ( 11 | github.com/davecgh/go-spew v1.1.1 // indirect 12 | github.com/pmezard/go-difflib v1.0.0 // indirect 13 | gopkg.in/yaml.v3 v3.0.1 // indirect 14 | ) 15 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= 6 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= 7 | golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= 8 | golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= 9 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 10 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 11 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 12 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 13 | -------------------------------------------------------------------------------- /keys.go: -------------------------------------------------------------------------------- 1 | package openssl 2 | 3 | import ( 4 | "crypto/md5" //#nosec G501 -- Used for OpenSSL compatibility in old KDF 5 | "crypto/sha1" //#nosec G505 -- Used for OpenSSL compatibility in old KDF 6 | "crypto/sha256" 7 | "crypto/sha512" 8 | "fmt" 9 | "hash" 10 | 11 | "golang.org/x/crypto/pbkdf2" 12 | ) 13 | 14 | // DefaultPBKDF2Iterations specifies the number of iterations to use 15 | // in PBKDF2 key generation. This is taken from the `openssl enc` 16 | // commands default. 17 | // 18 | // Taken from OpenSSL v3.1.2: 19 | // `openssl enc --help |& grep -A1 iter` 20 | const DefaultPBKDF2Iterations = 10000 21 | 22 | const ( 23 | opensslKeyLength = 32 24 | opensslIVLength = 16 25 | ) 26 | 27 | // CredsGenerator are functions to derive a key and iv from a password and a salt 28 | type CredsGenerator func(password, salt []byte) (Creds, error) 29 | 30 | var ( 31 | // BytesToKeyMD5 utilizes MD5 key-derivation (`-md md5`) 32 | BytesToKeyMD5 = NewBytesToKeyGenerator(md5.New) 33 | // BytesToKeySHA1 utilizes SHA1 key-derivation (`-md sha1`) 34 | BytesToKeySHA1 = NewBytesToKeyGenerator(sha1.New) 35 | // BytesToKeySHA256 utilizes SHA256 key-derivation (`-md sha256`) 36 | BytesToKeySHA256 = NewBytesToKeyGenerator(sha256.New) 37 | // BytesToKeySHA384 utilizes SHA384 key-derivation (`-md sha384`) 38 | BytesToKeySHA384 = NewBytesToKeyGenerator(sha512.New384) 39 | // BytesToKeySHA512 utilizes SHA512 key-derivation (`-md sha512`) 40 | BytesToKeySHA512 = NewBytesToKeyGenerator(sha512.New) 41 | // PBKDF2MD5 utilizes PBKDF2 key derivation with MD5 hashing (`-pbkdf2 -md md5`) 42 | PBKDF2MD5 = NewPBKDF2Generator(md5.New, DefaultPBKDF2Iterations) 43 | // PBKDF2SHA1 utilizes PBKDF2 key derivation with SHA1 hashing (`-pbkdf2 -md sha1`) 44 | PBKDF2SHA1 = NewPBKDF2Generator(sha1.New, DefaultPBKDF2Iterations) 45 | // PBKDF2SHA256 utilizes PBKDF2 key derivation with SHA256 hashing (`-pbkdf2 -md sha256`) 46 | PBKDF2SHA256 = NewPBKDF2Generator(sha256.New, DefaultPBKDF2Iterations) 47 | // PBKDF2SHA384 utilizes PBKDF2 key derivation with SHA384 hashing (`-pbkdf2 -md sha384`) 48 | PBKDF2SHA384 = NewPBKDF2Generator(sha512.New384, DefaultPBKDF2Iterations) 49 | // PBKDF2SHA512 utilizes PBKDF2 key derivation with SHA512 hashing (`-pbkdf2 -md sha512`) 50 | PBKDF2SHA512 = NewPBKDF2Generator(sha512.New, DefaultPBKDF2Iterations) 51 | ) 52 | 53 | // NewBytesToKeyGenerator implements the openSSLEvpBytesToKey key 54 | // derivation functions described in the OpenSSL code as follows: 55 | // 56 | // openSSLEvpBytesToKey follows the OpenSSL (undocumented?) convention for extracting the key and IV from passphrase. 57 | // It uses the EVP_BytesToKey() method which is basically: 58 | // D_i = HASH^count(D_(i-1) || password || salt) where || denotes concatentaion, until there are sufficient bytes available 59 | // 48 bytes since we're expecting to handle AES-256, 32bytes for a key and 16bytes for the IV 60 | func NewBytesToKeyGenerator(hashFunc func() hash.Hash) CredsGenerator { 61 | df := func(in []byte) []byte { 62 | h := hashFunc() 63 | if _, err := h.Write(in); err != nil { 64 | panic(fmt.Errorf("writing to hash: %w", err)) 65 | } 66 | return h.Sum(nil) 67 | } 68 | 69 | return func(password, salt []byte) (Creds, error) { 70 | var m []byte 71 | prev := []byte{} 72 | for len(m) < opensslKeyLength+opensslIVLength { 73 | a := make([]byte, len(prev)+len(password)+len(salt)) 74 | copy(a, prev) 75 | copy(a[len(prev):], password) 76 | copy(a[len(prev)+len(password):], salt) 77 | 78 | prev = df(a) 79 | m = append(m, prev...) 80 | } 81 | return Creds{Key: m[:opensslKeyLength], IV: m[opensslKeyLength : opensslKeyLength+opensslIVLength]}, nil 82 | } 83 | } 84 | 85 | // NewPBKDF2Generator implements a credential generator compatible 86 | // with the OpenSSL `-pbkdf2` parameter 87 | func NewPBKDF2Generator(hashFunc func() hash.Hash, iterations int) CredsGenerator { 88 | return func(password, salt []byte) (Creds, error) { 89 | m := pbkdf2.Key(password, salt, iterations, opensslKeyLength+opensslIVLength, hashFunc) 90 | return Creds{Key: m[:opensslKeyLength], IV: m[opensslKeyLength : opensslKeyLength+opensslIVLength]}, nil 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /keys_test.go: -------------------------------------------------------------------------------- 1 | package openssl 2 | 3 | import ( 4 | "crypto/sha256" 5 | "testing" 6 | ) 7 | 8 | func TestBytesToKeyGenerator(t *testing.T) { 9 | var ( 10 | pass = []byte("myverysecretpass") 11 | salt = []byte{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7} 12 | ) 13 | 14 | for name, tc := range map[string]struct { 15 | CG CredsGenerator 16 | OC Creds 17 | }{ 18 | "MD5": {CG: BytesToKeyMD5, OC: Creds{ 19 | // # echo "" | openssl enc -e -P -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md md5 20 | // salt=0001020304050607 21 | // key=7434342C270FA039438DA7B2898C6B3CA936DCE3D2705E805DA2987E5808CC06 22 | // iv =E20BB8B5CCBC1405705734ACCE1040A9 23 | Key: []uint8{0x74, 0x34, 0x34, 0x2C, 0x27, 0x0F, 0xA0, 0x39, 0x43, 0x8D, 0xA7, 0xB2, 0x89, 0x8C, 0x6B, 0x3C, 0xA9, 0x36, 0xDC, 0xE3, 0xD2, 0x70, 0x5E, 0x80, 0x5D, 0xA2, 0x98, 0x7E, 0x58, 0x08, 0xCC, 0x06}, 24 | IV: []uint8{0xE2, 0x0B, 0xB8, 0xB5, 0xCC, 0xBC, 0x14, 0x05, 0x70, 0x57, 0x34, 0xAC, 0xCE, 0x10, 0x40, 0xA9}, 25 | }}, 26 | "SHA1": {CG: BytesToKeySHA1, OC: Creds{ 27 | // # echo "" | openssl enc -e -P -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md sha1 28 | // salt=0001020304050607 29 | // key=186718DE0173029146A45CE44CD5D95224DDE0CC3DA63412B5BA41F4AB4B9927 30 | // iv =5AE1C3D9ACE659D309842CFF32A8D18B 31 | Key: []uint8{0x18, 0x67, 0x18, 0xDE, 0x01, 0x73, 0x02, 0x91, 0x46, 0xA4, 0x5C, 0xE4, 0x4C, 0xD5, 0xD9, 0x52, 0x24, 0xDD, 0xE0, 0xCC, 0x3D, 0xA6, 0x34, 0x12, 0xB5, 0xBA, 0x41, 0xF4, 0xAB, 0x4B, 0x99, 0x27}, 32 | IV: []uint8{0x5A, 0xE1, 0xC3, 0xD9, 0xAC, 0xE6, 0x59, 0xD3, 0x09, 0x84, 0x2C, 0xFF, 0x32, 0xA8, 0xD1, 0x8B}, 33 | }}, 34 | "SHA256": {CG: BytesToKeySHA256, OC: Creds{ 35 | // # echo "" | openssl enc -e -P -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md sha256 36 | // salt=0001020304050607 37 | // key=C309EE4C6809DF8C0137F80D8409DAC2C8C4E054349D17DDC1D6390C3999070B 38 | // iv =D3411C53B5C49FB339690EAC86D07107 39 | Key: []uint8{0xC3, 0x09, 0xEE, 0x4C, 0x68, 0x09, 0xDF, 0x8C, 0x01, 0x37, 0xF8, 0x0D, 0x84, 0x09, 0xDA, 0xC2, 0xC8, 0xC4, 0xE0, 0x54, 0x34, 0x9D, 0x17, 0xDD, 0xC1, 0xD6, 0x39, 0x0C, 0x39, 0x99, 0x07, 0x0B}, 40 | IV: []uint8{0xD3, 0x41, 0x1C, 0x53, 0xB5, 0xC4, 0x9F, 0xB3, 0x39, 0x69, 0x0E, 0xAC, 0x86, 0xD0, 0x71, 0x07}, 41 | }}, 42 | "SHA384": {CG: BytesToKeySHA384, OC: Creds{ 43 | // # echo "" | openssl enc -e -P -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md sha384 44 | // salt=0001020304050607 45 | // key=9BB4703E4EF60FCC812DBE757240219AE2370CC1DF9A685BAAC60CCA99B76222 46 | // iv =D64BDFF4A105BCEFEF28183B9722CDEC 47 | Key: []uint8{0x9B, 0xB4, 0x70, 0x3E, 0x4E, 0xF6, 0x0F, 0xCC, 0x81, 0x2D, 0xBE, 0x75, 0x72, 0x40, 0x21, 0x9A, 0xE2, 0x37, 0x0C, 0xC1, 0xDF, 0x9A, 0x68, 0x5B, 0xAA, 0xC6, 0x0C, 0xCA, 0x99, 0xB7, 0x62, 0x22}, 48 | IV: []uint8{0xD6, 0x4B, 0xDF, 0xF4, 0xA1, 0x05, 0xBC, 0xEF, 0xEF, 0x28, 0x18, 0x3B, 0x97, 0x22, 0xCD, 0xEC}, 49 | }}, 50 | "SHA512": {CG: BytesToKeySHA512, OC: Creds{ 51 | // # echo "" | openssl enc -e -P -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md sha512 52 | // salt=0001020304050607 53 | // key=735C94766AA35E84C1A314EB4505F177008B64F9853D1E10BF19C943313250D1 54 | // iv =304B88C772E582D8BBBBB3B3F535422C 55 | Key: []uint8{0x73, 0x5C, 0x94, 0x76, 0x6A, 0xA3, 0x5E, 0x84, 0xC1, 0xA3, 0x14, 0xEB, 0x45, 0x05, 0xF1, 0x77, 0x00, 0x8B, 0x64, 0xF9, 0x85, 0x3D, 0x1E, 0x10, 0xBF, 0x19, 0xC9, 0x43, 0x31, 0x32, 0x50, 0xD1}, 56 | IV: []uint8{0x30, 0x4B, 0x88, 0xC7, 0x72, 0xE5, 0x82, 0xD8, 0xBB, 0xBB, 0xB3, 0xB3, 0xF5, 0x35, 0x42, 0x2C}, 57 | }}, 58 | } { 59 | res, err := tc.CG(pass, salt) 60 | if err != nil { 61 | t.Fatalf("Generator %s caused an error: %s", name, err) 62 | } 63 | 64 | if !res.equals(tc.OC) { 65 | t.Errorf("Generator %s yielded unexpected result: exp=%#v res=%#v", name, tc.OC, res) 66 | } 67 | } 68 | } 69 | 70 | func TestPBKDF2Generator(t *testing.T) { 71 | var ( 72 | pass = []byte("myverysecretpass") 73 | salt = []byte{0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7} 74 | ) 75 | 76 | for name, tc := range map[string]struct { 77 | CG CredsGenerator 78 | OC Creds 79 | }{ 80 | "MD5": {CG: PBKDF2MD5, OC: Creds{ 81 | // # echo "" | openssl enc -e -P -pbkdf2 -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md md5 82 | // salt=0001020304050607 83 | // key=C5D1C98445902BD0515C105C25C88DA7243B79B2D67FE1CC978397BEDC526237 84 | // iv =F34AEAD261AAB8C16067D90A29275676 85 | Key: []uint8{0xC5, 0xD1, 0xC9, 0x84, 0x45, 0x90, 0x2B, 0xD0, 0x51, 0x5C, 0x10, 0x5C, 0x25, 0xC8, 0x8D, 0xA7, 0x24, 0x3B, 0x79, 0xB2, 0xD6, 0x7F, 0xE1, 0xCC, 0x97, 0x83, 0x97, 0xBE, 0xDC, 0x52, 0x62, 0x37}, 86 | IV: []uint8{0xF3, 0x4A, 0xEA, 0xD2, 0x61, 0xAA, 0xB8, 0xC1, 0x60, 0x67, 0xD9, 0x0A, 0x29, 0x27, 0x56, 0x76}, 87 | }}, 88 | "SHA1": {CG: PBKDF2SHA1, OC: Creds{ 89 | // # echo "" | openssl enc -e -P -pbkdf2 -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md sha1 90 | // salt=0001020304050607 91 | // key=EAE7B36DEAA01F34894722C1EBA856B5DB6FF5C34CFBDC8774B259DA9CB44837 92 | // iv =4496482B39B410D8B2AB582FB0993D7D 93 | Key: []uint8{0xEA, 0xE7, 0xB3, 0x6D, 0xEA, 0xA0, 0x1F, 0x34, 0x89, 0x47, 0x22, 0xC1, 0xEB, 0xA8, 0x56, 0xB5, 0xDB, 0x6F, 0xF5, 0xC3, 0x4C, 0xFB, 0xDC, 0x87, 0x74, 0xB2, 0x59, 0xDA, 0x9C, 0xB4, 0x48, 0x37}, 94 | IV: []uint8{0x44, 0x96, 0x48, 0x2B, 0x39, 0xB4, 0x10, 0xD8, 0xB2, 0xAB, 0x58, 0x2F, 0xB0, 0x99, 0x3D, 0x7D}, 95 | }}, 96 | "SHA256": {CG: PBKDF2SHA256, OC: Creds{ 97 | // # echo "" | openssl enc -e -P -pbkdf2 -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md sha256 98 | // salt=0001020304050607 99 | // key=A1B5D01BF7C1A1A0BF7659850C68ADD40E1CDF6B2D603EBD03673CED1C5AF032 100 | // iv =7DC52677DEF3D4B6D9A644209F42AE26 101 | Key: []uint8{0xA1, 0xB5, 0xD0, 0x1B, 0xF7, 0xC1, 0xA1, 0xA0, 0xBF, 0x76, 0x59, 0x85, 0x0C, 0x68, 0xAD, 0xD4, 0x0E, 0x1C, 0xDF, 0x6B, 0x2D, 0x60, 0x3E, 0xBD, 0x03, 0x67, 0x3C, 0xED, 0x1C, 0x5A, 0xF0, 0x32}, 102 | IV: []uint8{0x7D, 0xC5, 0x26, 0x77, 0xDE, 0xF3, 0xD4, 0xB6, 0xD9, 0xA6, 0x44, 0x20, 0x9F, 0x42, 0xAE, 0x26}, 103 | }}, 104 | "SHA256_25k": {CG: NewPBKDF2Generator(sha256.New, 25000), OC: Creds{ 105 | // # echo "" | openssl enc -e -P -pbkdf2 -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md sha256 -iter 25000 106 | // salt=0001020304050607 107 | // key=2D6C8A525CC457FF1C7CA1E8F366FEE441CD80562AF6AD12A6B7033C12BA0514 108 | // iv =F10F5FAE49D9A74C104BFF8346DDEB0C 109 | Key: []uint8{0x2D, 0x6C, 0x8A, 0x52, 0x5C, 0xC4, 0x57, 0xFF, 0x1C, 0x7C, 0xA1, 0xE8, 0xF3, 0x66, 0xFE, 0xE4, 0x41, 0xCD, 0x80, 0x56, 0x2A, 0xF6, 0xAD, 0x12, 0xA6, 0xB7, 0x03, 0x3C, 0x12, 0xBA, 0x05, 0x14}, 110 | IV: []uint8{0xF1, 0x0F, 0x5F, 0xAE, 0x49, 0xD9, 0xA7, 0x4C, 0x10, 0x4B, 0xFF, 0x83, 0x46, 0xDD, 0xEB, 0x0C}, 111 | }}, 112 | "SHA384": {CG: PBKDF2SHA384, OC: Creds{ 113 | // # echo "" | openssl enc -e -P -pbkdf2 -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md sha384 114 | // salt=0001020304050607 115 | // key=E73AA9008F7D33BBCBBFBCD3D69FE18802AD7807453BEF43761E2B3E88224132 116 | // iv =1A7171E9FFE4F69B56077C5C823DAD92 117 | Key: []uint8{0xE7, 0x3A, 0xA9, 0x00, 0x8F, 0x7D, 0x33, 0xBB, 0xCB, 0xBF, 0xBC, 0xD3, 0xD6, 0x9F, 0xE1, 0x88, 0x02, 0xAD, 0x78, 0x07, 0x45, 0x3B, 0xEF, 0x43, 0x76, 0x1E, 0x2B, 0x3E, 0x88, 0x22, 0x41, 0x32}, 118 | IV: []uint8{0x1A, 0x71, 0x71, 0xE9, 0xFF, 0xE4, 0xF6, 0x9B, 0x56, 0x07, 0x7C, 0x5C, 0x82, 0x3D, 0xAD, 0x92}, 119 | }}, 120 | "SHA512": {CG: PBKDF2SHA512, OC: Creds{ 121 | // # echo "" | openssl enc -e -P -pbkdf2 -aes-256-cbc -pass "pass:myverysecretpass" -S 0001020304050607 -md sha512 122 | // salt=0001020304050607 123 | // key=84D09D95F052EA32F0570817C0034D70392A966B319986539E97797841D65009 124 | // iv =63254E32D530B2ECC13EF88E7CF3CD17 125 | Key: []uint8{0x84, 0xD0, 0x9D, 0x95, 0xF0, 0x52, 0xEA, 0x32, 0xF0, 0x57, 0x08, 0x17, 0xC0, 0x03, 0x4D, 0x70, 0x39, 0x2A, 0x96, 0x6B, 0x31, 0x99, 0x86, 0x53, 0x9E, 0x97, 0x79, 0x78, 0x41, 0xD6, 0x50, 0x09}, 126 | IV: []uint8{0x63, 0x25, 0x4E, 0x32, 0xD5, 0x30, 0xB2, 0xEC, 0xC1, 0x3E, 0xF8, 0x8E, 0x7C, 0xF3, 0xCD, 0x17}, 127 | }}, 128 | } { 129 | res, err := tc.CG(pass, salt) 130 | if err != nil { 131 | t.Fatalf("Generator %s caused an error: %s", name, err) 132 | } 133 | 134 | if !res.equals(tc.OC) { 135 | t.Errorf("Generator %s yielded unexpected result: exp=%#v res=%#v", name, tc.OC, res) 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /openssl.go: -------------------------------------------------------------------------------- 1 | // Package openssl contains a pure Go implementation of an OpenSSL 2 | // compatible encryption / decryption 3 | package openssl 4 | 5 | import ( 6 | "bytes" 7 | "crypto/aes" 8 | "crypto/cipher" 9 | "crypto/rand" 10 | "encoding/base64" 11 | "errors" 12 | "fmt" 13 | "io" 14 | ) 15 | 16 | const ( 17 | opensslSaltHeader = "Salted__" // OpenSSL salt is always this string + 8 bytes of actual salt 18 | opensslSaltLength = 8 19 | ) 20 | 21 | // ErrInvalidSalt is returned when a salt with a length of != 8 byte is passed 22 | var ErrInvalidSalt = errors.New("salt needs to have exactly 8 byte") 23 | 24 | // OpenSSL is a helper to generate OpenSSL compatible encryption 25 | // with autmatic IV derivation and storage. As long as the key is known all 26 | // data can also get decrypted using OpenSSL CLI. 27 | // Code from http://dequeue.blogspot.de/2014/11/decrypting-something-encrypted-with.html 28 | type OpenSSL struct { 29 | openSSLSaltHeader string 30 | } 31 | 32 | // Creds holds a key and an IV for encryption methods 33 | type Creds struct { 34 | Key []byte 35 | IV []byte 36 | } 37 | 38 | func (o Creds) equals(i Creds) bool { 39 | // If lengths does not match no chance they are equal 40 | if len(o.Key) != len(i.Key) || len(o.IV) != len(i.IV) { 41 | return false 42 | } 43 | 44 | // Compare keys 45 | for j := 0; j < len(o.Key); j++ { 46 | if o.Key[j] != i.Key[j] { 47 | return false 48 | } 49 | } 50 | 51 | // Compare IV 52 | for j := 0; j < len(o.IV); j++ { 53 | if o.IV[j] != i.IV[j] { 54 | return false 55 | } 56 | } 57 | 58 | return true 59 | } 60 | 61 | // New instanciates and initializes a new OpenSSL encrypter 62 | func New() *OpenSSL { 63 | return &OpenSSL{ 64 | openSSLSaltHeader: opensslSaltHeader, 65 | } 66 | } 67 | 68 | // DecryptBytes takes a slice of bytes with base64 encoded, encrypted data to decrypt 69 | // and a key-derivation function. The key-derivation function must match the function 70 | // used to encrypt the data. (In OpenSSL the value of the `-md` parameter.) 71 | // 72 | // You should not just try to loop the digest functions as this will cause a race 73 | // condition and you will not be able to decrypt your data properly. 74 | func (o OpenSSL) DecryptBytes(passphrase string, encryptedBase64Data []byte, cg CredsGenerator) ([]byte, error) { 75 | data := make([]byte, base64.StdEncoding.DecodedLen(len(encryptedBase64Data))) 76 | n, err := base64.StdEncoding.Decode(data, encryptedBase64Data) 77 | if err != nil { 78 | return nil, fmt.Errorf("decoding data: %w", err) 79 | } 80 | 81 | // Truncate to real message length 82 | data = data[0:n] 83 | 84 | decrypted, err := o.DecryptBinaryBytes(passphrase, data, cg) 85 | if err != nil { 86 | return nil, err 87 | } 88 | return decrypted, nil 89 | } 90 | 91 | // DecryptBinaryBytes takes a slice of binary bytes, encrypted data to decrypt 92 | // and a key-derivation function. The key-derivation function must match the function 93 | // used to encrypt the data. (In OpenSSL the value of the `-md` parameter.) 94 | // 95 | // You should not just try to loop the digest functions as this will cause a race 96 | // condition and you will not be able to decrypt your data properly. 97 | func (o OpenSSL) DecryptBinaryBytes(passphrase string, encryptedData []byte, cg CredsGenerator) ([]byte, error) { 98 | if len(encryptedData) < aes.BlockSize { 99 | return nil, fmt.Errorf("data too short") 100 | } 101 | saltHeader := encryptedData[:aes.BlockSize] 102 | if string(saltHeader[:8]) != o.openSSLSaltHeader { 103 | return nil, fmt.Errorf("does not appear to have been encrypted with OpenSSL, salt header missing") 104 | } 105 | salt := saltHeader[8:] 106 | 107 | creds, err := cg([]byte(passphrase), salt) 108 | if err != nil { 109 | return nil, err 110 | } 111 | return o.decrypt(creds.Key, creds.IV, encryptedData) 112 | } 113 | 114 | func (o OpenSSL) decrypt(key, iv, data []byte) ([]byte, error) { 115 | if len(data) == 0 || len(data)%aes.BlockSize != 0 { 116 | return nil, fmt.Errorf("bad blocksize(%v), aes.BlockSize = %v", len(data), aes.BlockSize) 117 | } 118 | c, err := aes.NewCipher(key) 119 | if err != nil { 120 | return nil, fmt.Errorf("creating AES cipher: %w", err) 121 | } 122 | cbc := cipher.NewCBCDecrypter(c, iv) 123 | cbc.CryptBlocks(data[aes.BlockSize:], data[aes.BlockSize:]) 124 | out, err := o.pkcs7Unpad(data[aes.BlockSize:], aes.BlockSize) 125 | if out == nil { 126 | return nil, err 127 | } 128 | return out, nil 129 | } 130 | 131 | // EncryptBytes encrypts a slice of bytes that are base64 encoded in a manner compatible to OpenSSL encryption 132 | // functions using AES-256-CBC as encryption algorithm. This function generates 133 | // a random salt on every execution. 134 | func (o OpenSSL) EncryptBytes(passphrase string, plainData []byte, cg CredsGenerator) ([]byte, error) { 135 | salt, err := o.GenerateSalt() 136 | if err != nil { 137 | return nil, err 138 | } 139 | 140 | return o.EncryptBytesWithSaltAndDigestFunc(passphrase, salt, plainData, cg) 141 | } 142 | 143 | // EncryptBinaryBytes encrypts a slice of bytes in a manner compatible to OpenSSL encryption 144 | // functions using AES-256-CBC as encryption algorithm. This function generates 145 | // a random salt on every execution. 146 | func (o OpenSSL) EncryptBinaryBytes(passphrase string, plainData []byte, cg CredsGenerator) ([]byte, error) { 147 | salt, err := o.GenerateSalt() 148 | if err != nil { 149 | return nil, err 150 | } 151 | 152 | return o.EncryptBinaryBytesWithSaltAndDigestFunc(passphrase, salt, plainData, cg) 153 | } 154 | 155 | // EncryptBytesWithSaltAndDigestFunc encrypts a slice of bytes that are base64 encoded in a manner compatible to OpenSSL 156 | // encryption functions using AES-256-CBC as encryption algorithm. The salt 157 | // needs to be passed in here which ensures the same result on every execution 158 | // on cost of a much weaker encryption as with EncryptString. 159 | // 160 | // The salt passed into this function needs to have exactly 8 byte. 161 | // 162 | // The hash function corresponds to the `-md` parameter of OpenSSL. For OpenSSL pre-1.1.0c 163 | // DigestMD5Sum was the default, since then it is DigestSHA256Sum. 164 | // 165 | // If you don't have a good reason to use this, please don't! For more information 166 | // see this: https://en.wikipedia.org/wiki/Salt_(cryptography)#Common_mistakes 167 | func (o OpenSSL) EncryptBytesWithSaltAndDigestFunc(passphrase string, salt, plainData []byte, cg CredsGenerator) ([]byte, error) { 168 | enc, err := o.EncryptBinaryBytesWithSaltAndDigestFunc(passphrase, salt, plainData, cg) 169 | if err != nil { 170 | return nil, err 171 | } 172 | 173 | return []byte(base64.StdEncoding.EncodeToString(enc)), nil 174 | } 175 | 176 | func (o OpenSSL) encrypt(key, iv, data []byte) ([]byte, error) { 177 | padded, err := o.pkcs7Pad(data, aes.BlockSize) 178 | if err != nil { 179 | return nil, err 180 | } 181 | 182 | c, err := aes.NewCipher(key) 183 | if err != nil { 184 | return nil, fmt.Errorf("creating AES cipher: %w", err) 185 | } 186 | cbc := cipher.NewCBCEncrypter(c, iv) 187 | cbc.CryptBlocks(padded[aes.BlockSize:], padded[aes.BlockSize:]) 188 | 189 | return padded, nil 190 | } 191 | 192 | // EncryptBinaryBytesWithSaltAndDigestFunc encrypts a slice of bytes in a manner compatible to OpenSSL 193 | // encryption functions using AES-256-CBC as encryption algorithm. The salt 194 | // needs to be passed in here which ensures the same result on every execution 195 | // on cost of a much weaker encryption as with EncryptString. 196 | // 197 | // The salt passed into this function needs to have exactly 8 byte. 198 | // 199 | // The hash function corresponds to the `-md` parameter of OpenSSL. For OpenSSL pre-1.1.0c 200 | // DigestMD5Sum was the default, since then it is DigestSHA256Sum. 201 | // 202 | // If you don't have a good reason to use this, please don't! For more information 203 | // see this: https://en.wikipedia.org/wiki/Salt_(cryptography)#Common_mistakes 204 | func (o OpenSSL) EncryptBinaryBytesWithSaltAndDigestFunc(passphrase string, salt, plainData []byte, cg CredsGenerator) ([]byte, error) { 205 | if len(salt) != opensslSaltLength { 206 | return nil, ErrInvalidSalt 207 | } 208 | 209 | data := make([]byte, len(plainData)+aes.BlockSize) 210 | copy(data[0:], o.openSSLSaltHeader) 211 | copy(data[len(o.openSSLSaltHeader):], salt) 212 | copy(data[aes.BlockSize:], plainData) 213 | 214 | creds, err := cg([]byte(passphrase), salt) 215 | if err != nil { 216 | return nil, err 217 | } 218 | 219 | enc, err := o.encrypt(creds.Key, creds.IV, data) 220 | if err != nil { 221 | return nil, err 222 | } 223 | 224 | return enc, nil 225 | } 226 | 227 | // GenerateSalt generates a random 8 byte salt 228 | func (OpenSSL) GenerateSalt() ([]byte, error) { 229 | salt := make([]byte, opensslSaltLength) // Generate an 8 byte salt 230 | _, err := io.ReadFull(rand.Reader, salt) 231 | if err != nil { 232 | return nil, fmt.Errorf("reading random salt: %w", err) 233 | } 234 | 235 | return salt, nil 236 | } 237 | 238 | // MustGenerateSalt is a wrapper around GenerateSalt which will panic on an error. 239 | // This allows you to use this function as a parameter to EncryptBytesWithSaltAndDigestFunc 240 | func (o OpenSSL) MustGenerateSalt() []byte { 241 | s, err := o.GenerateSalt() 242 | if err != nil { 243 | panic(err) 244 | } 245 | return s 246 | } 247 | 248 | // pkcs7Pad appends padding. 249 | func (OpenSSL) pkcs7Pad(data []byte, blocklen int) ([]byte, error) { 250 | if blocklen <= 0 { 251 | return nil, fmt.Errorf("invalid blocklen %d", blocklen) 252 | } 253 | padlen := 1 254 | for ((len(data) + padlen) % blocklen) != 0 { 255 | padlen++ 256 | } 257 | 258 | pad := bytes.Repeat([]byte{byte(padlen)}, padlen) 259 | return append(data, pad...), nil 260 | } 261 | 262 | // pkcs7Unpad returns slice of the original data without padding. 263 | func (OpenSSL) pkcs7Unpad(data []byte, blocklen int) ([]byte, error) { 264 | if blocklen <= 0 { 265 | return nil, fmt.Errorf("invalid blocklen %d", blocklen) 266 | } 267 | if len(data)%blocklen != 0 || len(data) == 0 { 268 | return nil, fmt.Errorf("invalid data len %d", len(data)) 269 | } 270 | padlen := int(data[len(data)-1]) 271 | if padlen > blocklen || padlen == 0 { 272 | return nil, fmt.Errorf("invalid padding") 273 | } 274 | pad := data[len(data)-padlen:] 275 | for i := 0; i < padlen; i++ { 276 | if pad[i] != byte(padlen) { 277 | return nil, fmt.Errorf("invalid padding") 278 | } 279 | } 280 | return data[:len(data)-padlen], nil 281 | } 282 | -------------------------------------------------------------------------------- /openssl_test.go: -------------------------------------------------------------------------------- 1 | package openssl 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "os/exec" 7 | "strings" 8 | "testing" 9 | 10 | "github.com/stretchr/testify/assert" 11 | "github.com/stretchr/testify/require" 12 | ) 13 | 14 | const ( 15 | testPassphrase = "z4yH36a6zerhfE5427ZV" //#nosec G101 -- Is hardcoded passphrase but only for testing purposes 16 | testPlaintext = "hallowelt" 17 | ) 18 | 19 | var testTable = []struct { 20 | tName string 21 | tMdParam string 22 | tMdFunc CredsGenerator 23 | tPBKDF bool 24 | }{ 25 | {"MD5", "md5", BytesToKeyMD5, false}, 26 | {"SHA1", "sha1", BytesToKeySHA1, false}, 27 | {"SHA256", "sha256", BytesToKeySHA256, false}, 28 | {"SHA384", "sha384", BytesToKeySHA384, false}, 29 | {"SHA512", "sha512", BytesToKeySHA512, false}, 30 | {"PBKDF2_MD5", "md5", PBKDF2MD5, true}, 31 | {"PBKDF2_SHA1", "sha1", PBKDF2SHA1, true}, 32 | {"PBKDF2_SHA256", "sha256", PBKDF2SHA256, true}, 33 | {"PBKDF2_SHA384", "sha384", PBKDF2SHA384, true}, 34 | {"PBKDF2_SHA512", "sha512", PBKDF2SHA512, true}, 35 | } 36 | 37 | func TestBinaryEncryptToDecryptWithCustomSalt(t *testing.T) { 38 | salt := []byte("saltsalt") 39 | 40 | o := New() 41 | 42 | enc, err := o.EncryptBinaryBytesWithSaltAndDigestFunc(testPassphrase, salt, []byte(testPlaintext), BytesToKeySHA256) 43 | require.NoError(t, err) 44 | 45 | dec, err := o.DecryptBinaryBytes(testPassphrase, enc, BytesToKeySHA256) 46 | require.NoError(t, err) 47 | 48 | assert.Equal(t, testPlaintext, string(dec)) 49 | } 50 | 51 | func TestBinaryEncryptToDecrypt(t *testing.T) { 52 | o := New() 53 | 54 | enc, err := o.EncryptBinaryBytes(testPassphrase, []byte(testPlaintext), BytesToKeySHA256) 55 | require.NoError(t, err) 56 | 57 | dec, err := o.DecryptBinaryBytes(testPassphrase, enc, BytesToKeySHA256) 58 | require.NoError(t, err) 59 | 60 | assert.Equal(t, testPlaintext, string(dec)) 61 | } 62 | 63 | func TestBinaryEncryptToOpenSSL(t *testing.T) { 64 | o := New() 65 | 66 | for _, tc := range testTable { 67 | t.Run(tc.tName, func(t *testing.T) { 68 | salt, err := o.GenerateSalt() 69 | require.NoError(t, err) 70 | 71 | enc, err := o.EncryptBinaryBytesWithSaltAndDigestFunc(testPassphrase, salt, []byte(testPlaintext), tc.tMdFunc) 72 | require.NoError(t, err) 73 | 74 | // Need to specify /dev/stdin as file so that we can pass in binary 75 | // data to openssl without creating a file 76 | cmdArgs := []string{ 77 | "openssl", "aes-256-cbc", 78 | "-d", 79 | "-pass", fmt.Sprintf("pass:%s", testPassphrase), 80 | "-md", tc.tMdParam, 81 | "-in", "/dev/stdin", 82 | } 83 | 84 | if tc.tPBKDF { 85 | cmdArgs = append(cmdArgs, "-pbkdf2") 86 | } 87 | 88 | cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) //#nosec:G204 -- Hardcoded tests, this is fine 89 | 90 | var out bytes.Buffer 91 | cmd.Stdout = &out 92 | cmd.Stdin = bytes.NewBuffer(enc) 93 | 94 | err = cmd.Run() 95 | require.NoError(t, err) 96 | 97 | assert.Equal(t, testPlaintext, out.String()) 98 | }) 99 | } 100 | } 101 | 102 | func TestBinaryEncryptWithSaltShouldHaveSameOutput(t *testing.T) { 103 | plaintext := "outputshouldbesame" 104 | passphrase := "passphrasesupersecure" 105 | salt := []byte("saltsalt") 106 | 107 | o := New() 108 | 109 | enc1, err := o.EncryptBinaryBytesWithSaltAndDigestFunc(passphrase, salt, []byte(plaintext), BytesToKeySHA256) 110 | require.NoError(t, err) 111 | 112 | enc2, err := o.EncryptBinaryBytesWithSaltAndDigestFunc(passphrase, salt, []byte(plaintext), BytesToKeySHA256) 113 | require.NoError(t, err) 114 | 115 | assert.Equal(t, enc1, enc2) 116 | } 117 | 118 | func TestDecryptBinaryFromString(t *testing.T) { 119 | o := New() 120 | 121 | for _, tc := range testTable { 122 | t.Run(tc.tName, func(t *testing.T) { 123 | var out bytes.Buffer 124 | 125 | cmdArgs := []string{ 126 | "openssl", "aes-256-cbc", 127 | "-pass", fmt.Sprintf("pass:%s", testPassphrase), 128 | "-md", tc.tMdParam, 129 | "-in", "/dev/stdin", 130 | } 131 | 132 | if tc.tPBKDF { 133 | cmdArgs = append(cmdArgs, "-pbkdf2") 134 | } 135 | 136 | cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) //#nosec:G204 -- Hardcoded tests, this is fine 137 | cmd.Stdout = &out 138 | cmd.Stdin = strings.NewReader(testPlaintext) 139 | 140 | require.NoError(t, cmd.Run()) 141 | 142 | data, err := o.DecryptBinaryBytes(testPassphrase, out.Bytes(), tc.tMdFunc) 143 | require.NoError(t, err) 144 | 145 | if !assert.Equal(t, testPlaintext, string(data)) { 146 | t.Logf("Data: %s\nPlaintext: %s", string(data), testPlaintext) 147 | } 148 | }) 149 | } 150 | } 151 | 152 | func TestDecryptFromString(t *testing.T) { 153 | o := New() 154 | 155 | for _, tc := range testTable { 156 | t.Run(tc.tName, func(t *testing.T) { 157 | var out bytes.Buffer 158 | 159 | cmdArgs := []string{ 160 | "openssl", "aes-256-cbc", 161 | "-base64", 162 | "-pass", fmt.Sprintf("pass:%s", testPassphrase), 163 | "-md", tc.tMdParam, 164 | } 165 | 166 | if tc.tPBKDF { 167 | cmdArgs = append(cmdArgs, "-pbkdf2") 168 | } 169 | 170 | cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) //#nosec:G204 -- Hardcoded tests, this is fine 171 | cmd.Stdout = &out 172 | cmd.Stdin = strings.NewReader(testPlaintext) 173 | 174 | require.NoError(t, cmd.Run()) 175 | 176 | data, err := o.DecryptBytes(testPassphrase, out.Bytes(), tc.tMdFunc) 177 | require.NoError(t, err) 178 | 179 | if !assert.Equal(t, testPlaintext, string(data)) { 180 | t.Logf("Data: %s\nPlaintext: %s", string(data), testPlaintext) 181 | } 182 | }) 183 | } 184 | } 185 | 186 | func TestEncryptToDecrypt(t *testing.T) { 187 | o := New() 188 | 189 | enc, err := o.EncryptBytes(testPassphrase, []byte(testPlaintext), BytesToKeySHA256) 190 | require.NoError(t, err) 191 | 192 | dec, err := o.DecryptBytes(testPassphrase, enc, BytesToKeySHA256) 193 | require.NoError(t, err) 194 | 195 | assert.Equal(t, testPlaintext, string(dec)) 196 | } 197 | 198 | func TestEncryptToDecryptWithCustomSalt(t *testing.T) { 199 | salt := []byte("saltsalt") 200 | 201 | o := New() 202 | 203 | enc, err := o.EncryptBytesWithSaltAndDigestFunc(testPassphrase, salt, []byte(testPlaintext), BytesToKeySHA256) 204 | require.NoError(t, err) 205 | 206 | dec, err := o.DecryptBytes(testPassphrase, enc, BytesToKeySHA256) 207 | require.NoError(t, err) 208 | 209 | assert.Equal(t, testPlaintext, string(dec)) 210 | } 211 | 212 | func TestEncryptToOpenSSL(t *testing.T) { 213 | for _, tc := range testTable { 214 | t.Run(tc.tName, func(t *testing.T) { 215 | o := New() 216 | 217 | salt, err := o.GenerateSalt() 218 | require.NoError(t, err) 219 | 220 | enc, err := o.EncryptBytesWithSaltAndDigestFunc(testPassphrase, salt, []byte(testPlaintext), tc.tMdFunc) 221 | require.NoError(t, err) 222 | 223 | enc = append(enc, '\n') 224 | 225 | var out bytes.Buffer 226 | 227 | cmdArgs := []string{ 228 | "openssl", "aes-256-cbc", 229 | "-base64", "-d", 230 | "-pass", fmt.Sprintf("pass:%s", testPassphrase), 231 | "-md", tc.tMdParam, 232 | "-in", "/dev/stdin", 233 | } 234 | 235 | if tc.tPBKDF { 236 | cmdArgs = append(cmdArgs, "-pbkdf2") 237 | } 238 | 239 | cmd := exec.Command(cmdArgs[0], cmdArgs[1:]...) //#nosec:G204 -- Hardcoded tests, this is fine 240 | cmd.Stdout = &out 241 | cmd.Stdin = bytes.NewReader(enc) 242 | 243 | require.NoError(t, cmd.Run()) 244 | 245 | assert.Equal(t, testPlaintext, out.String()) 246 | }) 247 | } 248 | } 249 | 250 | func TestEncryptWithSaltShouldHaveSameOutput(t *testing.T) { 251 | plaintext := "outputshouldbesame" 252 | passphrase := "passphrasesupersecure" 253 | salt := []byte("saltsalt") 254 | 255 | o := New() 256 | 257 | enc1, err := o.EncryptBytesWithSaltAndDigestFunc(passphrase, salt, []byte(plaintext), BytesToKeySHA256) 258 | require.NoError(t, err) 259 | 260 | enc2, err := o.EncryptBytesWithSaltAndDigestFunc(passphrase, salt, []byte(plaintext), BytesToKeySHA256) 261 | require.NoError(t, err) 262 | 263 | assert.Equal(t, enc1, enc2) 264 | } 265 | 266 | func TestGenerateSalt(t *testing.T) { 267 | knownSalts := [][]byte{} 268 | 269 | o := New() 270 | 271 | for i := 0; i < 1000; i++ { 272 | salt, err := o.GenerateSalt() 273 | require.NoError(t, err) 274 | 275 | for _, ks := range knownSalts { 276 | assert.NotEqual(t, ks, salt) 277 | knownSalts = append(knownSalts, salt) 278 | } 279 | } 280 | } 281 | 282 | func TestSaltValidation(t *testing.T) { 283 | var err error 284 | o := New() 285 | 286 | _, err = o.EncryptBytesWithSaltAndDigestFunc(testPassphrase, []byte("12345"), []byte(testPlaintext), BytesToKeySHA256) 287 | assert.ErrorIs(t, err, ErrInvalidSalt) 288 | 289 | _, err = o.EncryptBytesWithSaltAndDigestFunc(testPassphrase, []byte("1234567890"), []byte(testPlaintext), BytesToKeySHA256) 290 | assert.ErrorIs(t, err, ErrInvalidSalt) 291 | 292 | _, err = o.EncryptBytesWithSaltAndDigestFunc(testPassphrase, []byte{0xcb, 0xd5, 0x1a, 0x3, 0x84, 0xba, 0xa8, 0xc8}, []byte(testPlaintext), BytesToKeySHA256) 293 | assert.NoError(t, err) 294 | } 295 | 296 | // 297 | // Benchmarks 298 | // 299 | 300 | func benchmarkDecrypt(ciphertext []byte, cg CredsGenerator, b *testing.B) { 301 | o := New() 302 | 303 | for n := 0; n < b.N; n++ { 304 | _, err := o.DecryptBytes(testPassphrase, ciphertext, cg) 305 | require.NoError(b, err) 306 | } 307 | } 308 | 309 | func BenchmarkDecryptMD5(b *testing.B) { 310 | benchmarkDecrypt([]byte("U2FsdGVkX19ZM5qQJGe/d5A/4pccgH+arBGTp+QnWPU="), BytesToKeyMD5, b) 311 | } 312 | 313 | func BenchmarkDecryptSHA1(b *testing.B) { 314 | benchmarkDecrypt([]byte("U2FsdGVkX1/Yy9kegseq2Ewd4UvjFYCpIEA1cltTA1Q="), BytesToKeySHA1, b) 315 | } 316 | 317 | func BenchmarkDecryptSHA256(b *testing.B) { 318 | benchmarkDecrypt([]byte("U2FsdGVkX1+O68d7BO9ibP8nB5+xtb/27IHlyjJWpl8="), BytesToKeySHA256, b) 319 | } 320 | 321 | func benchmarkEncrypt(plaintext string, cg CredsGenerator, b *testing.B) { 322 | o := New() 323 | salt, _ := o.GenerateSalt() 324 | 325 | for n := 0; n < b.N; n++ { 326 | _, err := o.EncryptBytesWithSaltAndDigestFunc(testPassphrase, salt, []byte(plaintext), cg) 327 | require.NoError(b, err) 328 | } 329 | } 330 | 331 | func BenchmarkEncryptMD5(b *testing.B) { 332 | benchmarkEncrypt(testPlaintext, BytesToKeyMD5, b) 333 | } 334 | 335 | func BenchmarkEncryptSHA1(b *testing.B) { 336 | benchmarkEncrypt(testPlaintext, BytesToKeySHA1, b) 337 | } 338 | 339 | func BenchmarkEncryptSHA256(b *testing.B) { 340 | benchmarkEncrypt(testPlaintext, BytesToKeySHA256, b) 341 | } 342 | 343 | func BenchmarkGenerateSalt(b *testing.B) { 344 | o := New() 345 | for n := 0; n < b.N; n++ { 346 | _, err := o.GenerateSalt() 347 | require.NoError(b, err) 348 | } 349 | } 350 | -------------------------------------------------------------------------------- /stream.go: -------------------------------------------------------------------------------- 1 | package openssl 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "crypto/aes" 7 | "crypto/cipher" 8 | "crypto/rand" 9 | "errors" 10 | "fmt" 11 | "io" 12 | ) 13 | 14 | // DecryptReader represents an io.Reader for OpenSSL encrypted data 15 | type DecryptReader struct { 16 | r *bufio.Reader 17 | mode cipher.BlockMode 18 | cg CredsGenerator 19 | passphrase []byte 20 | 21 | buf bytes.Buffer 22 | } 23 | 24 | // NewReader creates a new OpenSSL stream reader with underlying reader, 25 | // passphrase and CredsGenerator 26 | func NewReader(r io.Reader, passphrase string, cg CredsGenerator) *DecryptReader { 27 | return &DecryptReader{ 28 | r: bufio.NewReader(r), 29 | cg: cg, 30 | passphrase: []byte(passphrase), 31 | } 32 | } 33 | 34 | // Read implements the io.Reader interface to read from an encrypted 35 | // datastream 36 | func (d *DecryptReader) Read(b []byte) (int, error) { 37 | if d.mode == nil { 38 | if err := d.initMode(); err != nil { 39 | return 0, fmt.Errorf("initializing mode: %w", err) 40 | } 41 | } 42 | 43 | n, err := d.r.Read(b) 44 | if err != nil && !errors.Is(err, io.EOF) { 45 | return n, fmt.Errorf("reading from underlying reader: %w", err) 46 | } 47 | 48 | // write original data to buffer first 49 | if _, err := d.buf.Write(b[:n]); err != nil { 50 | return 0, fmt.Errorf("writing bytes to buffer: %w", err) 51 | } 52 | 53 | realSize := len(b) 54 | if d.buf.Len() < realSize { 55 | realSize = d.buf.Len() 56 | } 57 | 58 | size := (realSize / aes.BlockSize) * aes.BlockSize 59 | 60 | if size == 0 { 61 | return 0, nil 62 | } 63 | 64 | // read encrypted data from buffer 65 | if _, err := io.ReadFull(&d.buf, b[:size]); err != nil { 66 | return size, fmt.Errorf("reading from underlying reader: %w", err) 67 | } 68 | 69 | d.mode.CryptBlocks(b[:size], b[:size]) 70 | 71 | // AS OpenSSL enforces the encrypted data to have a length of a 72 | // multiple of the AES BlockSize we will always read full blocks. 73 | // Therefore we can check whether the next block exists or yields 74 | // an io.EOF error. If it does we need to remove the PKCS7 padding. 75 | if _, err := d.r.Peek(aes.BlockSize); errors.Is(err, io.EOF) { 76 | if _, err := io.Copy(&d.buf, d.r); err != nil { 77 | return size, fmt.Errorf("copying remaining data to buffer: %w", err) 78 | } 79 | 80 | if d.buf.Len() == 0 { 81 | size -= int(b[size-1]) 82 | if size < 0 { 83 | return 0, fmt.Errorf("incorrect padding size: %d", size) 84 | } 85 | return size, io.EOF 86 | } 87 | 88 | if d.buf.Len()%aes.BlockSize != 0 { 89 | return size, fmt.Errorf("incorrect encrypted data size: %d", d.buf.Len()) 90 | } 91 | } 92 | 93 | return size, nil 94 | } 95 | 96 | func (d *DecryptReader) initMode() error { 97 | if d.mode != nil { 98 | return nil 99 | } 100 | 101 | saltHeader := make([]byte, aes.BlockSize) 102 | if _, err := io.ReadFull(d.r, saltHeader); err != nil { 103 | return fmt.Errorf("reading salt header: %w", err) 104 | } 105 | 106 | if string(saltHeader[:8]) != opensslSaltHeader { 107 | return fmt.Errorf("missing OpenSSL salt-header") 108 | } 109 | 110 | salt := saltHeader[8:] 111 | 112 | creds, err := d.cg(d.passphrase, salt) 113 | if err != nil { 114 | return err 115 | } 116 | 117 | c, err := aes.NewCipher(creds.Key) 118 | if err != nil { 119 | return fmt.Errorf("creating new AES cipher: %w", err) 120 | } 121 | d.mode = cipher.NewCBCDecrypter(c, creds.IV) 122 | return nil 123 | } 124 | 125 | // EncryptWriter represents an io.WriteCloser info OpenSSL encrypted data 126 | type EncryptWriter struct { 127 | mode cipher.BlockMode 128 | w io.Writer 129 | cg CredsGenerator 130 | passphrase []byte 131 | buf []byte 132 | } 133 | 134 | // NewWriter create new openssl stream writer with underlying writer, 135 | // passphrase and CredsGenerator. 136 | // 137 | // Make sure close the writer after writing all data, to ensure the 138 | // remaining data is padded and written to the underlying writer. 139 | func NewWriter(w io.Writer, passphrase string, cg CredsGenerator) *EncryptWriter { 140 | return &EncryptWriter{ 141 | w: w, 142 | cg: cg, 143 | passphrase: []byte(passphrase), 144 | } 145 | } 146 | 147 | // Write implements io.WriteCloser to write encrypted data into the 148 | // underlying writer. The Write call may keep data in the buffer and 149 | // needs to flush them through the Close function. 150 | func (e *EncryptWriter) Write(b []byte) (int, error) { 151 | if e.mode == nil { 152 | if err := e.initMode(); err != nil { 153 | return 0, err 154 | } 155 | } 156 | 157 | originSize := len(b) 158 | 159 | buf := bytes.NewBuffer(nil) 160 | 161 | if e.buf != nil { 162 | if _, err := buf.Write(e.buf); err != nil { 163 | return 0, fmt.Errorf("writing remaining data to buffer: %w", err) 164 | } 165 | e.buf = nil 166 | } 167 | 168 | if _, err := buf.Write(b); err != nil { 169 | return 0, fmt.Errorf("writing current data to buffer: %w", err) 170 | } 171 | 172 | size := (buf.Len() / aes.BlockSize) * aes.BlockSize 173 | 174 | if remain := buf.Len() - size; remain > 0 { 175 | e.buf = buf.Bytes()[size:] 176 | } 177 | 178 | if size == 0 { 179 | return originSize, nil 180 | } 181 | 182 | e.mode.CryptBlocks(buf.Bytes()[:size], buf.Bytes()[:size]) 183 | 184 | n, err := e.w.Write(buf.Bytes()[:size]) 185 | if err != nil { 186 | return n, fmt.Errorf("writing encrypted data to underlying writer: %w", err) 187 | } 188 | 189 | return originSize, nil 190 | } 191 | 192 | // Close writes any buffered data to the underlying io.Writer. 193 | // Make sure close the writer after write all data. 194 | func (e *EncryptWriter) Close() error { 195 | padlen := 1 196 | for ((len(e.buf) + padlen) % aes.BlockSize) != 0 { 197 | padlen++ 198 | } 199 | 200 | pad := bytes.Repeat([]byte{byte(padlen)}, padlen) 201 | pad = append(e.buf, pad...) 202 | 203 | e.buf = nil 204 | e.mode.CryptBlocks(pad, pad) 205 | 206 | if _, err := e.w.Write(pad); err != nil { 207 | return fmt.Errorf("writing padding to underlying writer: %w", err) 208 | } 209 | 210 | return nil 211 | } 212 | 213 | func (e *EncryptWriter) initMode() error { 214 | if e.mode != nil { 215 | return nil 216 | } 217 | 218 | salt := make([]byte, opensslSaltLength) // Generate an 8 byte salt 219 | _, err := io.ReadFull(rand.Reader, salt) 220 | if err != nil { 221 | return fmt.Errorf("reading salt: %w", err) 222 | } 223 | 224 | _, err = e.w.Write(append([]byte(opensslSaltHeader), salt...)) 225 | if err != nil { 226 | return fmt.Errorf("writing salt to underlying writer: %w", err) 227 | } 228 | 229 | creds, err := e.cg(e.passphrase, salt) 230 | if err != nil { 231 | return err 232 | } 233 | 234 | c, err := aes.NewCipher(creds.Key) 235 | if err != nil { 236 | return fmt.Errorf("creating new AES cipher: %w", err) 237 | } 238 | e.mode = cipher.NewCBCEncrypter(c, creds.IV) 239 | return nil 240 | } 241 | -------------------------------------------------------------------------------- /stream_test.go: -------------------------------------------------------------------------------- 1 | package openssl 2 | 3 | import ( 4 | "bytes" 5 | "crypto/aes" 6 | "fmt" 7 | "io" 8 | "testing" 9 | 10 | "github.com/stretchr/testify/assert" 11 | "github.com/stretchr/testify/require" 12 | ) 13 | 14 | type limitedSizeReader struct { 15 | size int 16 | r io.Reader 17 | } 18 | 19 | func (o *limitedSizeReader) Read(b []byte) (int, error) { 20 | if len(b) == 0 { 21 | return 0, nil 22 | } 23 | 24 | return o.r.Read(b[:o.size]) //nolint:wrapcheck 25 | } 26 | 27 | func TestReader(t *testing.T) { 28 | o := New() 29 | 30 | pass := "abcd" 31 | plaintext := []byte("123abc,./vvvczcekdewfeojdosndsdlsndlncnepcnodcnviorf409eofnvkdfvjfvdsoijvo") 32 | 33 | data, err := o.EncryptBinaryBytes(pass, plaintext, BytesToKeyMD5) 34 | require.NoError(t, err) 35 | 36 | for i := 1; i <= aes.BlockSize+1; i++ { 37 | t.Run(fmt.Sprintf("read_size_%d", i), func(t *testing.T) { 38 | var ( 39 | buf = new(bytes.Buffer) 40 | bytesBuf = make([]byte, aes.BlockSize+1) 41 | r = &limitedSizeReader{i, bytes.NewReader(data)} 42 | ) 43 | 44 | _, err = io.CopyBuffer(buf, NewReader(r, pass, BytesToKeyMD5), bytesBuf) 45 | require.NoError(t, err) 46 | assert.Equal(t, plaintext, buf.Bytes()) 47 | }) 48 | } 49 | } 50 | 51 | func TestWriter(t *testing.T) { 52 | o := New() 53 | 54 | pass := "abcd" 55 | plaintext := []byte("123abc,./vvvczcekdewfeojzaasdsddsdosnd432pdneonkefnoescndisbcisfheosfbdk vsdovsdn]sdlsndlncnepcnodcnviorf409eofnvkdfvjfvdsoijvo") 56 | 57 | buf := bytes.NewBuffer(nil) 58 | es := NewWriter(buf, pass, BytesToKeyMD5) 59 | 60 | _, err := es.Write(plaintext) 61 | require.NoError(t, err) 62 | require.NoError(t, es.Close()) 63 | 64 | da, err := o.DecryptBinaryBytes(pass, buf.Bytes(), BytesToKeyMD5) 65 | require.NoError(t, err) 66 | 67 | require.Equal(t, da, plaintext) 68 | } 69 | --------------------------------------------------------------------------------