[chore] update keyTool

@types
neeboo 6 years ago
parent 0a4b648b59
commit 51eb43237f
  1. 30
      packages/harmony-crypto/src/keyTool.ts

@ -5,9 +5,16 @@ import { keccak256 } from './keccak256';
import { randomBytes } from './random';
const secp256k1 = elliptic.ec('secp256k1');
// const { curve } = secp256k1;
/**
* @function generatePrivateKey
* @description generatePrivate key using `eth-lib` settings
* @return {string}
*/
export const generatePrivateKey = (): string => {
const entropy: string = '0x' + randomBytes(16);
const innerHex: string = keccak256(
bytes.concat(['0x' + randomBytes(32), entropy || '0x' + randomBytes(32)]),
);
@ -19,25 +26,44 @@ export const generatePrivateKey = (): string => {
return outerHex;
};
/**
* @function getPubkeyFromPrivateKey
* @param {string} privateKey - private key String
* @return {string}
*/
export const getPubkeyFromPrivateKey = (privateKey: string): string => {
const buffer = new Buffer(privateKey.slice(2), 'hex');
const ecKey = secp256k1.keyFromPrivate(buffer);
const pubK = '0x' + ecKey.getPublic(false, 'hex').slice(2);
const publicKey = keccak256(pubK);
const publicKey = '0x' + ecKey.getPublic(true, 'hex');
return publicKey;
};
/**
* @function getAddressFromPrivateKey
* @param {string} privateKey - private key string
* @return {string} address with `length = 40`
*/
export const getAddressFromPrivateKey = (privateKey: string): string => {
const publicKey = getPubkeyFromPrivateKey(privateKey);
const address = '0x' + publicKey.slice(-40);
return address;
};
/**
* @function getAddressFromPublicKey
* @param {string} publicKey - public key string
* @return {string} address with `length = 40`
*/
export const getAddressFromPublicKey = (publicKey: string): string => {
const address = '0x' + publicKey.slice(-40);
return address;
};
/**
* @function toChecksumAddress
* @param {string} address - raw address
* @return {string} checksumed address
*/
export const toChecksumAddress = (address: string): string => {
if (typeof address !== 'string' || !address.match(/^0x[0-9A-Fa-f]{40}$/)) {
errors.throwError('invalid address', errors.INVALID_ARGUMENT, {

Loading…
Cancel
Save