@@ -170,6 +170,29 @@ export const hashMessage = (message: string): string => {
170170 return sha3Raw ( ethMessage ) ; // using keccak in web3-utils.sha3Raw instead of SHA3 (NIST Standard) as both are different
171171} ;
172172
173+ /**
174+ * Takes a hash of a message and a private key, signs the message using the SECP256k1 elliptic curve algorithm, and returns the signature components.
175+ * @param hash - The hash of the message to be signed, represented as a hexadecimal string.
176+ * @param privateKey - The private key used to sign the message, represented as a byte array.
177+ * @returns - The signature Object containing the message, messageHash, signature r, s, v
178+ */
179+ export const signMessageWithPrivateKey = ( hash : HexString , privateKey : Bytes ) : SignResult => {
180+ const privateKeyUint8Array = parseAndValidatePrivateKey ( privateKey ) ;
181+
182+ const signature = secp256k1 . sign ( hash . substring ( 2 ) , privateKeyUint8Array ) ;
183+ const signatureBytes = signature . toCompactRawBytes ( ) ;
184+ const r = signature . r . toString ( 16 ) . padStart ( 64 , '0' ) ;
185+ const s = signature . s . toString ( 16 ) . padStart ( 64 , '0' ) ;
186+ const v = signature . recovery ! + 27 ;
187+
188+ return {
189+ messageHash : hash ,
190+ v : numberToHex ( v ) ,
191+ r : `0x${ r } ` ,
192+ s : `0x${ s } ` ,
193+ signature : `${ bytesToHex ( signatureBytes ) } ${ v . toString ( 16 ) } ` ,
194+ } ;
195+ } ;
173196/**
174197 * Signs arbitrary data with a given private key.
175198 * :::info
@@ -193,23 +216,17 @@ export const hashMessage = (message: string): string => {
193216 * ```
194217 */
195218export const sign = ( data : string , privateKey : Bytes ) : SignResult => {
196- const privateKeyUint8Array = parseAndValidatePrivateKey ( privateKey ) ;
197-
198219 const hash = hashMessage ( data ) ;
199220
200- const signature = secp256k1 . sign ( hash . substring ( 2 ) , privateKeyUint8Array ) ;
201- const signatureBytes = signature . toCompactRawBytes ( ) ;
202- const r = signature . r . toString ( 16 ) . padStart ( 64 , '0' ) ;
203- const s = signature . s . toString ( 16 ) . padStart ( 64 , '0' ) ;
204- const v = signature . recovery ! + 27 ;
221+ const { messageHash, v, r, s, signature } = signMessageWithPrivateKey ( hash , privateKey ) ;
205222
206223 return {
207224 message : data ,
208- messageHash : hash ,
209- v : numberToHex ( v ) ,
210- r : `0x ${ r } ` ,
211- s : `0x ${ s } ` ,
212- signature : ` ${ bytesToHex ( signatureBytes ) } ${ v . toString ( 16 ) } ` ,
225+ messageHash,
226+ v,
227+ r,
228+ s,
229+ signature,
213230 } ;
214231} ;
215232
0 commit comments