// crypto.js
// Copyright (C) 2022 DTP Technologies, LLC
// License: Apache-2.0

'use strict';

const crypto = require('crypto');

const { SiteService } = require('../../lib/site-lib');

class CryptoService extends SiteService {

  constructor (dtp) {
    super(dtp, module.exports);
  }

  maskPassword (passwordSalt, password) {
    const hash = crypto.createHash('sha256');

    hash.update(process.env.DTP_PASSWORD_SALT);
    hash.update(passwordSalt);
    hash.update(password);

    return hash.digest('hex');
  }

  createHash (content, algorithm = 'sha256') {
    const hash = crypto.createHash(algorithm);
    hash.update(content);
    return hash.digest('hex');
  }

  hash32 (text) {
    var hash = 0, i, chr;
    if (text.length === 0) {
      return hash;
    }
    for (i = text.length - 1; i >= 0; --i) {
      chr = text.charCodeAt(i);
      // jshint ignore:start
      hash = ((hash << 5) - hash) + chr;
      hash |= 0;
      // jshint ignore:end
    }
    hash = hash.toString(16);
    if (hash[0] === '-') {
      hash = hash.slice(1);
    }
    return hash;
  }

  createProof (secret, challenge) {
    let hash = crypto.createHash('sha256');
    hash.update(secret);
    hash.update(challenge);
    return hash.digest('hex');
  }
}

module.exports = {
  slug: 'crypto',
  name: 'crypto',
  create: (dtp) => { return new CryptoService(dtp); },
};