Created
May 27, 2022 15:10
-
-
Save prichodko/99cec8aab855bbd127166307f1963d8a to your computer and use it in GitHub Desktop.
Decrypt Public Key from Keystore File
This file contains 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 { decrypt } from 'ethereum-cryptography/aes' | |
import { keccak256 } from 'ethereum-cryptography/keccak' | |
import { scrypt } from 'ethereum-cryptography/scrypt' | |
import { getPublicKey } from 'ethereum-cryptography/secp256k1' | |
import { | |
bytesToHex, | |
concatBytes, | |
hexToBytes, | |
utf8ToBytes, | |
} from 'ethereum-cryptography/utils' | |
const keystore = { | |
version: 3, | |
id: '3529eee7-ac92-4a8c-9b9a-320365541816', | |
address: 'f6daa929a5193a877b6ea54fee6c386efda879f2', | |
crypto: { | |
ciphertext: | |
'3d769519fa5a8c92ee4c5ef504edc1fa2e8bcb41134f76c6196f9ed12a2725aa', | |
cipherparams: { | |
iv: '1f0173c361b2577c018804bd97549c40', | |
}, | |
cipher: 'aes-128-ctr', | |
kdf: 'scrypt', | |
kdfparams: { | |
dklen: 32, | |
salt: '61a371af3f72e4bd2b975f0e9c1e10fbecd20bfd58d40da69e8efc2bcf73d56d', | |
n: 131072, | |
r: 8, | |
p: 1, | |
}, | |
mac: '713dc9dabc389bc1bfe3c1de09b9b3df1780020ba870022452e5bccc593a3bdd', | |
}, | |
} | |
const password = 'quantum computer' | |
it('should decrypt a private key', async () => { | |
const { ciphertext, kdfparams, cipherparams, mac } = keystore.crypto | |
const derivedKey = await scrypt( | |
utf8ToBytes(password), | |
hexToBytes(kdfparams.salt), | |
kdfparams.n, | |
kdfparams.p, | |
kdfparams.r, | |
kdfparams.dklen | |
) | |
const messageAuthenticationCode = bytesToHex( | |
keccak256(concatBytes(derivedKey.slice(16), hexToBytes(ciphertext))) | |
) | |
expect(messageAuthenticationCode).toEqual(mac) | |
const privateKey = await decrypt( | |
hexToBytes(ciphertext), | |
derivedKey.slice(0, 16), | |
hexToBytes(cipherparams.iv), | |
'aes-128-ctr' | |
) | |
console.log(bytesToHex(privateKey)) | |
const publicKey = getPublicKey(privateKey) | |
const publicKeyWithoutPrefix = publicKey.slice(1) // uncompressed public key has 04 prefix | |
const hash = keccak256(publicKeyWithoutPrefix) | |
const address = bytesToHex(hash.slice(12)) | |
expect(address).toEqual(keystore.address) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment