/
ed.ts
162 lines (139 loc) · 4.83 KB
/
ed.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/*
* Copyright © 2022 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*
*/
import * as crypto from 'crypto';
import { Mnemonic } from '@liskhq/lisk-passphrase';
import { parseKeyDerivationPath, hash, tagMessage } from './utils';
import { ED25519_CURVE, EMPTY_BUFFER, MESSAGE_TAG_NON_PROTOCOL_MESSAGE } from './constants';
import {
NACL_SIGN_PUBLICKEY_LENGTH,
NACL_SIGN_SIGNATURE_LENGTH,
getKeyPair,
getPublicKey,
signDetached,
verifyDetached,
} from './nacl';
const createHeader = (text: string): string => `-----${text}-----`;
const signedMessageHeader = createHeader('BEGIN LISK SIGNED MESSAGE');
const messageHeader = createHeader('MESSAGE');
const publicKeyHeader = createHeader('PUBLIC KEY');
const signatureHeader = createHeader('SIGNATURE');
const signatureFooter = createHeader('END LISK SIGNED MESSAGE');
export const getPublicKeyFromPrivateKey = (pk: Buffer): Buffer => getPublicKey(pk);
const getMasterKeyFromSeed = (seed: Buffer) => {
const hmac = crypto.createHmac('sha512', ED25519_CURVE);
const digest = hmac.update(seed).digest();
const leftBytes = digest.slice(0, 32);
const rightBytes = digest.slice(32);
return {
key: leftBytes,
chainCode: rightBytes,
};
};
const getChildKey = (node: { key: Buffer; chainCode: Buffer }, index: number) => {
const indexBuffer = Buffer.allocUnsafe(4);
indexBuffer.writeUInt32BE(index, 0);
const data = Buffer.concat([Buffer.alloc(1, 0), node.key, indexBuffer]);
const digest = crypto.createHmac('sha512', node.chainCode).update(data).digest();
const leftBytes = digest.slice(0, 32);
const rightBytes = digest.slice(32);
return {
key: leftBytes,
chainCode: rightBytes,
};
};
export const getPrivateKeyFromPhraseAndPath = async (
phrase: string,
path: string,
): Promise<Buffer> => {
const masterSeed = await Mnemonic.mnemonicToSeed(phrase);
let node = getMasterKeyFromSeed(masterSeed);
for (const segment of parseKeyDerivationPath(path)) {
node = getChildKey(node, segment);
}
return getKeyPair(node.key).privateKey;
};
export const signMessageWithPrivateKey = (
message: string | Buffer,
privateKey: Buffer,
tag = MESSAGE_TAG_NON_PROTOCOL_MESSAGE,
): SignedMessage => {
const messageBuffer = typeof message === 'string' ? Buffer.from(message, 'utf8') : message;
const publicKey = getPublicKey(privateKey);
const signature = signDataWithPrivateKey(tag, EMPTY_BUFFER, messageBuffer, privateKey);
return {
message,
publicKey,
signature,
};
};
export const verifyMessageWithPublicKey = ({
message,
publicKey,
signature,
tag = MESSAGE_TAG_NON_PROTOCOL_MESSAGE,
}: SignedMessageWithTag): boolean => {
if (publicKey.length !== NACL_SIGN_PUBLICKEY_LENGTH) {
throw new Error(`Invalid publicKey, expected ${NACL_SIGN_PUBLICKEY_LENGTH}-byte publicKey`);
}
if (signature.length !== NACL_SIGN_SIGNATURE_LENGTH) {
throw new Error(
`Invalid signature length, expected ${NACL_SIGN_SIGNATURE_LENGTH}-byte signature`,
);
}
const messageBuffer = typeof message === 'string' ? Buffer.from(message, 'utf8') : message;
return verifyData(tag, EMPTY_BUFFER, messageBuffer, signature, publicKey);
};
export interface SignedMessage {
readonly message: string | Buffer;
readonly publicKey: Buffer;
readonly signature: Buffer;
}
interface SignedMessageWithTag extends SignedMessage {
tag?: string;
}
// Old redundant interface SignedMessageWithPrivateKey for backwards compatibility
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface SignedMessageWithPrivateKey extends SignedMessage {}
export const printSignedMessage = ({ message, signature, publicKey }: SignedMessage): string =>
[
signedMessageHeader,
messageHeader,
typeof message === 'string' ? message : message.toString('hex'),
publicKeyHeader,
publicKey.toString('hex'),
signatureHeader,
signature.toString('hex'),
signatureFooter,
]
.filter(Boolean)
.join('\n');
export const signAndPrintMessage = (message: string, privateKey: Buffer): string => {
const signedMessage = signMessageWithPrivateKey(message, privateKey);
return printSignedMessage(signedMessage);
};
export const signDataWithPrivateKey = (
tag: string,
chainID: Buffer,
data: Buffer,
privateKey: Buffer,
): Buffer => signDetached(hash(tagMessage(tag, chainID, data)), privateKey);
export const signData = signDataWithPrivateKey;
export const verifyData = (
tag: string,
chainID: Buffer,
data: Buffer,
signature: Buffer,
publicKey: Buffer,
): boolean => verifyDetached(hash(tagMessage(tag, chainID, data)), signature, publicKey);