Skip to content

Instantly share code, notes, and snippets.

@alimir1
Created December 27, 2021 20:13
Show Gist options
  • Save alimir1/85eb33db20cc19ce4d23d594a7bc49d7 to your computer and use it in GitHub Desktop.
Save alimir1/85eb33db20cc19ce4d23d594a7bc49d7 to your computer and use it in GitHub Desktop.
demo
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