sign.js 724 B

1234567891011121314151617181920212223
  1. import * as crypto from 'crypto';
  2. import { promisify } from 'util';
  3. import nodeDigest from './dsa_digest.js';
  4. import hmacDigest from './hmac_digest.js';
  5. import nodeKey from './node_key.js';
  6. import getSignKey from './get_sign_verify_key.js';
  7. let oneShotSign;
  8. if (crypto.sign.length > 3) {
  9. oneShotSign = promisify(crypto.sign);
  10. }
  11. else {
  12. oneShotSign = crypto.sign;
  13. }
  14. const sign = async (alg, key, data) => {
  15. const keyObject = getSignKey(alg, key, 'sign');
  16. if (alg.startsWith('HS')) {
  17. const hmac = crypto.createHmac(hmacDigest(alg), keyObject);
  18. hmac.update(data);
  19. return hmac.digest();
  20. }
  21. return oneShotSign(nodeDigest(alg), data, nodeKey(alg, keyObject));
  22. };
  23. export default sign;