Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encryption + Decryption Examples #54

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion conditional-signing/browser/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ In this directory, `conditional-signing/browser`, run `yarn` to install the proj

If you already have a Lit PKP that you'd like to use, you can copy the contents of the provided `.env.example` to a `.env` file to specify it. If you don't have a PKP, or wish to use a new one for this example, then you can skip this step and one will be created for you when you run this example.

**NOTE** In order for a new Lit PKP to minted for you, you **must** have `testLPX` tokens. You can receive some `testLPX` using the faucet available [here](https://faucet.litprotocol.com/).
**NOTE** In order for a new Lit PKP to minted for you, you **must** have `tstLPX` tokens. You can receive some `tstLPX` using the faucet available [here](https://faucet.litprotocol.com/).

```
cp .env.example .env
Expand Down
1 change: 1 addition & 0 deletions encryption-decryption/browser/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_CAPACITY_CREDIT_TOKEN_ID=
18 changes: 18 additions & 0 deletions encryption-decryption/browser/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
24 changes: 24 additions & 0 deletions encryption-decryption/browser/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
51 changes: 51 additions & 0 deletions encryption-decryption/browser/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# String Encryption/Decryption Using the Lit SDK in the Browser

This code example demonstrates how the Lit SDK can be used to encrypt and decrypt data within a browser.

## Running this Example

### Install the Dependencies

In this directory, `encryption-decryption/browser`, run `yarn` to install the project dependencies.

### Specifying Your Lit Capacity Credit's Token ID

If you already have a Lit Capacity Credit that you'd like to use, you can copy the contents of the provided `.env.example` to a `.env` file to specify it. If you don't have a Capacity Credit, or wish to use a new one for this example, then you can skip this step and one will be minted for you when you run this example.

**NOTE** In order for a new Lit Capacity Credit to be minted, you **must** have `tstLPX` tokens. You can receive some `tstLPX` using the faucet available [here](https://faucet.litprotocol.com/).

```
cp .env.example .env
```

Your `.env` file should look like:

```
VITE_LIT_CAPACITY_CREDIT_TOKEN_ID=yourCapacityCreditTokenId
```

### Starting the Example

In this directory, `encryption-decryption/browser`, run `yarn dev` to bundle all of this code and serve the HTML file at: [http://localhost:5173](http://localhost:5173).

Before you click the buttons, open up the JavaScript console in your browser so you can see the output of this example.

After typing in the text you want to encrypt, clicking the `Encrypt String` button will:

1. You will be prompted by your wallet (i.e. MetaMask) to connect an account to the site
2. After connecting an account, the console should display a successful connection to the Lit network and the encrypted `ciphertext` and `dataToEncryptHash` that will later be used to decrypt the string

After encrypting the string, clicking the `Decrypt String` button will:

1. Connect you to the Lit network and LitContracts client
2. If you did not provide a Capacity Credit token ID, you will be prompted by your wallet to mint a new one
3. You will then be prompted by your wallet to sign a message. This message will create a `capacityDelegationAuthSig`, which is used to pay for decrypting data ([and other functionality](https://developer.litprotocol.com/paying-for-lit/capacity-credits)) on the Lit network
4. You will then be prompted by your wallet to sign another one final message. This message is the SIWE message that will derive your address from to use for the conditional check of whether or not you are permitted to decrypt the data

The full example should look something like:


https://github.com/user-attachments/assets/64bcc6a9-e35e-48b2-969f-e05b6c22907f



26 changes: 26 additions & 0 deletions encryption-decryption/browser/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
<style>
body, html {
margin: 0;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#root {
width: 100%;
text-align: center;
}
</style>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
39 changes: 39 additions & 0 deletions encryption-decryption/browser/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "quick-start",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
"@esbuild-plugins/node-modules-polyfill": "^0.2.2",
"@lit-protocol/auth-helpers": "^6.4.10",
"@lit-protocol/contracts-sdk": "^6.4.10",
"@lit-protocol/lit-node-client": "^6.4.10",
"@lit-protocol/types": "^6.4.10",
"@simplewebauthn/browser": "^10.0.0",
"@vitejs/plugin-react-swc": "^3.7.0",
"ethers": "v5",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"rollup-plugin-polyfill-node": "^0.13.0",
"vite-plugin-node-polyfills": "^0.22.0"
},
"devDependencies": {
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^7.13.1",
"@typescript-eslint/parser": "^7.13.1",
"@vitejs/plugin-react": "^4.3.1",
"eslint": "^8.57.0",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-refresh": "^0.4.7",
"typescript": "^5.5.3",
"vite": "^5.3.1"
}
}
1 change: 1 addition & 0 deletions encryption-decryption/browser/public/vite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
42 changes: 42 additions & 0 deletions encryption-decryption/browser/src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}

.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}

@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}

.card {
padding: 2em;
}

.read-the-docs {
color: #888;
}
66 changes: 66 additions & 0 deletions encryption-decryption/browser/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { useState } from "react";
import { encryptToString } from "./encryptString";
import { decryptString } from "./decryptString";

function App() {
const [encryptedResult, setEncryptedResult] = useState<{
ciphertext: string;
dataToEncryptHash: string;
}>();
const [toEncrypt, setToEncrypt] = useState("");

const handleInputChange = (e: any) => {
setToEncrypt(e.target.value);
};

const handleEncrypt = async () => {
try {
const result = await encryptToString(toEncrypt);
setEncryptedResult(result);
} catch (error) {
console.error("Encryption failed:", error);
}
};

return (
<>
<div className="card">
<hr />
<h3>Encrypt a String</h3>
<label htmlFor="input">Enter a string to encrypt:</label>
<br></br>
<input
type="text"
id="input"
value={toEncrypt}
onChange={handleInputChange}
></input>
<br></br>
<button onClick={async () => await handleEncrypt()}>
Encrypt String
</button>
<h5> Check the browser console! </h5>
<hr />
</div>

<div className="card">
<hr />
<h3>Decrypt a String</h3>
<button
onClick={async () =>
await decryptString(
encryptedResult!.ciphertext,
encryptedResult!.dataToEncryptHash
)
}
>
Decrypt String
</button>
<h5> Check the browser console! </h5>
<hr />
</div>
</>
);
}

export default App;
1 change: 1 addition & 0 deletions encryption-decryption/browser/src/assets/react.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading