├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── Cargo.toml ├── LICENSE ├── README.md ├── src └── lib.rs └── tests ├── generate.json ├── invalid.json └── verify.json /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | allow: 8 | # Also update indirect dependencies 9 | - dependency-type: all 10 | - package-ecosystem: "github-actions" 11 | directory: "/" 12 | schedule: 13 | interval: "daily" 14 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: [pull_request, push] 2 | 3 | name: CI 4 | 5 | jobs: 6 | ci: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | RUST: 11 | - stable 12 | - beta 13 | - nightly 14 | features: 15 | - "--features default" 16 | - "--no-default-features --features rustcrypto" 17 | steps: 18 | - uses: actions/checkout@v4.1.1 19 | - uses: actions-rs/toolchain@v1 20 | with: 21 | profile: minimal 22 | toolchain: ${{ matrix.RUST }} 23 | override: true 24 | components: rustfmt, clippy 25 | 26 | - uses: actions-rs/cargo@v1 27 | with: 28 | command: build 29 | args: ${{ matrix.features }} 30 | 31 | - uses: actions-rs/cargo@v1 32 | with: 33 | command: test 34 | 35 | - uses: actions-rs/cargo@v1 36 | with: 37 | command: test 38 | args: ${{ matrix.features }} 39 | 40 | - uses: actions-rs/cargo@v1 41 | with: 42 | command: fmt 43 | args: --all -- --check 44 | 45 | - uses: actions-rs/cargo@v1 46 | with: 47 | command: clippy 48 | args: -- -D warnings 49 | 50 | - uses: actions-rs/audit-check@v1.2.0 51 | with: 52 | token: ${{ secrets.GITHUB_TOKEN }} 53 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target 3 | **/*.rs.bk 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Community Participation Guidelines 2 | 3 | This repository is governed by Mozilla's code of conduct and etiquette guidelines. 4 | For more details, please read the 5 | [Mozilla Community Participation Guidelines](https://www.mozilla.org/about/governance/policies/participation/). 6 | 7 | ## How to Report 8 | For more information on how to report violations of the Community Participation Guidelines, please read our '[How to Report](https://www.mozilla.org/about/governance/policies/participation/reporting/)' page. 9 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "fernet" 3 | version = "0.2.2" 4 | authors = [ 5 | "Alex Gaynor ", 6 | "Ben Bangert ", 7 | ] 8 | description = "An implementation of fernet in Rust." 9 | repository = "https://github.com/mozilla-services/fernet-rs/" 10 | homepage = "https://github.com/mozilla-services/fernet-rs/" 11 | license = "MPL-2.0" 12 | readme = "README.md" 13 | edition = "2018" 14 | 15 | 16 | [badges] 17 | travis-ci = { repository = "mozilla-services/fernet-rs" } 18 | 19 | [features] 20 | default = ["openssl"] 21 | fernet_danger_timestamps = [] 22 | rustcrypto = ["aes", "cbc", "sha2", "hmac", "subtle"] 23 | 24 | [package.metadata.docs.rs] 25 | features = ["fernet_danger_timestamps"] 26 | 27 | [dependencies] 28 | base64 = "0.22" 29 | byteorder = "1" 30 | openssl = { version = "0.10", optional = true } 31 | getrandom = "0.2" 32 | zeroize = { version = "1.0", features = ["zeroize_derive"] } 33 | aes = { version = "0.8", optional = true } 34 | cbc = { version = "0.1", optional = true, features = ["alloc"] } 35 | hmac = { version = "0.12", optional = true } 36 | sha2 = { version = "0.10", optional = true } 37 | subtle = { version = "2.4", optional = true } 38 | 39 | 40 | [dev-dependencies] 41 | time = { version = "0.3", features = ["parsing"] } 42 | serde = "1.0" 43 | serde_derive = "1.0" 44 | serde_json = "1.0" 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | fernet-rs 2 | ========= 3 | 4 | [![dependency status](https://deps.rs/repo/github/mozilla-services/fernet-rs/status.svg)](https://deps.rs/repo/github/mozilla-services/fernet-rs) 5 | 6 | An implementation of [fernet](https://github.com/fernet/spec) in Rust. 7 | 8 | What is Fernet? 9 | --------------- 10 | 11 | Fernet is a small library to help you encrypt parcels of data with optional expiry times. It's 12 | great for tokens or exchanging small strings or blobs of data. Fernet is designed to be easy 13 | to use, combining cryptographic primitives in a way that is hard to get wrong, prevents tampering 14 | and gives you confidence that the token is legitimate. You should consider this if you need: 15 | 16 | * Time limited authentication tokens in URLs or authorisation headers 17 | * To send small blobs of encrypted data between two points with a static key 18 | * Simple encryption of secrets to store to disk that can be read later 19 | * Many more ... 20 | 21 | Great! How do I start? 22 | ---------------------- 23 | 24 | Add fernet to your Cargo.toml: 25 | 26 | [dependencies] 27 | fernet = "0.1" 28 | 29 | And then have a look at our [API documentation] online, or run "cargo doc --open" in your 30 | project. 31 | 32 | [API documentation online]: https://docs.rs/fernet 33 | 34 | Testing Token Expiry 35 | -------------------- 36 | 37 | By default fernet wraps operations in an attempt to be safe - you should never be able to 38 | "hold it incorrectly". But we understand that sometimes you need to be able to do some 39 | more complicated operations. 40 | 41 | The major example of this is having your application test how it handles tokens that 42 | have expired past their ttl. 43 | 44 | To support this, we allow you to pass in timestamps to the `encrypt_at_time` and 45 | `decrypt_at_time` functions, but these are behind a feature gate. To activate these 46 | api's you need to add the following to Cargo.toml 47 | 48 | [dependencies] 49 | fernet = { version = "0.1", features = ["fernet_danger_timestamps"] } 50 | 51 | 52 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![deny(warnings)] 2 | 3 | //! Fernet provides symmetric-authenticated-encryption with an API that makes 4 | //! misusing it difficult. It is based on a public specification and there are 5 | //! interoperable implementations in Rust, Python, Ruby, Go, and Clojure. 6 | 7 | //! # Example 8 | //! ```rust 9 | //! // Store `key` somewhere safe! 10 | //! let key = fernet::Fernet::generate_key(); 11 | //! let fernet = fernet::Fernet::new(&key).unwrap(); 12 | //! let plaintext = b"my top secret message!"; 13 | //! let ciphertext = fernet.encrypt(plaintext); 14 | //! let decrypted_plaintext = fernet.decrypt(&ciphertext); 15 | //! assert_eq!(decrypted_plaintext.unwrap(), plaintext); 16 | // ``` 17 | 18 | use byteorder::ReadBytesExt; 19 | use std::error::Error; 20 | use std::fmt::{self, Display}; 21 | use std::io::{Cursor, Read, Seek, SeekFrom}; 22 | use std::time; 23 | use zeroize::Zeroize; 24 | use base64::Engine; 25 | 26 | #[cfg(feature = "rustcrypto")] 27 | use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, BlockEncryptMut, KeyIvInit}; 28 | #[cfg(feature = "rustcrypto")] 29 | use hmac::Mac; 30 | #[cfg(feature = "rustcrypto")] 31 | use sha2::Sha256; 32 | 33 | #[cfg(not(any(feature = "rustcrypto", feature = "openssl",)))] 34 | compile_error!( 35 | "no crypto cargo feature enabled! \ 36 | please enable one of: default, openssl" 37 | ); 38 | 39 | const MAX_CLOCK_SKEW: u64 = 60; 40 | 41 | // Automatically zero out the contents of the memory when the struct is drop'd. 42 | #[derive(Clone, Zeroize)] 43 | #[zeroize(drop)] 44 | pub struct Fernet { 45 | encryption_key: [u8; 16], 46 | signing_key: [u8; 16], 47 | } 48 | 49 | /// This error is returned when fernet cannot decrypt the ciphertext for any 50 | /// reason. It could be an expired token, incorrect key or other failure. If 51 | /// you recieve this error, you should consider the fernet token provided as 52 | /// invalid. 53 | #[derive(Debug, PartialEq, Eq)] 54 | pub struct DecryptionError; 55 | 56 | impl Error for DecryptionError {} 57 | 58 | impl Display for DecryptionError { 59 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 60 | write!(f, "Fernet decryption error") 61 | } 62 | } 63 | 64 | #[derive(Clone)] 65 | pub struct MultiFernet { 66 | fernets: Vec, 67 | } 68 | 69 | /// `MultiFernet` encapsulates the encrypt operation with the first `Fernet` 70 | /// instance and decryption with the `Fernet` instances provided in order 71 | /// until successful decryption or a `DecryptionError`. 72 | impl MultiFernet { 73 | pub fn new(keys: Vec) -> MultiFernet { 74 | assert!(!keys.is_empty(), "keys must not be empty"); 75 | MultiFernet { fernets: keys } 76 | } 77 | 78 | /// Encrypts data with the first `Fernet` instance. Returns a value 79 | /// (which is base64-encoded) that can be passed to `MultiFernet::decrypt`. 80 | pub fn encrypt(&self, data: &[u8]) -> String { 81 | self.fernets[0].encrypt(data) 82 | } 83 | 84 | /// Decrypts a ciphertext, using the `Fernet` instances provided. Returns 85 | /// either `Ok(plaintext)` if decryption is successful or 86 | /// `Err(DecryptionError)` if no decryption was possible across the set of 87 | /// fernet keys. 88 | pub fn decrypt(&self, token: &str) -> Result, DecryptionError> { 89 | for fernet in self.fernets.iter() { 90 | let res = fernet.decrypt(token); 91 | if res.is_ok() { 92 | return res; 93 | } 94 | } 95 | 96 | Err(DecryptionError) 97 | } 98 | } 99 | 100 | /// Token split into parts before decryption. 101 | struct ParsedToken { 102 | /// message is the whole token except for the HMAC 103 | message: Vec, 104 | /// 128 bit IV 105 | iv: [u8; 16], 106 | /// Ciphertext (part of message) 107 | ciphertext: Vec, 108 | /// 256 bit HMAC 109 | hmac: [u8; 32], 110 | } 111 | 112 | /// `Fernet` encapsulates encrypt and decrypt operations for a particular symmetric key. 113 | impl Fernet { 114 | /// Returns a new fernet instance with the provided key. The key should be 115 | /// 32-bytes, url-safe base64-encoded. Generating keys with `Fernet::generate_key` 116 | /// is recommended. DO NOT USE A HUMAN READABLE PASSWORD AS A KEY. Returns 117 | /// `None` if the key is not 32-bytes base64 encoded. 118 | pub fn new(key: &str) -> Option { 119 | let key = b64_decode_url(key).ok()?; 120 | if key.len() != 32 { 121 | return None; 122 | } 123 | 124 | let mut signing_key: [u8; 16] = Default::default(); 125 | signing_key.copy_from_slice(&key[..16]); 126 | let mut encryption_key: [u8; 16] = Default::default(); 127 | encryption_key.copy_from_slice(&key[16..]); 128 | 129 | Some(Fernet { 130 | signing_key, 131 | encryption_key, 132 | }) 133 | } 134 | 135 | /// Generates a new, random, key. Can be safely passed to `Fernet::new()`. 136 | /// Store this somewhere safe! 137 | pub fn generate_key() -> String { 138 | let mut key: [u8; 32] = Default::default(); 139 | getrandom::getrandom(&mut key).expect("Error in getrandom"); 140 | crate::b64_encode_url(&key.to_vec()) 141 | } 142 | 143 | /// Encrypts data into a token. Returns a value (which is base64-encoded) that can be 144 | /// passed to `Fernet::decrypt` for decryption and verification.. 145 | pub fn encrypt(&self, data: &[u8]) -> String { 146 | let current_time = time::SystemTime::now() 147 | .duration_since(time::UNIX_EPOCH) 148 | .unwrap() 149 | .as_secs(); 150 | self._encrypt_at_time(data, current_time) 151 | } 152 | 153 | /// Encrypts data with the current_time. Returns a value (which is base64-encoded) that can be 154 | /// passed to `Fernet::decrypt`. 155 | /// 156 | /// This function has the capacity to be used incorrectly or insecurely due to 157 | /// to the "current_time" parameter. current_time must be the systems `time::SystemTime::now()` 158 | /// with `duraction_since(time::UNIX_EPOCH)` as seconds. 159 | /// 160 | /// The motivation for a function like this is for your application to be able to test 161 | /// ttl expiry of tokens in your API. This allows you to pass in mock time data to assert 162 | /// correct behaviour of your application. Care should be taken to ensure you always pass in 163 | /// correct current_time values for deployments. 164 | #[inline] 165 | #[cfg(feature = "fernet_danger_timestamps")] 166 | pub fn encrypt_at_time(&self, data: &[u8], current_time: u64) -> String { 167 | self._encrypt_at_time(data, current_time) 168 | } 169 | 170 | fn _encrypt_at_time(&self, data: &[u8], current_time: u64) -> String { 171 | let mut iv: [u8; 16] = Default::default(); 172 | getrandom::getrandom(&mut iv).expect("Error in getrandom"); 173 | self._encrypt_from_parts(data, current_time, &iv) 174 | } 175 | 176 | #[cfg(not(feature = "rustcrypto"))] 177 | fn _encrypt_from_parts(&self, data: &[u8], current_time: u64, iv: &[u8]) -> String { 178 | let ciphertext = openssl::symm::encrypt( 179 | openssl::symm::Cipher::aes_128_cbc(), 180 | &self.encryption_key, 181 | Some(iv), 182 | data, 183 | ) 184 | .unwrap(); 185 | 186 | let mut result = vec![0x80]; 187 | result.extend_from_slice(¤t_time.to_be_bytes()); 188 | result.extend_from_slice(iv); 189 | result.extend_from_slice(&ciphertext); 190 | 191 | let hmac_pkey = openssl::pkey::PKey::hmac(&self.signing_key).unwrap(); 192 | let mut hmac_signer = 193 | openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), &hmac_pkey).unwrap(); 194 | hmac_signer.update(&result).unwrap(); 195 | 196 | result.extend_from_slice(&hmac_signer.sign_to_vec().unwrap()); 197 | 198 | crate::b64_encode_url(&result) 199 | } 200 | 201 | #[cfg(feature = "rustcrypto")] 202 | fn _encrypt_from_parts(&self, data: &[u8], current_time: u64, iv: &[u8]) -> String { 203 | let ciphertext = cbc::Encryptor::::new_from_slices(&self.encryption_key, iv) 204 | .unwrap() 205 | .encrypt_padded_vec_mut::(data); 206 | 207 | let mut result = vec![0x80]; 208 | result.extend_from_slice(¤t_time.to_be_bytes()); 209 | result.extend_from_slice(iv); 210 | result.extend_from_slice(&ciphertext); 211 | 212 | let mut hmac_signer = hmac::Hmac::::new_from_slice(&self.signing_key) 213 | .expect("Signing key has unexpected size"); 214 | hmac_signer.update(&result); 215 | 216 | result.extend_from_slice(&hmac_signer.finalize().into_bytes()); 217 | crate::b64_encode_url(&result) 218 | } 219 | 220 | /// Decrypts a ciphertext. Returns either `Ok(plaintext)` if decryption is 221 | /// successful or `Err(DecryptionError)` if there are any errors. Errors could 222 | /// include incorrect key or tampering with the data. 223 | pub fn decrypt(&self, token: &str) -> Result, DecryptionError> { 224 | let current_time = time::SystemTime::now() 225 | .duration_since(time::UNIX_EPOCH) 226 | .unwrap() 227 | .as_secs(); 228 | self._decrypt_at_time(token, None, current_time) 229 | } 230 | 231 | /// Decrypts a ciphertext with a time-to-live. Returns either `Ok(plaintext)` 232 | /// if decryption is successful or `Err(DecryptionError)` if there are any errors. 233 | /// Note if the token timestamp + ttl > current time, then this will also yield a 234 | /// DecryptionError. The ttl is measured in seconds. This is a relative time, not 235 | /// the absolute time of expiry. IE you would use 60 as a ttl_secs if you wanted 236 | /// tokens to be considered invalid after that time. 237 | pub fn decrypt_with_ttl(&self, token: &str, ttl_secs: u64) -> Result, DecryptionError> { 238 | let current_time = time::SystemTime::now() 239 | .duration_since(time::UNIX_EPOCH) 240 | .unwrap() 241 | .as_secs(); 242 | self._decrypt_at_time(token, Some(ttl_secs), current_time) 243 | } 244 | 245 | /// Decrypt a ciphertext with a time-to-live, and the current time. 246 | /// Returns either `Ok(plaintext)` if decryption is 247 | /// successful or `Err(DecryptionError)` if there are any errors. 248 | /// 249 | /// This function has the capacity to be used incorrectly or insecurely due to 250 | /// to the "current_time" parameter. current_time must be the systems time::SystemTime::now() 251 | /// with duraction_since(time::UNIX_EPOCH) as seconds. 252 | /// 253 | /// The motivation for a function like this is for your application to be able to test 254 | /// ttl expiry of tokens in your API. This allows you to pass in mock time data to assert 255 | /// correct behaviour of your application. Care should be taken to ensure you always pass in 256 | /// correct current_time values for deployments. 257 | #[inline] 258 | #[cfg(feature = "fernet_danger_timestamps")] 259 | pub fn decrypt_at_time( 260 | &self, 261 | token: &str, 262 | ttl: Option, 263 | current_time: u64, 264 | ) -> Result, DecryptionError> { 265 | self._decrypt_at_time(token, ttl, current_time) 266 | } 267 | 268 | #[cfg(not(feature = "rustcrypto"))] 269 | fn _decrypt_at_time( 270 | &self, 271 | token: &str, 272 | ttl: Option, 273 | current_time: u64, 274 | ) -> Result, DecryptionError> { 275 | let parsed = Self::_decrypt_parse(token, ttl, current_time)?; 276 | 277 | let hmac_pkey = openssl::pkey::PKey::hmac(&self.signing_key).unwrap(); 278 | let mut hmac_signer = 279 | openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), &hmac_pkey).unwrap(); 280 | hmac_signer.update(&parsed.message).unwrap(); 281 | let expected_hmac = hmac_signer.sign_to_vec().unwrap(); 282 | if !openssl::memcmp::eq(&expected_hmac, &parsed.hmac) { 283 | return Err(DecryptionError); 284 | } 285 | 286 | let plaintext = openssl::symm::decrypt( 287 | openssl::symm::Cipher::aes_128_cbc(), 288 | &self.encryption_key, 289 | Some(&parsed.iv), 290 | &parsed.ciphertext, 291 | ) 292 | .map_err(|_| DecryptionError)?; 293 | 294 | Ok(plaintext) 295 | } 296 | 297 | #[cfg(feature = "rustcrypto")] 298 | fn _decrypt_at_time( 299 | &self, 300 | token: &str, 301 | ttl: Option, 302 | current_time: u64, 303 | ) -> Result, DecryptionError> { 304 | let parsed = Self::_decrypt_parse(token, ttl, current_time)?; 305 | 306 | let mut hmac_signer = hmac::Hmac::::new_from_slice(&self.signing_key) 307 | .expect("Signing key has unexpected size"); 308 | hmac_signer.update(&parsed.message); 309 | 310 | let expected_hmac = hmac_signer.finalize().into_bytes(); 311 | 312 | use subtle::ConstantTimeEq; 313 | let hmac_matches: bool = parsed.hmac.ct_eq(&expected_hmac).into(); 314 | if !hmac_matches { 315 | return Err(DecryptionError); 316 | } 317 | 318 | let plaintext = 319 | cbc::Decryptor::::new_from_slices(&self.encryption_key, &parsed.iv) 320 | .unwrap() 321 | .decrypt_padded_vec_mut::(&parsed.ciphertext) 322 | .map_err(|_| DecryptionError)?; 323 | 324 | Ok(plaintext) 325 | } 326 | 327 | /// Parse the base64-encoded token into parts, verify timestamp TTL if given 328 | fn _decrypt_parse( 329 | token: &str, 330 | ttl: Option, 331 | current_time: u64, 332 | ) -> Result { 333 | let data = match b64_decode_url(token) { 334 | Ok(data) => data, 335 | Err(_) => return Err(DecryptionError), 336 | }; 337 | 338 | let mut input = Cursor::new(data); 339 | 340 | match input.read_u8() { 341 | Ok(0x80) => {} 342 | _ => return Err(DecryptionError), 343 | } 344 | 345 | let timestamp = input 346 | .read_u64::() 347 | .map_err(|_| DecryptionError)?; 348 | 349 | if let Some(ttl) = ttl { 350 | if timestamp + ttl < current_time { 351 | return Err(DecryptionError); 352 | } 353 | } 354 | 355 | if current_time + MAX_CLOCK_SKEW < timestamp { 356 | return Err(DecryptionError); 357 | } 358 | 359 | let mut iv = [0; 16]; 360 | input.read_exact(&mut iv).map_err(|_| DecryptionError)?; 361 | 362 | let mut rest = vec![]; 363 | input.read_to_end(&mut rest).unwrap(); 364 | if rest.len() < 32 { 365 | return Err(DecryptionError); 366 | } 367 | let ciphertext = rest[..rest.len() - 32].to_owned(); 368 | 369 | input 370 | .seek(SeekFrom::Current(-32)) 371 | .map_err(|_| DecryptionError)?; 372 | let mut hmac = [0u8; 32]; 373 | input.read_exact(&mut hmac).map_err(|_| DecryptionError)?; 374 | 375 | let message = input.get_ref()[..input.get_ref().len() - 32].to_vec(); 376 | Ok(ParsedToken { 377 | message, 378 | iv, 379 | ciphertext, 380 | hmac, 381 | }) 382 | } 383 | } 384 | 385 | #[cfg(test)] 386 | mod tests { 387 | use super::{DecryptionError, Fernet, MultiFernet}; 388 | use serde_derive::Deserialize; 389 | use std::collections::HashSet; 390 | use time::format_description::well_known::Rfc3339; 391 | use time::OffsetDateTime; 392 | 393 | #[derive(Deserialize)] 394 | struct GenerateVector<'a> { 395 | token: &'a str, 396 | now: &'a str, 397 | iv: Vec, 398 | src: &'a str, 399 | secret: &'a str, 400 | } 401 | 402 | #[derive(Deserialize)] 403 | struct VerifyVector<'a> { 404 | token: &'a str, 405 | now: &'a str, 406 | ttl_sec: u64, 407 | src: &'a str, 408 | secret: &'a str, 409 | } 410 | 411 | #[derive(Deserialize, Debug)] 412 | struct InvalidVector<'a> { 413 | token: &'a str, 414 | now: &'a str, 415 | ttl_sec: u64, 416 | secret: &'a str, 417 | } 418 | 419 | #[test] 420 | fn test_generate_vectors() { 421 | let vectors: Vec = 422 | serde_json::from_str(include_str!("../tests/generate.json")).unwrap(); 423 | 424 | for v in vectors { 425 | let f = Fernet::new(v.secret).unwrap(); 426 | let token = f._encrypt_from_parts( 427 | v.src.as_bytes(), 428 | OffsetDateTime::parse(v.now, &Rfc3339) 429 | .unwrap() 430 | .unix_timestamp() as u64, 431 | &v.iv, 432 | ); 433 | assert_eq!(token, v.token); 434 | } 435 | } 436 | 437 | #[test] 438 | fn test_verify_vectors() { 439 | let vectors: Vec = 440 | serde_json::from_str(include_str!("../tests/verify.json")).unwrap(); 441 | 442 | for v in vectors { 443 | let f = Fernet::new(v.secret).unwrap(); 444 | let decrypted = f._decrypt_at_time( 445 | v.token, 446 | Some(v.ttl_sec), 447 | OffsetDateTime::parse(v.now, &Rfc3339) 448 | .unwrap() 449 | .unix_timestamp() as u64, 450 | ); 451 | assert_eq!(decrypted, Ok(v.src.as_bytes().to_vec())); 452 | } 453 | } 454 | 455 | #[test] 456 | fn test_invalid_vectors() { 457 | let vectors: Vec = 458 | serde_json::from_str(include_str!("../tests/invalid.json")).unwrap(); 459 | 460 | for v in vectors { 461 | let f = Fernet::new(v.secret).unwrap(); 462 | let decrypted = f._decrypt_at_time( 463 | v.token, 464 | Some(v.ttl_sec), 465 | OffsetDateTime::parse(v.now, &Rfc3339) 466 | .unwrap() 467 | .unix_timestamp() as u64, 468 | ); 469 | assert_eq!(decrypted, Err(DecryptionError)); 470 | } 471 | } 472 | 473 | #[test] 474 | fn test_invalid() { 475 | let f = Fernet::new(&super::b64_encode_url(&vec![0; 32])).unwrap(); 476 | 477 | // Invalid version byte 478 | assert_eq!( 479 | f.decrypt(&crate::b64_encode_url(&b"\x81".to_vec())), 480 | Err(DecryptionError) 481 | ); 482 | // Timestamp too short 483 | assert_eq!( 484 | f.decrypt(&super::b64_encode_url( 485 | &b"\x80\x00\x00\x00".to_vec())), 486 | Err(DecryptionError) 487 | ); 488 | // Invalid base64 489 | assert_eq!(f.decrypt("\x00"), Err(DecryptionError)); 490 | } 491 | 492 | #[test] 493 | fn test_roundtrips() { 494 | let f = Fernet::new(&super::b64_encode_url(&vec![0; 32])).unwrap(); 495 | 496 | for val in [b"".to_vec(), b"Abc".to_vec(), b"\x00\xFF\x00\x00".to_vec()].iter() { 497 | assert_eq!(f.decrypt(&f.encrypt(val)), Ok(val.clone())); 498 | } 499 | } 500 | 501 | #[test] 502 | fn test_new_errors() { 503 | assert!(Fernet::new("axxx").is_none()); 504 | assert!(Fernet::new(&super::b64_encode_url(&vec![0, 33])).is_none()); 505 | assert!(Fernet::new(&super::b64_encode_url(&vec![0, 31])).is_none()); 506 | } 507 | 508 | #[test] 509 | fn test_generate_key() { 510 | let mut keys = HashSet::new(); 511 | for _ in 0..1024 { 512 | keys.insert(Fernet::generate_key()); 513 | } 514 | assert_eq!(keys.len(), 1024); 515 | } 516 | 517 | #[test] 518 | fn test_generate_key_roundtrips() { 519 | let k = Fernet::generate_key(); 520 | let f1 = Fernet::new(&k).unwrap(); 521 | let f2 = Fernet::new(&k).unwrap(); 522 | 523 | for val in [b"".to_vec(), b"Abc".to_vec(), b"\x00\xFF\x00\x00".to_vec()].iter() { 524 | assert_eq!(f1.decrypt(&f2.encrypt(val)), Ok(val.clone())); 525 | assert_eq!(f2.decrypt(&f1.encrypt(val)), Ok(val.clone())); 526 | } 527 | } 528 | 529 | #[test] 530 | fn test_multi_encrypt() { 531 | let key1 = Fernet::generate_key(); 532 | let key2 = Fernet::generate_key(); 533 | let f1 = Fernet::new(&key1).unwrap(); 534 | let f2 = Fernet::new(&key2).unwrap(); 535 | let f = MultiFernet::new(vec![ 536 | Fernet::new(&key1).unwrap(), 537 | Fernet::new(&key2).unwrap(), 538 | ]); 539 | assert_eq!(f1.decrypt(&f.encrypt(b"abc")).unwrap(), b"abc".to_vec()); 540 | assert_eq!(f2.decrypt(&f.encrypt(b"abc")), Err(DecryptionError)); 541 | } 542 | 543 | #[test] 544 | fn test_multi_decrypt() { 545 | let key1 = Fernet::generate_key(); 546 | let key2 = Fernet::generate_key(); 547 | let f1 = Fernet::new(&key1).unwrap(); 548 | let f2 = Fernet::new(&key2).unwrap(); 549 | let f = MultiFernet::new(vec![ 550 | Fernet::new(&key1).unwrap(), 551 | Fernet::new(&key2).unwrap(), 552 | ]); 553 | assert_eq!(f.decrypt(&f1.encrypt(b"abc")).unwrap(), b"abc".to_vec()); 554 | assert_eq!(f.decrypt(&f2.encrypt(b"abc")).unwrap(), b"abc".to_vec()); 555 | assert_eq!(f.decrypt("\x00"), Err(DecryptionError)); 556 | } 557 | 558 | #[test] 559 | #[should_panic] 560 | fn test_multi_no_fernets() { 561 | MultiFernet::new(vec![]); 562 | } 563 | 564 | #[test] 565 | fn test_multi_roundtrips() { 566 | let f = MultiFernet::new(vec![Fernet::new(&Fernet::generate_key()).unwrap()]); 567 | 568 | for val in [b"".to_vec(), b"Abc".to_vec(), b"\x00\xFF\x00\x00".to_vec()].iter() { 569 | assert_eq!(f.decrypt(&f.encrypt(val)), Ok(val.clone())); 570 | } 571 | } 572 | 573 | #[test] 574 | fn test_danger_timestamps() { 575 | use std::time; 576 | let key = Fernet::generate_key(); 577 | let f = Fernet::new(&key).unwrap(); 578 | let current_time = time::SystemTime::now() 579 | .duration_since(time::UNIX_EPOCH) 580 | .unwrap() 581 | .as_secs(); 582 | let good_time = current_time + 1; 583 | let exp_time = current_time + 60; 584 | assert_eq!( 585 | f._decrypt_at_time( 586 | &f._encrypt_at_time(b"abc", current_time), 587 | Some(30), 588 | good_time, 589 | ) 590 | .unwrap(), 591 | b"abc".to_vec() 592 | ); 593 | assert_eq!( 594 | f._decrypt_at_time( 595 | &f._encrypt_at_time(b"abc", current_time), 596 | Some(30), 597 | exp_time, 598 | ) 599 | .unwrap_err(), 600 | DecryptionError 601 | ); 602 | } 603 | } 604 | 605 | /// base64 had a habit of changing this a fair bit, so isolating these functions 606 | /// to reduce future code changes. 607 | /// 608 | pub(crate) fn b64_decode_url(input: &str) -> std::result::Result, base64::DecodeError> { 609 | base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(input.trim_end_matches('=')) 610 | } 611 | 612 | pub(crate) fn b64_encode_url(input: &Vec) -> String { 613 | base64::engine::general_purpose::URL_SAFE.encode(input) 614 | } 615 | -------------------------------------------------------------------------------- /tests/generate.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "token": "gAAAAAAdwJ6wAAECAwQFBgcICQoLDA0ODy021cpGVWKZ_eEwCGM4BLLF_5CV9dOPmrhuVUPgJobwOz7JcbmrR64jVmpU4IwqDA==", 4 | "now": "1985-10-26T01:20:00-07:00", 5 | "iv": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 6 | "src": "hello", 7 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 8 | } 9 | ] 10 | -------------------------------------------------------------------------------- /tests/invalid.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "desc": "incorrect mac", 4 | "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAl1-szkFVzXTuGb4hR8AKtwcaX1YdykQUFBQUFBQUFBQQ==", 5 | "now": "1985-10-26T01:20:01-07:00", 6 | "ttl_sec": 60, 7 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 8 | }, 9 | { 10 | "desc": "too short", 11 | "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPA==", 12 | "now": "1985-10-26T01:20:01-07:00", 13 | "ttl_sec": 60, 14 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 15 | }, 16 | { 17 | "desc": "invalid base64", 18 | "token": "%%%%%%%%%%%%%AECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAl1-szkFVzXTuGb4hR8AKtwcaX1YdykRtfsH-p1YsUD2Q==", 19 | "now": "1985-10-26T01:20:01-07:00", 20 | "ttl_sec": 60, 21 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 22 | }, 23 | { 24 | "desc": "payload size not multiple of block size", 25 | "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPOm73QeoCk9uGib28Xe5vz6oxq5nmxbx_v7mrfyudzUm", 26 | "now": "1985-10-26T01:20:01-07:00", 27 | "ttl_sec": 60, 28 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 29 | }, 30 | { 31 | "desc": "payload padding error", 32 | "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0ODz4LEpdELGQAad7aNEHbf-JkLPIpuiYRLQ3RtXatOYREu2FWke6CnJNYIbkuKNqOhw==", 33 | "now": "1985-10-26T01:20:01-07:00", 34 | "ttl_sec": 60, 35 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 36 | }, 37 | { 38 | "desc": "far-future TS (unacceptable clock skew)", 39 | "token": "gAAAAAAdwStRAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAnja1xKYyhd-Y6mSkTOyTGJmw2Xc2a6kBd-iX9b_qXQcw==", 40 | "now": "1985-10-26T01:20:01-07:00", 41 | "ttl_sec": 60, 42 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 43 | }, 44 | { 45 | "desc": "expired TTL", 46 | "token": "gAAAAAAdwJ6xAAECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAl1-szkFVzXTuGb4hR8AKtwcaX1YdykRtfsH-p1YsUD2Q==", 47 | "now": "1985-10-26T01:21:31-07:00", 48 | "ttl_sec": 60, 49 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 50 | }, 51 | { 52 | "desc": "incorrect IV (causes padding error)", 53 | "token": "gAAAAAAdwJ6xBQECAwQFBgcICQoLDA0OD3HkMATM5lFqGaerZ-fWPAkLhFLHpGtDBRLRTZeUfWgHSv49TF2AUEZ1TIvcZjK1zQ==", 54 | "now": "1985-10-26T01:20:01-07:00", 55 | "ttl_sec": 60, 56 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 57 | } 58 | ] 59 | -------------------------------------------------------------------------------- /tests/verify.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "token": "gAAAAAAdwJ6wAAECAwQFBgcICQoLDA0ODy021cpGVWKZ_eEwCGM4BLLF_5CV9dOPmrhuVUPgJobwOz7JcbmrR64jVmpU4IwqDA==", 4 | "now": "1985-10-26T01:20:01-07:00", 5 | "ttl_sec": 60, 6 | "src": "hello", 7 | "secret": "cw_0x689RpI-jtRR7oE8h_eQsKImvJapLeSbXpwF4e4=" 8 | } 9 | ] 10 | --------------------------------------------------------------------------------