Skip to content

Commit 64fc8a2

Browse files
committed
Added verify signature function in PublicAccount class
1 parent be669ab commit 64fc8a2

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

src/model/account/PublicAccount.ts

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@
1414
* limitations under the License.
1515
*/
1616

17-
import {NetworkType} from '../blockchain/NetworkType';
18-
import {Address} from './Address';
17+
import { KeyPair, convert } from 'nem2-library';
18+
import { NetworkType } from '../blockchain/NetworkType';
19+
import { Address } from './Address';
1920

2021
/**
2122
* The public account structure contains account's address and public key.
@@ -53,6 +54,48 @@ export class PublicAccount {
5354
return new PublicAccount(publicKey, address);
5455
}
5556

57+
/**
58+
* Verify a signature.
59+
*
60+
* @param {string} publicKey - The public key to use for verification.
61+
* @param {string} data - The data to verify.
62+
* @param {string} signature - The signature to verify.
63+
*
64+
* @return {boolean} - True if the signature is valid, false otherwise.
65+
*/
66+
static verifySignature(publicKey: string, data: string, signature: string): boolean {
67+
if (!publicKey || !data || !signature) {
68+
throw new Error('Missing argument !');
69+
}
70+
71+
if (publicKey.length !== 64 && publicKey.length !== 66) {
72+
throw new Error('Not a valid public key');
73+
}
74+
75+
if (convert.isHexString(signature)) {
76+
throw new Error('Signature must be hexadecimal only !');
77+
}
78+
79+
if (signature.length !== 128) {
80+
throw new Error('Signature length is incorrect !');
81+
}
82+
83+
// Convert signature key to Uint8Array
84+
const _signature = convert.hexToUint8(signature);
85+
86+
let _data;
87+
88+
// Convert data to hex if data is not hex
89+
if (!convert.isHexString(data)) {
90+
_data = convert.utf8ToHex(data);
91+
}
92+
93+
// Convert to Uint8Array
94+
_data = convert.hexToUint8(_data);
95+
96+
return KeyPair.verify(publicKey, _data, _signature);
97+
}
98+
5699
/**
57100
* Compares public accounts for equality.
58101
* @param publicAccount
@@ -61,4 +104,5 @@ export class PublicAccount {
61104
equals(publicAccount: PublicAccount) {
62105
return this.publicKey === publicAccount.publicKey && this.address.plain() === publicAccount.address.plain();
63106
}
107+
64108
}

0 commit comments

Comments
 (0)