From d6d548a09e753d4557ef14bbb0c8808df46ab138 Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Thu, 24 Jun 2021 15:53:27 +1000 Subject: [PATCH] Save private key in storage In clear for now. --- examples/eth-dm/src/App.tsx | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/examples/eth-dm/src/App.tsx b/examples/eth-dm/src/App.tsx index dcad23c0e3..526178f4a5 100644 --- a/examples/eth-dm/src/App.tsx +++ b/examples/eth-dm/src/App.tsx @@ -21,16 +21,25 @@ import { SendMessage } from './SendMessage'; export const PublicKeyContentTopic = '/eth-dm/1/public-key/json'; export const DirectMessageContentTopic = '/eth-dm/1/direct-message/json'; +const EthDmKeyStorageKey = 'ethDmKey'; + declare let window: any; function App() { const [waku, setWaku] = useState(); const [provider, setProvider] = useState(); - const [ethDmKeyPair, setEthDmKeyPair] = useState(); + const [ethDmKeyPair, setEthDmKeyPair] = useState( + retrieveKeysFromStorage + ); const [publicKeyMsg, setPublicKeyMsg] = useState(); const [publicKeys, setPublicKeys] = useState>(new Map()); const [messages, setMessages] = useState([]); + useEffect(() => { + if (!ethDmKeyPair) return; + saveKeysToStorage(ethDmKeyPair); + }, [ethDmKeyPair]); + useEffect(() => { if (provider) return; try { @@ -233,3 +242,22 @@ async function handleDirectMessage( return copy; }); } + +function saveKeysToStorage(ethDmKeyPair: KeyPair) { + // /!\ Bad idea to store keys in clear. At least put a password on it. + localStorage.setItem(EthDmKeyStorageKey, ethDmKeyPair.privateKey); +} + +function retrieveKeysFromStorage() { + const privateKey = window.localStorage.getItem(EthDmKeyStorageKey); + if (privateKey) { + const publicKey = EthCrypto.publicKeyByPrivateKey(privateKey); + const address = EthCrypto.publicKey.toAddress(publicKey); + return { + privateKey, + publicKey, + address, + }; + } + return; +}