symbol/KeyPair.js

  1. import { PrivateKey, PublicKey, Signature } from '../CryptoTypes.js';
  2. import ed25519 from '../impl/ed25519.js';
  3. import { deepCompare } from '../utils/arrayHelpers.js';
  4. const HASH_MODE = 'Sha2_512';
  5. /**
  6. * Represents an ED25519 private and public key.
  7. */
  8. export class KeyPair {
  9. /**
  10. * Creates a key pair from a private key.
  11. * @param {PrivateKey} privateKey Private key.
  12. */
  13. constructor(privateKey) {
  14. /**
  15. * @private
  16. */
  17. this._privateKey = privateKey;
  18. /**
  19. * @private
  20. */
  21. this._keyPair = ed25519.get().keyPairFromSeed(HASH_MODE, this._privateKey.bytes);
  22. }
  23. /**
  24. * Gets the public key.
  25. * @returns {PublicKey} Public key.
  26. */
  27. get publicKey() {
  28. return new PublicKey(this._keyPair.publicKey);
  29. }
  30. /**
  31. * Gets the private key.
  32. * @returns {PrivateKey} Private key.
  33. */
  34. get privateKey() {
  35. return new PrivateKey(this._privateKey.bytes);
  36. }
  37. /**
  38. * Signs a message with the private key.
  39. * @param {Uint8Array} message Message to sign.
  40. * @returns {Signature} Message signature.
  41. */
  42. sign(message) {
  43. return new Signature(ed25519.get().sign(HASH_MODE, message, this._keyPair));
  44. }
  45. }
  46. /**
  47. * Verifies signatures signed by a single key pair.
  48. */
  49. export class Verifier {
  50. /**
  51. * Creates a verifier from a public key.
  52. * @param {PublicKey} publicKey Public key.
  53. */
  54. constructor(publicKey) {
  55. if (0 === deepCompare(new Uint8Array(PublicKey.SIZE), publicKey.bytes))
  56. throw new Error('public key cannot be zero');
  57. /**
  58. * Public key used for signature verification.
  59. * @type PublicKey
  60. */
  61. this.publicKey = publicKey;
  62. }
  63. /**
  64. * Verifies a message signature.
  65. * @param {Uint8Array} message Message to verify.
  66. * @param {Signature} signature Signature to verify.
  67. * @returns {boolean} true if the message signature verifies.
  68. */
  69. verify(message, signature) {
  70. return ed25519.get().verify(HASH_MODE, message, signature.bytes, this.publicKey.bytes);
  71. }
  72. }