Created
December 27, 2021 20:13
-
-
Save alimir1/85eb33db20cc19ce4d23d594a7bc49d7 to your computer and use it in GitHub Desktop.
demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useEffect } from 'react'; | |
import { ethers } from "ethers"; | |
import { bufferToHex } from "ethereumjs-util"; | |
import { encrypt as metamaskEncrypt } from '@metamask/eth-sig-util'; | |
function Example() { | |
const [encryptedMessage, setEncryptedMessage] = useState(null); | |
const [encryptionPublicKey, setEncryptionPublicKey] = useState(null); | |
const [decryptedString, setDecryptedString] = useState(null); | |
const [accounts, setAccounts] = useState(null); | |
useEffect(() => { | |
console.log("Ethereum:", window.ethereum); | |
(async () => { | |
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }); | |
setAccounts(accounts); | |
console.log("accounts:", accounts); | |
})() | |
}, []); | |
useEffect(() => { | |
if (accounts) { | |
getEncryptionPubKey(); | |
} | |
}, [accounts]); | |
const decrypt = async () => { | |
const decryptedMessage = await window.ethereum | |
.request({ | |
method: 'eth_decrypt', | |
params: [encryptedMessage, accounts[0]], | |
}); | |
setDecryptedString(decryptedMessage); | |
} | |
const getEncryptionPubKey = async () => { | |
const key = await window.ethereum | |
.request({ | |
method: 'eth_getEncryptionPublicKey', | |
params: [accounts[0]], | |
}); | |
console.log("(getEncryptionPubKey) encryptionPublicKey:", key); | |
setEncryptionPublicKey(key); | |
}; | |
const encrypt = (message) => { | |
return bufferToHex( | |
Buffer.from( | |
JSON.stringify( | |
metamaskEncrypt( | |
{ | |
publicKey: encryptionPublicKey, | |
data: message, | |
version: 'x25519-xsalsa20-poly1305', | |
}, | |
) | |
), | |
'utf8' | |
) | |
); | |
} | |
const handleSubmit = async (event) => { | |
event.preventDefault(); | |
const msg = event.target.message.value; | |
console.log("msg:", msg); | |
const encryptedMsg = encrypt(msg); | |
setEncryptedMessage(encryptedMsg); | |
} | |
return ( | |
<div> | |
<p>Encryption public key: {encryptionPublicKey}</p> | |
<p>Generate encrypted message: {encryptedMessage}</p> | |
<p>Decrypted message: {decryptedString}</p> | |
<form onSubmit={handleSubmit}> | |
<label> | |
Message: | |
<input type="text" name="message" /> | |
</label> | |
<input type="submit" value="Encrypt" /> | |
</form> | |
<button onClick={decrypt}>Decrypt</button> | |
</div > | |
); | |
} | |
export default Example; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment