├── .formatter.exs ├── .github └── workflows │ └── main.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── lib ├── pbcs.ex └── pbcs │ ├── aes_cbc_hmac_sha2.ex │ ├── aes_gcm.ex │ ├── content_encryptor.ex │ ├── crypto_wrapper.ex │ ├── key_manager.ex │ ├── pbes2_hmac_sha2.ex │ ├── pkcs5.ex │ └── utils.ex ├── mix.exs ├── mix.lock └── test ├── pbcs_test.exs └── test_helper.exs /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["mix.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | format: 7 | name: Format 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v1 11 | 12 | - name: Install OTP and Elixir 13 | uses: erlef/setup-elixir@v1 14 | with: 15 | otp-version: 24.0 16 | elixir-version: 1.12.0 17 | 18 | - run: mix deps.get 19 | - run: mix deps.compile 20 | - run: mix compile --warnings-as-errors 21 | - run: mix format --check-formatted 22 | 23 | test: 24 | name: Test 25 | runs-on: ubuntu-latest 26 | 27 | strategy: 28 | fail-fast: false 29 | matrix: 30 | pair: 31 | - erlang: 24.0 32 | elixir: master 33 | - erlang: master 34 | elixir: 1.12.0 35 | - erlang: 24.0 36 | elixir: 1.12.0 37 | - erlang: 23.1 38 | elixir: 1.11.3 39 | - erlang: 23.1 40 | elixir: 1.10.4 41 | - erlang: 22.3 42 | elixir: 1.9.4 43 | - erlang: 21.3 44 | elixir: 1.8.1 45 | - erlang: 21.3 46 | elixir: 1.7.2 47 | - erlang: 21.3 48 | elixir: 1.6.6 49 | - erlang: 20.3 50 | elixir: 1.5.3 51 | - erlang: 20.2 52 | elixir: 1.4.5 53 | 54 | steps: 55 | - uses: actions/checkout@v1 56 | 57 | - name: Install OTP and Elixir 58 | uses: erlef/setup-beam@v1.7 59 | with: 60 | otp-version: ${{matrix.pair.erlang}} 61 | elixir-version: ${{matrix.pair.elixir}} 62 | 63 | - name: Install Mix Dependencies 64 | if: steps.mix-cache.outputs.cache-hit != 'true' 65 | run: | 66 | mix local.rebar --force 67 | mix local.hex --force 68 | mix deps.get 69 | 70 | - name: Run tests 71 | run: mix test 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where 3rd-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | pbcs-*.tar 24 | 25 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## v0.1.4 4 | 5 | * Bug fixes 6 | * Use old style cipher atoms for calls to `crypto:crypto_one_time_aead`. 7 | `crypto_one_time_aead` was introduced in OTP 22 but requires ciphers to 8 | be passed with the key length, such as `aes_128_gcm`. OTP 24 supports 9 | the use of the cipher `aes_gcm` where the length if inferred from the 10 | key, but this doesn't work for 22/23. 11 | 12 | ## v0.1.3 13 | 14 | * Enhancements 15 | * Update crypto API calls for OTP 24 support 16 | 17 | ## v0.1.2 18 | 19 | * Enhancements 20 | * Clean up Elixir 1.11 warnings 21 | 22 | ## v0.1.1 23 | 24 | * Bug fixes 25 | * Various updates to specs and docs 26 | 27 | ## v0.1.0 28 | 29 | Initial release 30 | The code originated from the [hex](https://github.com/hexpm/hex) 31 | -------------------------------------------------------------------------------- /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 | Copyright 2018, Six Colors AB 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PBCS 2 | 3 | [![Hex version](https://img.shields.io/hexpm/v/pbcs.svg "Hex version")](https://hex.pm/packages/pbcs) 4 | [![CI](https://github.com/hexpm/hexpm/workflows/CI/badge.svg)](https://github.com/hexpm/pbcs/actions?query=workflow%3ACI) 5 | 6 | The PBCS library securely protects secrets using passwords by following the 7 | style and recommendations in [PKCS #5 2.1](https://tools.ietf.org/html/rfc8018). 8 | As in PKCS #5, this library uses a salt to protect against dictionary attacks 9 | and iterates the key derivation function to increase the computation cost of 10 | attacks. These parameters and the cryptographic algorithms used are 11 | configurable. 12 | 13 | Key derivation algorithms include: 14 | 15 | * `PBES2-HS512`, `PBES2-HS384`, `PBES2-HS256` - PBES2 and HMAC-SHA-2. See [RFC 7518 4.8](https://tools.ietf.org/html/rfc7518#section-4.8) and [RFC 2898 6.2](https://tools.ietf.org/html/rfc2898#section-6.2) 16 | 17 | Content encryption algorithms include: 18 | 19 | * `A256GCM`, `A192GCM`, `A128GCM` - AES GCM. See [RFC 7518 5.3](https://tools.ietf.org/html/rfc7518#section-5.3) 20 | * `A256CBC-HS512`, `A192CBC-HS384`, `A128CBC-HS256` - AES_CBC_HMAC_SHA2. See [RFC 7518 5.2.6](https://tools.ietf.org/html/rfc7518#section-5.2.6) 21 | 22 | ## Installation 23 | 24 | Add pbcs to the `deps` section of your mix.exs file: 25 | 26 | ```elixir 27 | def deps do 28 | [ 29 | {:pbcs, "~> 0.1.0"} 30 | ] 31 | end 32 | ``` 33 | 34 | ## Usage 35 | 36 | ```elixir 37 | protected = %{ 38 | alg: "PBES2-HS512", 39 | enc: "A256GCM", 40 | p2c: 4096, 41 | p2s: :crypto.strong_rand_bytes(32) 42 | } 43 | 44 | tag = "ARBITRARY_TAG" 45 | 46 | cipher_text = PBCS.encrypt({tag, "Text to encrypt"}, protected, password: "12345") 47 | {:ok, "Text to encrypt"} = PBCS.decrypt({tag, cipher_text}, password: "12345") 48 | ``` 49 | -------------------------------------------------------------------------------- /lib/pbcs.ex: -------------------------------------------------------------------------------- 1 | defmodule PBCS do 2 | @moduledoc ~S""" 3 | PKCS #5: Password-Based Cryptography Specification Version 2.0. 4 | 5 | See: https://tools.ietf.org/html/rfc2898 6 | """ 7 | 8 | alias PBCS.Utils 9 | alias PBCS.ContentEncryptor 10 | alias PBCS.KeyManager 11 | 12 | @type tag :: binary 13 | @type plain_text :: binary 14 | @type cipher_text :: binary 15 | @type protected :: %{alg: String.t(), enc: String.t(), p2c: pos_integer, p2s: binary} 16 | @type opts :: Keyword.t() 17 | 18 | @spec encrypt({tag(), plain_text()}, protected(), opts()) :: 19 | cipher_text() | {:error, String.t()} 20 | def encrypt({tag, plain_text}, protected, opts) do 21 | case KeyManager.encrypt(protected, opts) do 22 | {:ok, protected, key, encrypted_key, content_encryptor} -> 23 | iv = ContentEncryptor.generate_iv(content_encryptor) 24 | protected = :erlang.term_to_binary(protected) 25 | aad = tag <> protected 26 | 27 | {cipher_text, cipher_tag} = 28 | ContentEncryptor.encrypt(content_encryptor, key, iv, {aad, plain_text}) 29 | 30 | %{ 31 | protected: protected, 32 | encrypted_key: encrypted_key, 33 | iv: iv, 34 | cipher_text: cipher_text, 35 | cipher_tag: cipher_tag 36 | } 37 | |> :erlang.term_to_binary() 38 | |> Utils.base64url_encode() 39 | 40 | encrypt_init_error -> 41 | encrypt_init_error 42 | end 43 | end 44 | 45 | @spec decrypt({tag(), cipher_text()}, opts()) :: plain_text() | {:error, String.t()} | :error 46 | def decrypt({tag, cipher_text}, opts) do 47 | {:ok, cipher_text} = Utils.base64url_decode(cipher_text) 48 | 49 | %{ 50 | protected: protected, 51 | encrypted_key: encrypted_key, 52 | iv: iv, 53 | cipher_text: cipher_text, 54 | cipher_tag: cipher_tag 55 | } = Utils.safe_binary_to_term!(cipher_text, [:safe]) 56 | 57 | aad = tag <> protected 58 | protected = Utils.safe_binary_to_term!(protected, [:safe]) 59 | 60 | case KeyManager.decrypt(protected, encrypted_key, opts) do 61 | {:ok, key, content_encryptor} -> 62 | ContentEncryptor.decrypt(content_encryptor, key, iv, {aad, cipher_text, cipher_tag}) 63 | 64 | decrypt_init_error -> 65 | decrypt_init_error 66 | end 67 | rescue 68 | ArgumentError -> 69 | :error 70 | end 71 | end 72 | -------------------------------------------------------------------------------- /lib/pbcs/aes_cbc_hmac_sha2.ex: -------------------------------------------------------------------------------- 1 | defmodule PBCS.AES_CBC_HMAC_SHA2 do 2 | alias PBCS.ContentEncryptor 3 | alias PBCS.CryptoWrapper 4 | @behaviour ContentEncryptor 5 | 6 | @moduledoc ~S""" 7 | Content Encryption with AES_CBC_HMAC_SHA2. 8 | 9 | See: https://tools.ietf.org/html/rfc7518#section-5.2.6 10 | """ 11 | 12 | @spec content_encrypt({binary, PBCS.plain_text()}, binary(), binary()) :: 13 | {PBCS.cipher_text(), binary()} 14 | def content_encrypt({aad, plain_text}, key, iv) 15 | when is_binary(aad) and is_binary(plain_text) and bit_size(key) in [256, 384, 512] and 16 | bit_size(iv) === 128 do 17 | mac_size = div(byte_size(key), 2) 18 | enc_size = mac_size 19 | tag_size = mac_size 20 | <> = key 21 | cipher_text = aes_cbc_encrypt(enc_key, iv, pkcs7_pad(plain_text)) 22 | aad_length = <> 23 | mac_data = aad <> iv <> cipher_text <> aad_length 24 | <> = hmac_sha2(mac_key, mac_data) 25 | {cipher_text, cipher_tag} 26 | end 27 | 28 | @spec content_decrypt({binary(), PBCS.cipher_text(), PBCS.tag()}, binary(), binary()) :: 29 | {:ok, PBCS.plain_text()} | :error 30 | def content_decrypt({aad, cipher_text, cipher_tag}, key, iv) 31 | when is_binary(aad) and is_binary(cipher_text) and bit_size(cipher_tag) in [128, 192, 256] and 32 | bit_size(key) in [256, 384, 512] and bit_size(iv) === 128 do 33 | mac_size = div(byte_size(key), 2) 34 | enc_size = mac_size 35 | tag_size = mac_size 36 | <> = key 37 | aad_length = <> 38 | mac_data = aad <> iv <> cipher_text <> aad_length 39 | 40 | case hmac_sha2(mac_key, mac_data) do 41 | <<^cipher_tag::binary-size(tag_size), _::binary>> -> 42 | case aes_cbc_decrypt(enc_key, iv, cipher_text) do 43 | plain_text when is_binary(plain_text) -> 44 | pkcs7_unpad(plain_text) 45 | 46 | _ -> 47 | :error 48 | end 49 | 50 | _ -> 51 | :error 52 | end 53 | end 54 | 55 | def init(%{enc: enc}, _opts) do 56 | {:ok, %{key_length: encoding_to_key_length(enc)}} 57 | end 58 | 59 | def encrypt(%{key_length: key_length}, key, iv, {aad, plain_text}) 60 | when byte_size(key) == key_length do 61 | content_encrypt({aad, plain_text}, key, iv) 62 | end 63 | 64 | def decrypt(%{key_length: key_length}, key, iv, {aad, cipher_text, cipher_tag}) 65 | when byte_size(key) == key_length do 66 | content_decrypt({aad, cipher_text, cipher_tag}, key, iv) 67 | end 68 | 69 | def generate_key(%{key_length: key_length}) do 70 | :crypto.strong_rand_bytes(key_length) 71 | end 72 | 73 | def generate_iv(_params) do 74 | :crypto.strong_rand_bytes(16) 75 | end 76 | 77 | def key_length(%{key_length: key_length}) do 78 | key_length 79 | end 80 | 81 | # Support new and old style AES-CBC calls. 82 | defp aes_cbc_encrypt(key, iv, plain_text) do 83 | CryptoWrapper.block_encrypt(:aes_cbc, key, iv, plain_text) 84 | end 85 | 86 | defp aes_cbc_decrypt(key, iv, cipher_text) do 87 | CryptoWrapper.block_decrypt(:aes_cbc, key, iv, cipher_text) 88 | end 89 | 90 | defp hmac_sha2(mac_key, mac_data) when bit_size(mac_key) === 128 do 91 | CryptoWrapper.hmac(:sha256, mac_key, mac_data) 92 | end 93 | 94 | defp hmac_sha2(mac_key, mac_data) when bit_size(mac_key) === 192 do 95 | CryptoWrapper.hmac(:sha384, mac_key, mac_data) 96 | end 97 | 98 | defp hmac_sha2(mac_key, mac_data) when bit_size(mac_key) === 256 do 99 | CryptoWrapper.hmac(:sha512, mac_key, mac_data) 100 | end 101 | 102 | # Pads a message using the PKCS #7 cryptographic message syntax. 103 | # 104 | # See: https://tools.ietf.org/html/rfc2315 105 | # See: `pkcs7_unpad/1` 106 | defp pkcs7_pad(message) do 107 | bytes_remaining = rem(byte_size(message), 16) 108 | padding_size = 16 - bytes_remaining 109 | message <> :binary.copy(<>, padding_size) 110 | end 111 | 112 | # Unpads a message using the PKCS #7 cryptographic message syntax. 113 | # 114 | # See: https://tools.ietf.org/html/rfc2315 115 | # See: `pkcs7_pad/1` 116 | defp pkcs7_unpad(<<>>) do 117 | :error 118 | end 119 | 120 | defp pkcs7_unpad(message) do 121 | padding_size = :binary.last(message) 122 | 123 | if padding_size <= 16 do 124 | message_size = byte_size(message) 125 | 126 | if binary_part(message, message_size, -padding_size) === 127 | :binary.copy(<>, padding_size) do 128 | {:ok, binary_part(message, 0, message_size - padding_size)} 129 | else 130 | :error 131 | end 132 | else 133 | :error 134 | end 135 | end 136 | 137 | defp encoding_to_key_length("A128CBC-HS256"), do: 32 138 | defp encoding_to_key_length("A192CBC-HS384"), do: 48 139 | defp encoding_to_key_length("A256CBC-HS512"), do: 64 140 | end 141 | -------------------------------------------------------------------------------- /lib/pbcs/aes_gcm.ex: -------------------------------------------------------------------------------- 1 | defmodule PBCS.AES_GCM do 2 | @moduledoc ~S""" 3 | Content Encryption with AES GCM. 4 | 5 | See: https://tools.ietf.org/html/rfc7518#section-5.3 6 | See: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf 7 | """ 8 | 9 | alias PBCS.ContentEncryptor 10 | alias PBCS.CryptoWrapper 11 | 12 | @behaviour ContentEncryptor 13 | 14 | @spec content_encrypt({binary, PBCS.plain_text()}, binary(), binary()) :: 15 | {PBCS.cipher_text(), binary()} 16 | def content_encrypt({aad, plain_text}, key, iv) 17 | when is_binary(aad) and is_binary(plain_text) and bit_size(key) in [128, 192, 256] and 18 | bit_size(iv) === 96 do 19 | CryptoWrapper.block_encrypt(:aes_gcm, key, iv, {aad, plain_text}) 20 | end 21 | 22 | @spec content_decrypt({binary(), PBCS.cipher_text(), PBCS.tag()}, binary(), binary()) :: 23 | {:ok, PBCS.plain_text()} | :error 24 | def content_decrypt({aad, cipher_text, cipher_tag}, key, iv) 25 | when is_binary(aad) and is_binary(cipher_text) and bit_size(cipher_tag) === 128 and 26 | bit_size(key) in [128, 192, 256] and bit_size(iv) === 96 do 27 | case CryptoWrapper.block_decrypt(:aes_gcm, key, iv, {aad, cipher_text, cipher_tag}) do 28 | plain_text when is_binary(plain_text) -> 29 | {:ok, plain_text} 30 | 31 | _ -> 32 | :error 33 | end 34 | end 35 | 36 | def init(%{enc: enc}, _opts) do 37 | {:ok, %{key_length: encoding_to_key_length(enc)}} 38 | end 39 | 40 | def encrypt(%{key_length: key_length}, key, iv, {aad, plain_text}) 41 | when byte_size(key) == key_length do 42 | content_encrypt({aad, plain_text}, key, iv) 43 | end 44 | 45 | def decrypt(%{key_length: key_length}, key, iv, {aad, cipher_text, cipher_tag}) 46 | when byte_size(key) == key_length do 47 | content_decrypt({aad, cipher_text, cipher_tag}, key, iv) 48 | end 49 | 50 | def generate_key(%{key_length: key_length}) do 51 | :crypto.strong_rand_bytes(key_length) 52 | end 53 | 54 | def generate_iv(_params) do 55 | :crypto.strong_rand_bytes(12) 56 | end 57 | 58 | def key_length(%{key_length: key_length}) do 59 | key_length 60 | end 61 | 62 | defp encoding_to_key_length("A128GCM"), do: 16 63 | defp encoding_to_key_length("A192GCM"), do: 24 64 | defp encoding_to_key_length("A256GCM"), do: 32 65 | end 66 | -------------------------------------------------------------------------------- /lib/pbcs/content_encryptor.ex: -------------------------------------------------------------------------------- 1 | defmodule PBCS.ContentEncryptor do 2 | @moduledoc """ 3 | Callback module for content encryptors. 4 | 5 | Implement this behaviour if you want to implement your own content encryptor. 6 | """ 7 | 8 | alias PBCS 9 | alias __MODULE__ 10 | 11 | @type t :: %ContentEncryptor{ 12 | module: module, 13 | params: any 14 | } 15 | 16 | defstruct module: nil, 17 | params: nil 18 | 19 | @callback init(protected :: map, opts :: Keyword.t()) :: {:ok, any} | {:error, String.t()} 20 | 21 | @callback encrypt( 22 | params :: any, 23 | key :: binary, 24 | iv :: binary, 25 | {aad :: binary, plain_text :: binary} 26 | ) :: {binary, binary} 27 | 28 | @callback decrypt( 29 | params :: any, 30 | key :: binary, 31 | iv :: binary, 32 | {aad :: binary, cipher_text :: binary, cipher_tag :: binary} 33 | ) :: {:ok, binary} | :error 34 | 35 | @callback generate_key(params :: any) :: binary 36 | 37 | @callback generate_iv(params :: any) :: binary 38 | 39 | @callback key_length(params :: any) :: non_neg_integer 40 | 41 | def init(protected = %{enc: enc}, opts) do 42 | case content_encryptor_module(enc) do 43 | :error -> 44 | {:error, "Unrecognized ContentEncryptor algorithm: #{inspect(enc)}"} 45 | 46 | module -> 47 | case module.init(protected, opts) do 48 | {:ok, params} -> 49 | content_encryptor = %ContentEncryptor{module: module, params: params} 50 | {:ok, content_encryptor} 51 | 52 | content_encryptor_error -> 53 | content_encryptor_error 54 | end 55 | end 56 | end 57 | 58 | @spec encrypt(PBCS.ContentEncryptor.t(), binary(), binary(), {binary(), PBCS.plain_text()}) :: 59 | {binary(), PBCS.cipher_text()} 60 | def encrypt(%ContentEncryptor{module: module, params: params}, key, iv, {aad, plain_text}) do 61 | module.encrypt(params, key, iv, {aad, plain_text}) 62 | end 63 | 64 | @spec decrypt( 65 | PBCS.ContentEncryptor.t(), 66 | binary(), 67 | binary(), 68 | {binary(), PBCS.cipher_text(), binary()} 69 | ) :: {:ok, PBCS.plain_text()} | :error 70 | def decrypt( 71 | %ContentEncryptor{module: module, params: params}, 72 | key, 73 | iv, 74 | {aad, cipher_text, cipher_tag} 75 | ) do 76 | module.decrypt(params, key, iv, {aad, cipher_text, cipher_tag}) 77 | end 78 | 79 | @spec generate_key(PBCS.ContentEncryptor.t()) :: binary() 80 | def generate_key(%ContentEncryptor{module: module, params: params}) do 81 | module.generate_key(params) 82 | end 83 | 84 | @spec generate_iv(PBCS.ContentEncryptor.t()) :: binary() 85 | def generate_iv(%ContentEncryptor{module: module, params: params}) do 86 | module.generate_iv(params) 87 | end 88 | 89 | @spec key_length(PBCS.ContentEncryptor.t()) :: pos_integer() 90 | def key_length(%ContentEncryptor{module: module, params: params}) do 91 | module.key_length(params) 92 | end 93 | 94 | defp content_encryptor_module("A128CBC-HS256"), do: PBCS.AES_CBC_HMAC_SHA2 95 | defp content_encryptor_module("A192CBC-HS384"), do: PBCS.AES_CBC_HMAC_SHA2 96 | defp content_encryptor_module("A256CBC-HS512"), do: PBCS.AES_CBC_HMAC_SHA2 97 | defp content_encryptor_module("A128GCM"), do: PBCS.AES_GCM 98 | defp content_encryptor_module("A192GCM"), do: PBCS.AES_GCM 99 | defp content_encryptor_module("A256GCM"), do: PBCS.AES_GCM 100 | defp content_encryptor_module(_), do: :error 101 | end 102 | -------------------------------------------------------------------------------- /lib/pbcs/crypto_wrapper.ex: -------------------------------------------------------------------------------- 1 | defmodule PBCS.CryptoWrapper do 2 | @moduledoc false 3 | # :crypto.mac/4 is introduced in Erlang/OTP 22.1 and :crypto.hmac/{3,4} are removed 4 | # in Erlang/OTP 24. The check is needed for backwards compatibility. 5 | Code.ensure_loaded?(:crypto) || IO.warn(":crypto module failed to load") 6 | 7 | case function_exported?(:crypto, :mac, 4) do 8 | true -> 9 | def hmac(type, key, data), do: :crypto.mac(:hmac, type, key, data) 10 | 11 | false -> 12 | def hmac(type, key, data), do: :crypto.hmac(type, key, data) 13 | end 14 | 15 | # Support new and old style AES-CBC calls. 16 | case function_exported?(:crypto, :crypto_one_time, 5) do 17 | true -> 18 | def block_decrypt(cipher, key, iv, {aad, cipher_text, cipher_tag}) do 19 | cipher = cipher_alias(cipher, bit_size(key)) 20 | :crypto.crypto_one_time_aead(cipher, key, iv, cipher_text, aad, cipher_tag, false) 21 | end 22 | 23 | def block_encrypt(cipher, key, iv, {aad, plain_text}) do 24 | cipher = cipher_alias(cipher, bit_size(key)) 25 | :crypto.crypto_one_time_aead(cipher, key, iv, plain_text, aad, true) 26 | end 27 | 28 | # TODO: remove when we require OTP 24 (since it has similar alias handling) 29 | defp cipher_alias(:aes_gcm, 128), do: :aes_128_gcm 30 | defp cipher_alias(:aes_gcm, 192), do: :aes_192_gcm 31 | defp cipher_alias(:aes_gcm, 256), do: :aes_256_gcm 32 | defp cipher_alias(other, _), do: other 33 | 34 | false -> 35 | def block_decrypt(cipher, key, iv, cipher_text) do 36 | :crypto.block_decrypt(cipher, key, iv, cipher_text) 37 | rescue 38 | FunctionClauseError -> 39 | key 40 | |> bit_size() 41 | |> bit_size_to_cipher() 42 | |> :crypto.block_decrypt(key, iv, cipher_text) 43 | end 44 | 45 | def block_encrypt(cipher, key, iv, plain_text) do 46 | :crypto.block_encrypt(cipher, key, iv, plain_text) 47 | rescue 48 | FunctionClauseError -> 49 | key 50 | |> bit_size() 51 | |> bit_size_to_cipher() 52 | |> :crypto.block_encrypt(key, iv, plain_text) 53 | end 54 | 55 | defp bit_size_to_cipher(128), do: :aes_cbc128 56 | defp bit_size_to_cipher(192), do: :aes_cbc192 57 | defp bit_size_to_cipher(256), do: :aes_cbc256 58 | end 59 | end 60 | -------------------------------------------------------------------------------- /lib/pbcs/key_manager.ex: -------------------------------------------------------------------------------- 1 | defmodule PBCS.KeyManager do 2 | @moduledoc """ 3 | Callback module for key managers. 4 | 5 | Implement this behaviour if you want to implement your own key manager. 6 | """ 7 | 8 | alias PBCS 9 | alias PBCS.ContentEncryptor 10 | alias __MODULE__ 11 | 12 | @type t :: %KeyManager{ 13 | module: module, 14 | params: any 15 | } 16 | 17 | defstruct module: nil, 18 | params: nil 19 | 20 | @callback init(protected :: map, opts :: Keyword.t()) :: {:ok, any} | {:error, String.t()} 21 | 22 | @callback encrypt(params :: any, protected :: map, content_encryptor :: ContentEncryptor.t()) :: 23 | {:ok, map, binary, binary} | {:error, String.t()} 24 | 25 | @callback decrypt( 26 | params :: any, 27 | protected :: map, 28 | encrypted_key :: binary, 29 | content_encryptor :: ContentEncryptor.t() 30 | ) :: {:ok, binary} | {:error, String.t()} 31 | 32 | @doc false 33 | def init(%{alg: alg} = protected, opts) do 34 | case key_manager_module(alg) do 35 | {:ok, module} -> 36 | case module.init(protected, opts) do 37 | {:ok, params} -> 38 | key_manager = %KeyManager{module: module, params: params} 39 | fetch_content_encryptor(key_manager, protected, opts) 40 | 41 | key_manager_error -> 42 | key_manager_error 43 | end 44 | 45 | error -> 46 | error 47 | end 48 | end 49 | 50 | @doc false 51 | def encrypt(protected, opts) do 52 | case init(protected, opts) do 53 | {:ok, %KeyManager{module: module, params: params}, content_encryptor} -> 54 | case module.encrypt(params, protected, content_encryptor) do 55 | {:ok, protected, key, encrypted_key} -> 56 | {:ok, protected, key, encrypted_key, content_encryptor} 57 | 58 | key_manager_error -> 59 | key_manager_error 60 | end 61 | 62 | init_error -> 63 | init_error 64 | end 65 | end 66 | 67 | @doc false 68 | def decrypt(protected, encrypted_key, opts) do 69 | case init(protected, opts) do 70 | {:ok, %KeyManager{module: module, params: params}, content_encryptor} -> 71 | case module.decrypt(params, protected, encrypted_key, content_encryptor) do 72 | {:ok, key} -> 73 | {:ok, key, content_encryptor} 74 | 75 | key_manager_error -> 76 | key_manager_error 77 | end 78 | 79 | init_error -> 80 | init_error 81 | end 82 | end 83 | 84 | defp key_manager_module("PBES2-HS256"), do: {:ok, PBCS.PBES2_HMAC_SHA2} 85 | defp key_manager_module("PBES2-HS384"), do: {:ok, PBCS.PBES2_HMAC_SHA2} 86 | defp key_manager_module("PBES2-HS512"), do: {:ok, PBCS.PBES2_HMAC_SHA2} 87 | defp key_manager_module(alg), do: {:error, "Unrecognized KeyManager algorithm: #{inspect(alg)}"} 88 | 89 | defp fetch_content_encryptor(key_manager, protected, opts) do 90 | case ContentEncryptor.init(protected, opts) do 91 | {:ok, content_encryptor} -> 92 | {:ok, key_manager, content_encryptor} 93 | 94 | error -> 95 | error 96 | end 97 | end 98 | end 99 | -------------------------------------------------------------------------------- /lib/pbcs/pbes2_hmac_sha2.ex: -------------------------------------------------------------------------------- 1 | defmodule PBCS.PBES2_HMAC_SHA2 do 2 | @moduledoc ~S""" 3 | Direct Key Derivation with PBES2 and HMAC-SHA-2. 4 | 5 | See: https://tools.ietf.org/html/rfc7518#section-4.8 6 | See: https://tools.ietf.org/html/rfc2898#section-6.2 7 | """ 8 | 9 | alias PBCS.ContentEncryptor 10 | alias PBCS.KeyManager 11 | alias PBCS.PKCS5 12 | 13 | @behaviour KeyManager 14 | 15 | @spec derive_key(String.t(), binary, pos_integer, non_neg_integer, :sha256 | :sha384 | :sha512) :: 16 | binary 17 | def derive_key(password, salt_input, iterations, derived_key_length, hash) 18 | when is_binary(password) and is_binary(salt_input) and is_integer(iterations) and 19 | iterations >= 1 and is_integer(derived_key_length) and derived_key_length >= 0 and 20 | hash in [:sha256, :sha384, :sha512] do 21 | salt = wrap_salt_input(salt_input, hash) 22 | derived_key = PKCS5.pbkdf2(password, salt, iterations, derived_key_length, hash) 23 | derived_key 24 | end 25 | 26 | def init(%{alg: alg} = protected, opts) do 27 | hash = algorithm_to_hash(alg) 28 | 29 | case fetch_password(opts) do 30 | {:ok, password} -> 31 | case fetch_p2c(protected) do 32 | {:ok, _iteration} -> 33 | protected 34 | |> fetch_p2s() 35 | |> handle_p2s(hash, password) 36 | 37 | error -> 38 | error 39 | end 40 | 41 | error -> 42 | error 43 | end 44 | end 45 | 46 | def encrypt( 47 | %{password: password, hash: hash}, 48 | %{p2c: iterations, p2s: salt} = protected, 49 | content_encryptor 50 | ) do 51 | derived_key_length = ContentEncryptor.key_length(content_encryptor) 52 | key = derive_key(password, salt, iterations, derived_key_length, hash) 53 | encrypted_key = "" 54 | {:ok, protected, key, encrypted_key} 55 | end 56 | 57 | def decrypt( 58 | %{password: password, hash: hash}, 59 | %{p2c: iterations, p2s: salt}, 60 | "", 61 | content_encryptor 62 | ) do 63 | derived_key_length = ContentEncryptor.key_length(content_encryptor) 64 | key = derive_key(password, salt, iterations, derived_key_length, hash) 65 | {:ok, key} 66 | end 67 | 68 | def decrypt(_, _, _, _), do: :error 69 | 70 | defp handle_p2s({:ok, _salt}, hash, passwd), do: {:ok, %{hash: hash, password: passwd}} 71 | defp handle_p2s(error, _, _), do: error 72 | 73 | defp fetch_password(opts) do 74 | case Keyword.fetch(opts, :password) do 75 | {:ok, password} when is_binary(password) -> 76 | {:ok, password} 77 | 78 | _ -> 79 | {:error, "option :password (PBKDF2 password) must be a binary"} 80 | end 81 | end 82 | 83 | defp fetch_p2c(opts) do 84 | case Map.fetch(opts, :p2c) do 85 | {:ok, p2c} when is_integer(p2c) and p2c >= 1 -> 86 | {:ok, p2c} 87 | 88 | _ -> 89 | {:error, "protected :p2c (PBKDF2 iterations) must be a positive integer"} 90 | end 91 | end 92 | 93 | defp fetch_p2s(opts) do 94 | case Map.fetch(opts, :p2s) do 95 | {:ok, p2s} when is_binary(p2s) -> 96 | {:ok, p2s} 97 | 98 | _ -> 99 | {:error, "protected :p2s (PBKDF2 salt) must be a binary"} 100 | end 101 | end 102 | 103 | defp wrap_salt_input(salt_input, :sha256) do 104 | <<"PBES2-HS256", 0, salt_input::binary>> 105 | end 106 | 107 | defp wrap_salt_input(salt_input, :sha384) do 108 | <<"PBES2-HS384", 0, salt_input::binary>> 109 | end 110 | 111 | defp wrap_salt_input(salt_input, :sha512) do 112 | <<"PBES2-HS512", 0, salt_input::binary>> 113 | end 114 | 115 | defp algorithm_to_hash("PBES2-HS256"), do: :sha256 116 | defp algorithm_to_hash("PBES2-HS384"), do: :sha384 117 | defp algorithm_to_hash("PBES2-HS512"), do: :sha512 118 | end 119 | -------------------------------------------------------------------------------- /lib/pbcs/pkcs5.ex: -------------------------------------------------------------------------------- 1 | defmodule PBCS.PKCS5 do 2 | @moduledoc false 3 | alias PBCS.CryptoWrapper 4 | 5 | def pbkdf2(password, salt, iterations, derived_key_length, hash) 6 | when is_binary(password) and is_binary(salt) and is_integer(iterations) and iterations >= 1 and 7 | is_integer(derived_key_length) and derived_key_length >= 0 do 8 | hash_length = byte_size(CryptoWrapper.hmac(hash, <<>>, <<>>)) 9 | 10 | if derived_key_length > 0xFFFFFFFF * hash_length do 11 | raise ArgumentError, "derived key too long" 12 | else 13 | rounds = ceildiv(derived_key_length, hash_length) 14 | 15 | <> = 16 | pbkdf2_iterate(password, salt, iterations, hash, 1, rounds, "") 17 | 18 | derived_key 19 | end 20 | end 21 | 22 | defp ceildiv(a, b) do 23 | div(a, b) + if rem(a, b) === 0, do: 0, else: 1 24 | end 25 | 26 | defp pbkdf2_iterate(password, salt, iterations, hash, rounds, rounds, derived_keying_material) do 27 | derived_keying_material <> 28 | pbkdf2_exor(password, salt, iterations, hash, 1, rounds, <<>>, <<>>) 29 | end 30 | 31 | defp pbkdf2_iterate(password, salt, iterations, hash, counter, rounds, derived_keying_material) do 32 | derived_keying_material = 33 | derived_keying_material <> 34 | pbkdf2_exor(password, salt, iterations, hash, 1, counter, <<>>, <<>>) 35 | 36 | pbkdf2_iterate(password, salt, iterations, hash, counter + 1, rounds, derived_keying_material) 37 | end 38 | 39 | defp pbkdf2_exor(_password, _salt, iterations, _hash, i, _counter, _prev, curr) 40 | when i > iterations do 41 | curr 42 | end 43 | 44 | defp pbkdf2_exor(password, salt, iterations, hash, i = 1, counter, <<>>, <<>>) do 45 | next = 46 | CryptoWrapper.hmac( 47 | hash, 48 | password, 49 | <> 50 | ) 51 | 52 | pbkdf2_exor(password, salt, iterations, hash, i + 1, counter, next, next) 53 | end 54 | 55 | defp pbkdf2_exor(password, salt, iterations, hash, i, counter, prev, curr) do 56 | next = CryptoWrapper.hmac(hash, password, prev) 57 | curr = :crypto.exor(next, curr) 58 | pbkdf2_exor(password, salt, iterations, hash, i + 1, counter, next, curr) 59 | end 60 | end 61 | -------------------------------------------------------------------------------- /lib/pbcs/utils.ex: -------------------------------------------------------------------------------- 1 | defmodule PBCS.Utils do 2 | @moduledoc false 3 | 4 | def base64url_encode(binary) do 5 | try do 6 | Base.url_encode64(binary, padding: false) 7 | catch 8 | _, _ -> 9 | binary 10 | |> Base.encode64() 11 | |> urlsafe_encode64(<<>>) 12 | end 13 | end 14 | 15 | def base64url_decode(binary) do 16 | try do 17 | Base.url_decode64(binary, padding: false) 18 | catch 19 | _, _ -> 20 | try do 21 | binary = urlsafe_decode64(binary, <<>>) 22 | 23 | binary = 24 | case rem(byte_size(binary), 4) do 25 | 2 -> binary <> "==" 26 | 3 -> binary <> "=" 27 | _ -> binary 28 | end 29 | 30 | Base.decode64(binary) 31 | catch 32 | _, _ -> 33 | :error 34 | end 35 | end 36 | end 37 | 38 | def safe_binary_to_term!(binary, opts \\ []) do 39 | case safe_binary_to_term(binary, opts) do 40 | {:ok, term} -> 41 | term 42 | 43 | :error -> 44 | raise ArgumentError, "unsafe terms" 45 | end 46 | end 47 | 48 | def safe_binary_to_term(binary, opts \\ []) 49 | 50 | def safe_binary_to_term(binary, opts) when is_binary(binary) do 51 | term = :erlang.binary_to_term(binary, opts) 52 | safe_terms(term) 53 | {:ok, term} 54 | catch 55 | :throw, :safe_terms -> 56 | :error 57 | end 58 | 59 | defp safe_terms(list) when is_list(list) do 60 | safe_list(list) 61 | end 62 | 63 | defp safe_terms(tuple) when is_tuple(tuple) do 64 | safe_tuple(tuple, tuple_size(tuple)) 65 | end 66 | 67 | defp safe_terms(map) when is_map(map) do 68 | fun = fn key, value, acc -> 69 | safe_terms(key) 70 | safe_terms(value) 71 | acc 72 | end 73 | 74 | :maps.fold(fun, map, map) 75 | end 76 | 77 | defp safe_terms(other) 78 | when is_atom(other) or is_number(other) or is_bitstring(other) or is_pid(other) or 79 | is_reference(other) do 80 | other 81 | end 82 | 83 | defp safe_terms(_other) do 84 | throw(:safe_terms) 85 | end 86 | 87 | defp safe_list([]), do: :ok 88 | 89 | defp safe_list([h | t]) when is_list(t) do 90 | safe_terms(h) 91 | safe_list(t) 92 | end 93 | 94 | defp safe_list([h | t]) do 95 | safe_terms(h) 96 | safe_terms(t) 97 | end 98 | 99 | defp safe_tuple(_tuple, 0), do: :ok 100 | 101 | defp safe_tuple(tuple, n) do 102 | safe_terms(:erlang.element(n, tuple)) 103 | safe_tuple(tuple, n - 1) 104 | end 105 | 106 | defp urlsafe_encode64(<>, acc) do 107 | urlsafe_encode64(rest, <>) 108 | end 109 | 110 | defp urlsafe_encode64(<>, acc) do 111 | urlsafe_encode64(rest, <>) 112 | end 113 | 114 | defp urlsafe_encode64(<>, acc) do 115 | urlsafe_encode64(rest, acc) 116 | end 117 | 118 | defp urlsafe_encode64(<>, acc) do 119 | urlsafe_encode64(rest, <>) 120 | end 121 | 122 | defp urlsafe_encode64(<<>>, acc) do 123 | acc 124 | end 125 | 126 | defp urlsafe_decode64(<>, acc) do 127 | urlsafe_decode64(rest, <>) 128 | end 129 | 130 | defp urlsafe_decode64(<>, acc) do 131 | urlsafe_decode64(rest, <>) 132 | end 133 | 134 | defp urlsafe_decode64(<>, acc) do 135 | urlsafe_decode64(rest, <>) 136 | end 137 | 138 | defp urlsafe_decode64(<<>>, acc) do 139 | acc 140 | end 141 | end 142 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule PBCS.MixProject do 2 | use Mix.Project 3 | 4 | @version "0.1.4" 5 | @source_url "https://github.com/hexpm/pbcs" 6 | 7 | def project do 8 | [ 9 | app: :pbcs, 10 | version: @version, 11 | elixir: "~> 1.0", 12 | start_permanent: Mix.env() == :prod, 13 | deps: deps(), 14 | source_url: @source_url, 15 | docs: [source_ref: "v#{@version}", main: "readme", extras: ["README.md"]], 16 | description: description(), 17 | package: package() 18 | ] 19 | end 20 | 21 | def application do 22 | [ 23 | extra_applications: [:crypto] 24 | ] 25 | end 26 | 27 | defp deps do 28 | [ 29 | {:ex_doc, "~> 0.18", only: :dev, runtime: false} 30 | ] 31 | end 32 | 33 | defp description do 34 | "PKCS #5: Password-Based Cryptography Specification Version 2.0" 35 | end 36 | 37 | defp package do 38 | [ 39 | licenses: ["Apache-2.0"], 40 | links: %{"GitHub" => "https://github.com/hexpm/pbcs"} 41 | ] 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "earmark_parser": {:hex, :earmark_parser, "1.4.10", "6603d7a603b9c18d3d20db69921527f82ef09990885ed7525003c7fe7dc86c56", [:mix], [], "hexpm", "8e2d5370b732385db2c9b22215c3f59c84ac7dda7ed7e544d7c459496ae519c0"}, 3 | "ex_doc": {:hex, :ex_doc, "0.23.0", "a069bc9b0bf8efe323ecde8c0d62afc13d308b1fa3d228b65bca5cf8703a529d", [:mix], [{:earmark_parser, "~> 1.4.0", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}], "hexpm", "f5e2c4702468b2fd11b10d39416ddadd2fcdd173ba2a0285ebd92c39827a5a16"}, 4 | "makeup": {:hex, :makeup, "1.0.5", "d5a830bc42c9800ce07dd97fa94669dfb93d3bf5fcf6ea7a0c67b2e0e4a7f26c", [:mix], [{:nimble_parsec, "~> 0.5 or ~> 1.0", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "cfa158c02d3f5c0c665d0af11512fed3fba0144cf1aadee0f2ce17747fba2ca9"}, 5 | "makeup_elixir": {:hex, :makeup_elixir, "0.15.0", "98312c9f0d3730fde4049985a1105da5155bfe5c11e47bdc7406d88e01e4219b", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.1", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "75ffa34ab1056b7e24844c90bfc62aaf6f3a37a15faa76b07bc5eba27e4a8b4a"}, 6 | "nimble_parsec": {:hex, :nimble_parsec, "1.1.0", "3a6fca1550363552e54c216debb6a9e95bd8d32348938e13de5eda962c0d7f89", [:mix], [], "hexpm", "08eb32d66b706e913ff748f11694b17981c0b04a33ef470e33e11b3d3ac8f54b"}, 7 | } 8 | -------------------------------------------------------------------------------- /test/pbcs_test.exs: -------------------------------------------------------------------------------- 1 | defmodule PBCSTest do 2 | use ExUnit.Case, async: true 3 | import PBCS.PKCS5 4 | 5 | defp check_vectors(list) do 6 | Enum.each(list, fn {password, salt, iterations, derived_key_length, hash, derived_key} -> 7 | assert pbkdf2(password, salt, iterations, derived_key_length, hash) === derived_key 8 | end) 9 | end 10 | 11 | defp check_vectors(list, iterations, length, hash_fun) do 12 | Enum.each(list, fn {password, salt, hash} -> 13 | assert pbkdf2(password, salt, iterations, length, hash_fun) == hash 14 | end) 15 | end 16 | 17 | test "PKCS#5 test vectors" do 18 | [ 19 | # See: https://tools.ietf.org/html/rfc6070 20 | {"password", "salt", 1, 20, :sha, 21 | <<12, 96, 200, 15, 150, 31, 14, 113, 243, 169, 181, 36, 175, 96, 18, 6, 47, 224, 55, 166>>}, 22 | {"password", "salt", 2, 20, :sha, 23 | <<234, 108, 1, 77, 199, 45, 111, 140, 205, 30, 217, 42, 206, 29, 65, 240, 216, 222, 137, 24 | 87>>}, 25 | {"password", "salt", 4096, 20, :sha, 26 | <<75, 0, 121, 1, 183, 101, 72, 154, 190, 173, 73, 217, 38, 247, 33, 208, 101, 164, 41, 27 | 193>>}, 28 | # {"password", "salt", 16777216, 20, :sha, <<238,254,61,97,205,77,164,228,233,148,91,61,107,162,21,140,38,52,233,132>>}, 29 | {"passwordPASSWORDpassword", "saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, 25, :sha, 30 | <<61, 46, 236, 79, 228, 28, 132, 155, 128, 200, 216, 54, 98, 192, 228, 74, 139, 41, 26, 31 | 150, 76, 242, 240, 112, 56>>}, 32 | {"pass\0word", "sa\0lt", 4096, 16, :sha, 33 | <<86, 250, 106, 167, 85, 72, 9, 157, 204, 55, 215, 240, 52, 37, 224, 195>>}, 34 | # See: http://stackoverflow.com/a/5136918/818187 35 | {"password", "salt", 1, 32, :sha256, 36 | <<18, 15, 182, 207, 252, 248, 179, 44, 67, 231, 34, 82, 86, 196, 248, 55, 168, 101, 72, 37 | 201, 44, 204, 53, 72, 8, 5, 152, 124, 183, 11, 225, 123>>}, 38 | {"password", "salt", 2, 32, :sha256, 39 | <<174, 77, 12, 149, 175, 107, 70, 211, 45, 10, 223, 249, 40, 240, 109, 208, 42, 48, 63, 40 | 142, 243, 194, 81, 223, 214, 226, 216, 90, 149, 71, 76, 67>>}, 41 | {"password", "salt", 4096, 32, :sha256, 42 | <<197, 228, 120, 213, 146, 136, 200, 65, 170, 83, 13, 182, 132, 92, 76, 141, 150, 40, 147, 43 | 160, 1, 206, 78, 17, 164, 150, 56, 115, 170, 152, 19, 74>>}, 44 | # {"password", "salt", 16777216, 32, :sha256, <<207,129,198,111,232,207,192,77,31,49,236,182,93,171,64,137,247,241,121,232,155,59,11,203,23,173,16,227,172,110,186,70>>}, 45 | {"passwordPASSWORDpassword", "saltSALTsaltSALTsaltSALTsaltSALTsalt", 4096, 40, :sha256, 46 | <<52, 140, 137, 219, 203, 211, 43, 47, 50, 216, 20, 184, 17, 110, 132, 207, 43, 23, 52, 47 | 126, 188, 24, 0, 24, 28, 78, 42, 31, 184, 221, 83, 225, 198, 53, 81, 140, 125, 172, 71, 48 | 233>>}, 49 | {"pass\0word", "sa\0lt", 4096, 16, :sha256, 50 | <<137, 182, 157, 5, 22, 248, 41, 137, 60, 105, 98, 38, 101, 10, 134, 135>>} 51 | ] 52 | |> check_vectors() 53 | end 54 | 55 | test "base" do 56 | assert pbkdf2("password", "0123456789abcdef", 1, 32, :sha512) == 57 | <<193, 61, 90, 136, 113, 11, 206, 56, 158, 69, 39, 50, 130, 177, 251, 11, 214, 1, 58 | 121, 42, 250, 241, 56, 122, 129, 140, 143, 82, 213, 101, 185, 92>> 59 | 60 | assert pbkdf2("password", "0123456789abcdef", 2, 32, :sha512) == 61 | <<186, 98, 237, 134, 129, 9, 190, 135, 251, 15, 165, 175, 31, 49, 183, 11, 201, 34, 62 | 80, 250, 161, 58, 110, 166, 250, 81, 210, 141, 110, 64, 128, 219>> 63 | end 64 | 65 | test "base pbkdf2_sha512" do 66 | [ 67 | {"passDATAb00AB7YxDTT", "saltKEYbcTcXHCBxtjD", 68 | <<172, 205, 205, 135, 152, 174, 92, 216, 88, 4, 115, 144, 21, 239, 42, 17, 227, 37, 145, 69 | 183, 183, 209, 111, 118, 129, 155, 48, 176, 212, 157, 128, 225, 171, 234, 108, 152, 34, 70 | 184, 10, 31, 223, 228, 33, 226, 111, 86, 3, 236, 168, 164, 122, 100, 201, 160, 4, 251, 71 | 90, 248, 34, 159, 118, 47, 244, 31>>}, 72 | {"passDATAb00AB7YxDTTl", "saltKEYbcTcXHCBxtjD2", 73 | <<89, 66, 86, 176, 189, 77, 108, 159, 33, 168, 127, 123, 165, 119, 42, 121, 26, 16, 230, 74 | 17, 6, 148, 244, 67, 101, 205, 148, 103, 14, 87, 241, 174, 205, 121, 126, 241, 209, 0, 75 | 25, 56, 113, 144, 68, 199, 240, 24, 2, 102, 151, 132, 94, 185, 173, 151, 217, 125, 227, 76 | 106, 184, 120, 106, 171, 80, 150>>}, 77 | {"passDATAb00AB7YxDTTlRH2dqxDx19GDxDV1zFMz7E6QVqKIzwOtMnlxQLttpE5", 78 | "saltKEYbcTcXHCBxtjD2PnBh44AIQ6XUOCESOhXpEp3HrcGMwbjzQKMSaf63IJe", 79 | <<7, 68, 116, 1, 200, 87, 102, 228, 174, 213, 131, 222, 46, 107, 245, 166, 117, 234, 190, 80 | 79, 54, 24, 40, 28, 149, 97, 111, 79, 193, 253, 254, 110, 203, 193, 195, 152, 39, 137, 81 | 212, 253, 148, 29, 101, 132, 239, 83, 74, 120, 189, 55, 174, 2, 85, 93, 148, 85, 232, 82 | 240, 137, 253, 180, 223, 182, 187>>} 83 | ] 84 | |> check_vectors(100_000, 64, :sha512) 85 | end 86 | 87 | test "python passlib pbkdf2_sha512" do 88 | [ 89 | {"password", <<36, 196, 248, 159, 51, 166, 84, 170, 213, 250, 159, 211, 154, 83, 10, 193>>, 90 | <<140, 166, 217, 30, 131, 240, 81, 96, 83, 211, 202, 99, 111, 240, 167, 81, 153, 133, 112, 91 | 31, 73, 91, 135, 108, 59, 53, 100, 126, 47, 87, 232, 247, 103, 228, 213, 214, 121, 143, 92 | 166, 132, 189, 65, 155, 133, 125, 174, 54, 11, 229, 151, 192, 223, 107, 161, 236, 105, 93 | 118, 130, 222, 88, 65, 175, 201, 8>>}, 94 | {"p@$$w0rd", <<252, 159, 83, 202, 89, 107, 141, 17, 66, 200, 121, 239, 29, 163, 20, 34>>, 95 | <<0, 157, 195, 175, 221, 186, 150, 210, 181, 176, 230, 76, 100, 0, 40, 79, 177, 40, 71, 96 | 180, 127, 30, 159, 134, 232, 27, 126, 224, 49, 68, 54, 38, 26, 202, 21, 76, 253, 144, 79, 97 | 186, 168, 197, 54, 23, 4, 244, 216, 211, 153, 199, 147, 152, 185, 210, 171, 55, 196, 67, 98 | 201, 154, 127, 46, 61, 179>>}, 99 | {"oh this is hard 2 guess", 100 | <<1, 96, 140, 17, 162, 84, 42, 165, 84, 42, 165, 244, 62, 71, 136, 177>>, 101 | <<23, 76, 100, 204, 149, 14, 41, 161, 252, 167, 0, 31, 19, 2, 222, 100, 173, 191, 150, 46, 102 | 130, 23, 120, 132, 114, 151, 232, 39, 85, 232, 19, 20, 20, 77, 43, 87, 8, 213, 113, 19, 103 | 91, 29, 214, 77, 26, 121, 9, 82, 20, 174, 137, 159, 18, 78, 140, 205, 124, 145, 146, 29, 104 | 204, 214, 36, 113>>}, 105 | {"even more difficult", 106 | <<215, 186, 87, 42, 133, 112, 14, 1, 160, 52, 38, 100, 44, 229, 92, 203>>, 107 | <<76, 75, 253, 194, 132, 154, 85, 59, 24, 28, 188, 87, 156, 86, 214, 59, 90, 10, 173, 65, 108 | 159, 80, 9, 99, 144, 185, 234, 143, 197, 191, 243, 64, 70, 104, 86, 225, 113, 193, 188, 109 | 7, 215, 217, 115, 78, 81, 161, 74, 59, 37, 11, 223, 115, 11, 13, 121, 237, 125, 131, 193, 110 | 131, 229, 76, 112, 28>>} 111 | ] 112 | |> check_vectors(19_000, 64, :sha512) 113 | end 114 | 115 | describe "A256GCM" do 116 | test "encrypt/decrypt" do 117 | protected = %{ 118 | alg: "PBES2-HS512", 119 | enc: "A256GCM", 120 | p2c: 4096, 121 | p2s: :crypto.strong_rand_bytes(32) 122 | } 123 | 124 | cipher_text = PBCS.encrypt({"", "foo"}, protected, password: "bar") 125 | assert {:ok, "foo"} = PBCS.decrypt({"", cipher_text}, password: "bar") 126 | end 127 | end 128 | end 129 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | --------------------------------------------------------------------------------