{"id":13552852,"url":"https://github.com/michelonsouza/encrypt-storage","last_synced_at":"2025-05-15T06:05:21.573Z","repository":{"id":37086563,"uuid":"336439790","full_name":"michelonsouza/encrypt-storage","owner":"michelonsouza","description":"EncryptStorage provide a little more security in frontend","archived":false,"fork":false,"pushed_at":"2025-03-27T14:45:49.000Z","size":1988,"stargazers_count":277,"open_issues_count":6,"forks_count":13,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-15T06:04:39.255Z","etag":null,"topics":["crypto-js","encrypt-localstorage","encryption-decryption","localstorage","localstorage-wrapper","secure-ls","security-tools","typescript-library"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/michelonsouza.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"michelonsouza"}},"created_at":"2021-02-06T02:40:59.000Z","updated_at":"2025-04-17T18:59:48.000Z","dependencies_parsed_at":"2025-01-22T09:00:52.010Z","dependency_job_id":"fa56db96-da8c-49e0-bbe7-c328b900867e","html_url":"https://github.com/michelonsouza/encrypt-storage","commit_stats":{"total_commits":320,"total_committers":5,"mean_commits":64.0,"dds":"0.31562500000000004","last_synced_commit":"49e66a6f3f4e60ea6b13b52db19b7dfba6461ba7"},"previous_names":[],"tags_count":204,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michelonsouza%2Fencrypt-storage","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michelonsouza%2Fencrypt-storage/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michelonsouza%2Fencrypt-storage/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/michelonsouza%2Fencrypt-storage/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/michelonsouza","download_url":"https://codeload.github.com/michelonsouza/encrypt-storage/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254283339,"owners_count":22045140,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["crypto-js","encrypt-localstorage","encryption-decryption","localstorage","localstorage-wrapper","secure-ls","security-tools","typescript-library"],"created_at":"2024-08-01T12:02:11.859Z","updated_at":"2025-05-15T06:05:21.547Z","avatar_url":"https://github.com/michelonsouza.png","language":"TypeScript","funding_links":["https://github.com/sponsors/michelonsouza"],"categories":["TypeScript","security-tools"],"sub_categories":[],"readme":"\u003cimg width=\"400\" style=\"margin-bottom: 30px; max-width: 100%;\" src=\"./docs/resources/encrypt-storage-logo.png\" /\u003e\n\n[![stargazers count](https://img.shields.io/github/stars/michelonsouza/encrypt-storage?style=social)](https://github.com/michelonsouza/encrypt-storage) ![maintenance](https://img.shields.io/npms-io/maintenance-score/encrypt-storage) [![npm](https://img.shields.io/npm/dm/encrypt-storage)](https://www.npmjs.com/package/encrypt-storage) ![sponsors](https://img.shields.io/github/sponsors/michelonsouza?logo=github-sponsors) ![package size](https://img.shields.io/bundlephobia/min/encrypt-storage?color=%232ebd4f\u0026label=package%20size\u0026logo=npm) [![Code Size](https://img.shields.io/github/languages/code-size/michelonsouza/encrypt-storage)](https://github.com/michelonsouza/encrypt-storage) [![Version](https://img.shields.io/github/package-json/v/michelonsouza/encrypt-storage/main)](https://github.com/michelonsouza/encrypt-storage/blob/main/package.json#L3) [![Build Status](https://img.shields.io/github/actions/workflow/status/michelonsouza/encrypt-storage/ci.yml)](https://img.shields.io/github/actions/workflow/status/michelonsouza/encrypt-storage/ci.yml) [![Coverage Status](https://coveralls.io/repos/github/michelonsouza/encrypt-storage/badge.svg)](https://coveralls.io/github/michelonsouza/encrypt-storage) [![License](https://img.shields.io/npm/l/encrypt-storage?color=%230e7fc0\u0026label=license)](https://github.com/michelonsouza/encrypt-storage/blob/main/LICENSE) [![Node CI](https://github.com/michelonsouza/encrypt-storage/actions/workflows/ci.yml/badge.svg)](https://github.com/michelonsouza/encrypt-storage/actions/workflows/codeql-analysis.yml) [![CodeQL](https://github.com/michelonsouza/encrypt-storage/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/michelonsouza/encrypt-storage/actions/workflows/codeql-analysis.yml) [![npm published](https://github.com/michelonsouza/encrypt-storage/actions/workflows/release.yml/badge.svg)](https://github.com/michelonsouza/encrypt-storage/actions/workflows/release.yml) [![jsdelivery](https://img.shields.io/jsdelivr/npm/hm/encrypt-storage)](https://www.jsdelivr.com/package/npm/encrypt-storage)\n\nOBS: This is the new version of Encrypt Storage, it has breaking changes that will not be described below. For version `1.3.X` documentation, access this [link](./docs/README_V1.md).\n\nThe `Encrypt Storage` is a `wrapper` for native `Storage` of browser.\n\nUsing the [`crypto-js`](https://github.com/brix/crypto-js) library as an encryption engine, it saves the encrypted data on the `selected storage` in the same way as the native `Storage`.\n\n\u003e **HELP THIS PROJECT**: Your Github `star` can help this project. Leave a `star`, it costs nothing.\n\n\u003e **⚠️ IMPORTANT**: Nothing on the front end is entirely secure. The library's proposal is to make it difficult for the user to see the data through the console, but as the secret key is on the front end, if the user searches hard enough, he will end up finding it. Just to make it clear that nothing is completely secure on the front end. Thank you for your attention.\n\n- [Encrypt Storage](#encrypt-storage)\n  - [Features](#features)\n  - [Installing](#installing)\n  - [Options](#options)\n  - [Usage](#usage)\n    - [Conventions](#conventions)\n    - [Parameters](#parameters)\n    - [CommonJS](#commonjs)\n    - [JS Import (ES6+)](#js-import-es6)\n    - [Multiple instances](#multiple-instances)\n    - [Options implementation](#options-implementation)\n      - [_prefix_](#prefix)\n      - [_storageType_](#storagetype)\n      - [_stateManagementUse_](#statemanagementuse)\n      - [_encAlgorithm_](#encalgorithm)\n      - [_notifyHandler_](#notifyhandler)\n      - [_doNotEncryptValues_](#doNotEncryptValues)\n      - [_doNotParseValues_](#doNotParseValues)\n    - [Methods](#methods)\n      - [_setItem_](#setitem)\n      - [_setMultipleItems_](#setmultipleitems)\n      - [_getItem_](#getitem)\n      - [_getMultipleItems_](#getmultipleitems)\n      - [_removeItem_](#removeitem)\n      - [_removeMultipleItems_](#removemultipleitems)\n      - [_getItemFromPattern_](#getitemfrompattern)\n      - [_removeItemFromPattern_](#removeitemfrompattern)\n      - [_key_](#key)\n      - [_length_](#length)\n      - [_clear_](#clear)\n      - [_encryptString_](#encryptstring)\n      - [_decryptString_](#decryptstring)\n      - [_encryptValue_](#encryptvalue)\n      - [_decryptValue_](#decryptvalue)\n      - [_hash_](#hash)\n      - [_md5Hash_](#md5hash)\n    - [NextJS](#nextjs)\n    - [AsyncEncryptStorage](#asyncencryptstorage)\n    - [AWS Amplify](#aws-amplify)\n    - [Cookie](#cookie)\n      - [_set_](#set)\n      - [_get_](#get)\n      - [_remove_](#remove)\n    - [State Management Persisters](#state-management-persisters)\n      - [_vuex-persist_](#vuex-persist)\n      - [_redux-persist_](#redux-persist)\n      - [_pinia-plugin-persist_](#pinia-plugin-persist)\n      - [_pinia-plugin-persistedstate_](#pinia-plugin-persistedstate)\n- [License](#license)\n\n## Features\n\n- Save encrypted data in `localStorage`, `sessionStorage` and `cookies`\n- Recover encrypted data with `get` functions\n- Use in the same way as native `Web Storage` (localStorage and sessionStorage)\n- If you use the `stateManagementUse` option, the data acquired in `get` functions will `not` have their return transformed into `Javascript objects`.\n- Use with `stateManagement` persisters (`vuex-persist` and `redux-persist`\\*)\n\n## Installing\n\n\u003e To run this project in the development mode, you'll need to have a basic environment with NodeJs and Yarn installed.\n\nUsing npm:\n\n```bash\n$ npm install encrypt-storage\n```\n\nOr yarn:\n\n```bash\n$ yarn add encrypt-storage\n```\n\nUsing `CDNs`:\n\n`Unpkg`:\n\n```html\n\u003cbody\u003e\n  \u003c!-- ...after other codes --\u003e\n  \u003cscript src=\"https://unpkg.com/encrypt-storage@latest/dist/index.js\"\u003e\u003c/script\u003e\n  \u003cscript\u003e\n    const encryptStorage = new EncryptStorage('secret-key-value');\n  \u003c/script\u003e\n\u003c/body\u003e\n```\n\nOBS: `Unpkg` doesn't have a counter badge\n\n`JS Delivery`:\n\n```html\n\u003cbody\u003e\n  \u003c!-- ...after other codes --\u003e\n  \u003cscript src=\"https://cdn.jsdelivr.net/npm/encrypt-storage@latest/dist/index.js\"\u003e\u003c/script\u003e\n  \u003cscript\u003e\n    const encryptStorage = new EncryptStorage('secret-key-value');\n  \u003c/script\u003e\n\u003c/body\u003e\n```\n\n## Options\n\nThe `options` object is optional and consists of the following properties:\n\n| Property name        | Default        | Type                                | required |\n| -------------------- | -------------- | ----------------------------------- | -------- |\n| `prefix`             | `''`           | `string`                            | `false`  |\n| `storageType`        | `localStorage` | [StorageType](./src/types.ts#L3)    | `false`  |\n| `encAlgorithm`       | `AES`          | [EncAlgorithm](./src/types.ts#L1)   | `false`  |\n| `notifyHandler`      | `undefined`    | [NotifyHandler](./src/types.ts#L23) | `false`  |\n| `stateManagementUse` | `false`        | `boolean`                           | `false`  |\n| `doNotEncryptValues` | `false`        | `boolean`                           | `false`  |\n| `doNotParseValues`   | `false`        | `boolean`                           | `false`  |\n\n## Usage\n\n### Conventions\n\nCreate a `file` containing the `EncryptStorage` instance in a `utils` folder or folder of your choice. It is recommended to use it as a `singleton` for better use of the library.\n\n\u003e Directory Layout\n\n```\n📦 src\n ┣ 📂 utils\n ┃ ┗ 📜 storage.ts\n ┗ 📜 index.ts\n ...\n```\n\n### Parameters\n\n_secretKey_: **required** = A string containing at least 10 characters;\n\n**NOTE**: If you are using a `SPA` model (vue, react or angular) prefer to store this information in your application's `.env` file.\n\n_options_: **optional** = An object as described above and which will be shown below;\n\n### CommonJS\n\n```typescript\nconst { EncryptStorage } = require('encrypt-storage');\n\n// Example of secret_key variable in an .env file\n// const encryptStorage = new EncryptStorage(process.env.SECRET_KEY, options);\nconst encryptStorage = new EncryptStorage('secret-key-value', options);\n\nmodule.exports = encryptStorage;\n```\n\n### JS Import (ES6+)\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\n// Example of secret_key variable in an .env file\n// const encryptStorage = new EncryptStorage(process.env.SECRET_KEY, options);\nexport const encryptStorage = new EncryptStorage('secret-key-value', options);\n```\n\n### Multiple instances\n\nTo use `multiple instances`, it is `strictly necessary` to pass the `prefix` to `all` of them. As shown below:\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage1 = new EncryptStorage('secret-key-value', {\n  prefix: '@instance1',\n});\n\nexport const encryptStorage2 = new EncryptStorage('secret-key-value', {\n  prefix: '@instance2',\n});\n\nencryptStorage1.setItem('any-key', 'any-value');\nencryptStorage2.setItem('any-key', 'any-value');\n```\n\nin your `storage`:\n\n| Key                  | Value                                      |\n| -------------------- | ------------------------------------------ |\n| `@instance1:any-key` | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n| `@instance2:any-key` | `U2FsdGVkX1/w4QaIcyq5521ZXB5pqw2KEwOH+`... |\n\n### Options implementation\n\n#### _prefix_\n\ndefault `''` - is optional and is the prefix of all keys used in the selected storage as shown below:\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new EncryptStorage('secret-key-value', {\n  prefix: '@example',\n});\n```\n\n#### _storageType_\n\ndefault `localStorage` - is the type of storage that will be used, at the moment only `localStorage` and `sessionStorage` are allowed:\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new EncryptStorage('secret-key-value', {\n  storageType: 'sessionStorage',\n});\n```\n\n#### _stateManagementUse_\n\n**NOTE**: This property is also `required` for completely `identical` use to the browser's native. Therefore, it will `not` have the native library behavior when `parsing` data to `javascript objects` or type casting such as `'true'` being a `boolean`, `'2'` being a `number`, etc.\n\ndefault `false` - is a `boolean` value that, when true allows the use of it with `vuex-persist` and `redux-persist`:\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new EncryptStorage('secret-key-value', {\n  stateManagementUse: true,\n});\n```\n\n#### _encAlgorithm_\n\ndefault `AES` - Is the selected encryption algorithm.:\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new EncryptStorage('secret-key-value', {\n  encAlgorithm: 'Rabbit',\n});\n```\n\n#### _doNotEncryptValues_\n\ndefault `false` - This option `NOT` encrypt values, but use those options like `prefix` our `multiple-instances`.:\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new EncryptStorage('secret-key-value', {\n  doNotEncryptValues: true,\n});\n```\n\n#### _doNotParseValues_\n\ndefault `false` - This option `NOT` parse values, but use those options like `prefix` our `multiple-instances`.:\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new EncryptStorage('secret-key-value', {\n  doNotParseValues: true,\n});\n\nencryptStorage.setItem('key', JSON.stringfy({ name: 'John Doe' }));\n\nconst value = JSON.parse(encryptStorage.getItem('key')); // { name: 'John Doe' }\n```\n\n\u003e NOTE: This option `does not` `JSON.stringify` or `JSON.parse` the data, making `return typing` useless or unnecessary.\n\u003e **This is similar to standard browser behavior.**\n\n#### _notifyHandler_\n\ndefault `undefined` - is a `function` that is `called` every time another `EncryptStorage function` is `called`. Good for logging API and monitoring `localStorage/sessionStorage`.:\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new EncryptStorage('secret-key-value', {\n  notifyHandler: (params: NotifyHandlerParams) =\u003e console.info({ params }),\n});\n```\n\nconsole:\n\n```bash\n{\n  params: {\n    type: 'get'\n    key: 'any-key',\n    value: 'any-value',\n    index: 1,\n  }\n}\n```\n\n**OBS**: Check [NotifyHandlerParams](./src/types.ts#L7) for more information.\n\n### Methods\n\nFrom here, we will have the following code as the EncryptStorage instance model:\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new EncryptStorage('secret-key-value', {\n  prefix: '@example',\n});\n```\n\n#### _setItem_\n\nAdd `key` and `encrypted` value to selected `storage`.\n\n```typescript\nencryptStorage.setItem('token', 'edbe38e0-748a-49c8-9f8f-b68f38dbe5a2');\nencryptStorage.setItem(\n  'token-not-encrypted',\n  'edbe38e0-748a-49c8-9f8f-b68f38dbe5a2',\n  true,\n);\n```\n\nin your `storage`:\n\n| Key                            | Value                                      |\n| ------------------------------ | ------------------------------------------ |\n| `@example:token`               | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n| `@example:token-not-encrypted` | `edbe38e0-748a-49c8-9f8f-b68f38dbe5a2`     |\n\n#### _setMultipleItems_\n\nAdd `keys` and `encrypted` values to selected `storage`.\n\n```typescript\nencryptStorage.setMultipleItems([\n  ['token', 'edbe38e0-748a-49c8-9f8f-b68f38dbe5a2'],\n  [\n    'user',\n    {\n      id: '123456',\n      name: 'John Doe',\n    },\n  ],\n]);\n```\n\nin your `storage`:\n\n| Key              | Value                                      |\n| ---------------- | ------------------------------------------ |\n| `@example:token` | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n| `@example:user`  | `U2FsdGVkX1/tT67hnb*\\afcb`...              |\n\n#### _getItem_\n\nReturns the value `decrypted` or `undefined` by the `key` passed by `parameter`. Default type is `any`;\n\n**NOTE**: It is possible to pass a `generics` (typescript case) to obtain a consistent and typed return for better use in the `typescript`.\n\n```typescript\nconst value = encryptStorage.getItem\u003cT = any\u003e('token');\nconst value2 = encryptStorage.getItem\u003cT = any\u003e('token-not-encrypted', true);\n```\n\nresult of `getItem`:\n\n```typescript\nconst value = 'edbe38e0-748a-49c8-9f8f-b68f38dbe5a2';\nconst value2 = 'edbe38e0-748a-49c8-9f8f-b68f38dbe5a2';\n```\n\n#### _getMultipleItems_\n\nReturns the key value pairs `decrypted` or `undefined` by the `keys` passed by `parameter`.;\n\n```typescript\nconst value = encryptStorage.getMultipleItems(['token', 'user', 'any-key']);\n```\n\nresult of `getMultipleItems`:\n\n```typescript\nconst value = {\n  token: 'edbe38e0-748a-49c8-9f8f-b68f38dbe5a2',\n  user: {\n    id: '123456',\n    name: 'John Doe',\n  },\n  'any-key': undefined,\n};\n```\n\n#### _removeItem_\n\nRemove item from selected `storage`.\n\nin your `storage`:\n\n| Key              | Value                                      |\n| ---------------- | ------------------------------------------ |\n| `@example:token` | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n\n```typescript\nencryptStorage.removeItem('token');\n```\n\nnow in your `storage`:\n\n| Key | Value |\n| --- | ----- |\n| ` ` | ` `   |\n\n#### _removeMultipleItems_\n\nRemove items from selected `storage`.\n\nin your `storage`:\n\n| Key              | Value                                      |\n| ---------------- | ------------------------------------------ |\n| `@example:token` | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n| `@example:user`  | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n\n```typescript\nencryptStorage.removeMultipleItems(['token', 'user']);\n```\n\nnow in your `storage`:\n\n| Key | Value |\n| --- | ----- |\n| ` ` | ` `   |\n\n#### _getItemFromPattern_\n\nReturns an `object` containing the `original` keys (no prefix) and `decrypted` values or `undefined` when no value found.\n\nin your `storage`:\n\n| Key                          | Value                                      |\n| ---------------------------- | ------------------------------------------ |\n| `@example:fruit:apple`       | `U2FsdGVkX1/2KEwOH+w4QaIc`                 |\n| `@example:fruit:grape`       | `U2FsdGVkX1/yq5521ZXB5pqw`                 |\n| `@example:vegetable:lettuce` | `U2FsdGVkX1/tT67hnb*\\afcb`                 |\n| `@example:token`             | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n\n```typescript\nconst values = encryptStorage.getItemFromPattern('fruit');\n```\n\nresult of `getItemFromPattern`:\n\n```typescript\nconst values = {\n  'fruit:apple': 'apple',\n  'fruit:grape': 'grape',\n};\n```\n\n#### _removeItemFromPattern_\n\nRemoves `all` items that have the `pattern` passed by `parameter` from the selected `storage`.\n\nin your `storage`:\n\n| Key                          | Value                                      |\n| ---------------------------- | ------------------------------------------ |\n| `@example:fruit:apple`       | `U2FsdGVkX1/2KEwOH+w4QaIc`                 |\n| `@example:fruit:grape`       | `U2FsdGVkX1/yq5521ZXB5pqw`                 |\n| `@example:vegetable:lettuce` | `U2FsdGVkX1/tT67hnb*\\afcb`                 |\n| `@example:token`             | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n\n```typescript\nencryptStorage.removeItemFromPattern('fruit');\n```\n\nnow in your `storage`:\n\n| Key                          | Value                                      |\n| ---------------------------- | ------------------------------------------ |\n| `@example:vegetable:lettuce` | `U2FsdGVkX1/tT67hnb*\\afcb`                 |\n| `@example:token`             | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n\n#### _key_\n\nReturns the `key` corresponding to the `index` passed by `parameter` or `null`.\n\nin your `storage`:\n\n| Key                          | Value                                      |\n| ---------------------------- | ------------------------------------------ |\n| `@example:vegetable:lettuce` | `U2FsdGVkX1/tT67hnb*\\afcb`                 |\n| `@example:token`             | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n\n```typescript\nconst key = encryptStorage.key(0);\n```\n\nresult of `key`:\n\n```bash\n'@example:vegetable:lettuce'\n```\n\n#### _length_\n\nReturns the `amount` of values from the selected `storage`.\n\nin your `storage`:\n\n| Key                          | Value                                      |\n| ---------------------------- | ------------------------------------------ |\n| `@example:vegetable:lettuce` | `U2FsdGVkX1/tT67hnb*\\afcb`                 |\n| `@example:token`             | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n\n```typescript\nconst length = encryptStorage.length;\n```\n\nresult of `length`:\n\n```bash\n2\n```\n\n#### _clear_\n\nRemoves `all` keys and values from the selected `storage`.\n\nin your `storage`:\n\n| Key                          | Value                                      |\n| ---------------------------- | ------------------------------------------ |\n| `@example:vegetable:lettuce` | `U2FsdGVkX1/tT67hnb*\\afcb`                 |\n| `@example:token`             | `U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw`... |\n\n```typescript\nencryptStorage.clear();\n```\n\nnow in your `storage`:\n\n| Key | Value |\n| --- | ----- |\n| ` ` | ` `   |\n\n#### _encryptString_\n\nEncrypts a `string` passed by `parameter`.\n\n```typescript\nconst value = encryptStorage.encryptString('John Doe');\n```\n\nresult of `encryptString`:\n\n```typescript\nconst value = 'U2FsdGVkX1/tT67hnb*afcb';\n```\n\n#### _decryptString_\n\nDecrypts a `string` passed by `parameter`.\n\n```typescript\nconst value = encryptStorage.decryptString('U2FsdGVkX1/tT67hnb*afcb');\n```\n\nresult of `decryptString`:\n\n```typescript\nconst value = 'John Doe';\n```\n\n#### _encryptValue_\n\nEncrypts a `value` passed by `parameter`.\n\n```typescript\nconst value = encryptStorage.encryptValue({\n  id: '123456',\n  name: 'John Doe',\n});\n```\n\nresult of `encryptValue`:\n\n```typescript\nconst value = 'U2FsdGVkX1/tT67hnb*afcb';\n```\n\n#### _decryptValue_\n\nDecrypts a `string` passed by `parameter`.\n\n```typescript\n// Using typescript\ninterface User {\n  id: string;\n  name: string;\n}\n\nconst value = encryptStorage.decryptValue\u003cUser\u003e('U2FsdGVkX1/tT67hnb*afcb');\n```\n\nresult of `decryptValue`:\n\n```typescript\nconst value = {\n  id: '123456',\n  name: 'John Doe',\n};\n```\n\n#### _hash_\n\nEncrypts a `string` passed by `parameter` with `SHA256` encryptation.\n\n```typescript\nconst value = encryptStorage.hash('John Doe');\n```\n\nresult of `hashed value`:\n\n```typescript\nconst value =\n  '52bec733f066a11182798f4defec648ea00e374a1cda73111a443b295fd8e028';\n```\n\n#### _md5Hash_\n\nEncrypts a `string` passed by `parameter` with `MD5` encryptation.\n\n```typescript\nconst value = encryptStorage.md5Hash('John Doe');\n```\n\nresult of `hashed value`:\n\n```typescript\nconst value = '284e512750fb7d41f1cc5284a2c56a13';\n```\n\n### NextJS\n\nWhen used in NextJS, validation must be done.\n\nexample:\n\n```typescript\n// utils/storage.(ts|js)\nimport { EncryptStorage } from 'encrypt-storage';\n\nconst encryptStorage = (): EncryptStorage | null =\u003e {\n  const isInClientSide =\n    typeof window !== 'undefined' \u0026\u0026 typeof window?.self !== 'undefined';\n\n  if (isInClientSide) {\n    return new EncryptStorage(\n      String(process.env.NEXT_PUBLIC_STORAGE_SECRET),\n      // options,\n    );\n  }\n\n  return null;\n};\n```\n\nusage:\n\n```typescript\n'use client';\nimport { encryptStorage } from '../utils/storage.ts';\n\n// ...rest of code\nencryptStorage()?.setItem('any-key', { name: 'John Doe', age: 40 });\n```\n\n### AsyncEncryptStorage\n\nEncryptStorage can also be used asynchronously, simply using its corresponding version already exported by the library.\n\n**NOTE**: This functionality has its usefulness revealed in the context of redux-persist, shown below.\n\nexample:\n\n```typescript\nimport { AsyncEncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new AsyncEncryptStorage('secret-key-value', options);\n\nasync function getDecryptedValue('key'): Promise\u003cany | undefined\u003e {\n  const value = await encryptStorage.getItem('key');\n}\n```\n\n### Cookie\n\nEncryptstorage can also be used to encrypt data in cookies. See below for ways to use it.\n\n#### _set_\n\nSet a `encrypted` cookie value passed by parameter.\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\nconst encryptStorage = new EncryptStorage('secret-key-value', {\n  prefix: '@encrypt-storage',\n});\n\nencryptStorage.cookie.set('any-key', { value: 'any-value' });\n\n// document.cookie\n// any-key=U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw...\n```\n\nYou can pass parameters to the set method, which are normally used in cookies. View params in [CookieOptions](./src/types.ts#L62).\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\nconst encryptStorage = new EncryptStorage('secret-key-value', {\n  prefix: '@encrypt-storage',\n});\n\nencryptStorage.cookie.set(\n  'any-key',\n  { value: 'any-value' },\n  {\n    path: '/',\n    domain: 'example.com',\n    expires: new Date(Date.now() + 86400000),\n    secure: true,\n    sameSite: 'strict',\n  },\n);\n\n// document.cookie\n// any-key=U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw; path=/; domain=example.com; expires=Tue, 24 Dec 2024 18:51:07 GMT; secure\n```\n\n#### _get_\n\nSet a `encrypted` cookie value passed by parameter.\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\nconst encryptStorage = new EncryptStorage('secret-key-value', {\n  prefix: '@encrypt-storage',\n});\n\nconst value = { value: 'any-value' };\n\nencryptStorage.cookie.set('any-key', value);\n\n// document.cookie\n// any-key=U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw...\n\nconst decryptedValue = encryptStorage.cookie.get('any-key');\n\n// { value: 'any-value' }\n```\n\n#### _remove_\n\nSet a `encrypted` cookie value passed by parameter.\n\n```typescript\nimport { EncryptStorage } from 'encrypt-storage';\nconst encryptStorage = new EncryptStorage('secret-key-value', {\n  prefix: '@encrypt-storage',\n});\n\nconst value = { value: 'any-value' };\n\nencryptStorage.cookie.set('any-key', value);\n\n// document.cookie\n// any-key=U2FsdGVkX1/2KEwOH+w4QaIcyq5521ZXB5pqw...\n\nencryptStorage.cookie.remove('any-key');\n\n// document.cookie\n// ''\n```\n\n### AWS Amplify\n\nIn the case of `aws-amplify`, if you want to use the facility of not needing to use `JSON.parse` in the rest of the application, prefer to create an instance within the `amplify` configuration file, as follows:\n\n```typescript\nimport Amplify from 'aws-amplify';\nimport { EncryptStorage } from 'encrypt-storage';\n\nconst encryptStorage = new EncryptStorage('secret-key-value', {\n  ...,\n  stateManagementUse: true,\n});\n\n...\n\nAmplify.configure({\n  Auth: {\n    ...,\n    storage: encryptStorage,\n  },\n});\n```\n\n### State Management Persisters\n\nThis library can be used to encrypt data from `state management persisters` like [vuex-persist](https://www.npmjs.com/package/vuex-persist), [redux-persist](https://www.npmjs.com/package/redux-persist) and [pinia-plugin-persist](https://www.npmjs.com/package/pinia-plugin-persist). Below are their respective implementations:\n\n**NOTE**: the `stateManagementUse` option must be used in the `EncryptStorage` instance to work `correctly`.\n\n#### _vuex-persist_\n\n```typescript\nimport VuexPersistence from 'vuex-persist';\n\nimport { encryptStorage } from 'path/to/encryptStorage';\n\nconst vuexLocal = new VuexPersistence\u003cRootState\u003e({\n  storage: encryptStorage,\n});\n```\n\n#### _redux-persist_\n\n```typescript\n// ...\nimport { AsyncEncryptStorage } from 'encrypt-storage';\n\nexport const encryptStorage = new AsyncEncryptStorage('secret-key-value', options);\n\nconst persistConfig = {\n  key: 'root',\n  storage: encryptStorage,\n  whitelist: ['navigation'],\n  ...\n};\n```\n\n#### _pinia-plugin-persist_\n\n```typescript\n// ...\nimport { encryptStorage } from 'path/to/encryptStorage';\n\nexport const useUserStore = defineStore('storeUser', {\n  state() {\n    return {\n      firstName: 'S',\n      lastName: 'L',\n      accessToken: 'xxxxxxxxxxxxx',\n    };\n  },\n  persist: {\n    enabled: true,\n    strategies: [\n      {\n        storage: encryptStorage,\n        paths: ['accessToken'],\n      },\n    ],\n  },\n});\n```\n\n#### _pinia-plugin-persistedstate_\n\n```typescript\nimport { defineStore } from 'pinia'\nimport { encryptStorage } from 'path/to/encryptStorage';\n\nexport const useStore = defineStore('store', {\n  state: () =\u003e ({\n    return: {\n      first: 'John',\n      last: 'Doe',\n      accessToken: 'xxxxxxxxxxxxx'.\n    },\n  }),\n  persist: {\n    storage: encryptStorage,\n    paths: ['accessToken'],\n  },\n});\n```\n\n# License\n\n[MIT License](/LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichelonsouza%2Fencrypt-storage","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmichelonsouza%2Fencrypt-storage","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmichelonsouza%2Fencrypt-storage/lists"}