To get started with file decryption, make sure you already have a file CID that you want to decrypt, or else follow the previous code example => "Browser Encryption Upload"
Step 1:Follow this React documentation and Create a new react app using the following command
npx create-react-app lighthouse-app
and go into the new repository using
cd lighthouse-app
Step 2.1:Install the Lighthouse SDK
npm i @lighthouse-web3/sdk
The following code will decrypt an image file previously uploaded to Lighthouse with encryption. You need to have a browser wallet like Metamask to sign from your wallet.
Step 3.1: Paste the CID of the file you want to decrypt in the decrypt function below as the cid variable.
import React from"react"import {ethers} from'ethers'import lighthouse from'@lighthouse-web3/sdk'functionApp() {const [fileURL,setFileURL] =React.useState(null)constencryptionSignature=async() =>{constprovider=newethers.providers.Web3Provider(window.ethereum)constsigner=provider.getSigner()constaddress=awaitsigner.getAddress()constmessageRequested= (awaitlighthouse.getAuthMessage(address)).data.messageconstsignedMessage=awaitsigner.signMessage(messageRequested)return({ signedMessage: signedMessage, publicKey: address }) }/* Decrypt file */constdecrypt=async() =>{// Fetch file encryption keyconstcid="QmVkbVeTGA7RHgvdt31H3ax1gW3pLi9JfW6i9hDdxTmcGK"//replace with your IPFS CIDconst {publicKey,signedMessage} =awaitencryptionSignature()/* fetchEncryptionKey(cid, publicKey, signedMessage) Parameters: CID: CID of the file to decrypt publicKey: public key of the user who has access to file or owner signedMessage: message signed by the owner of publicKey */constkeyObject=awaitlighthouse.fetchEncryptionKey( cid, publicKey, signedMessage )// Decrypt file/* decryptFile(cid, key, mimeType) Parameters: CID: CID of the file to decrypt key: the key to decrypt the file mimeType: default null, mime type of file */constfileType="image/jpeg"constdecrypted=awaitlighthouse.decryptFile(cid,keyObject.data.key, fileType)console.log(decrypted)/* Response: blob */// View Fileconsturl=URL.createObjectURL(decrypted)console.log(url)setFileURL(url) }return ( <divclassName="App"> <buttononClick={()=>decrypt()}>decrypt</button> { fileURL? <ahref={fileURL} target="_blank">viewFile</a>:null } </div> )}exportdefault App;
Step 4: As a final step, run the following command to view your react site in the browser
npm start
You can now decrypt the file by clicking the decrypt button and signing from the wallet. A View File hyperlink will pop up after decryption, and you can successfully view the file.