/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
/* jshint node:true */
'use strict';

var forge = require('node-forge');

module.exports = Tools;

function Tools() {
  var reseedDigester_;
  var updateDigester_;

  this.cipher = function(key, counter) {
	var aes_output = [];
    forge.aes._updateBlock(
        formatKey(key), formatSeed('' + counter), aes_output, false);
    var aes_buffer = forge.util.createBuffer();
    aes_buffer.putInt32(aes_output[0]);
    aes_buffer.putInt32(aes_output[1]);
    aes_buffer.putInt32(aes_output[2]);
    aes_buffer.putInt32(aes_output[3]);

    return aes_buffer.getBytes();
  };

  this.getReseedDigester = function() {
    if (typeof reseedDigester_ === 'undefined') {
      reseedDigester_ = forge.md.sha256.create();
    }

    return reseedDigester_;
  };

  this.getUpdateDigester = function() {
    if (typeof updateDigester_ === 'undefined') {
      updateDigester_ = forge.md.sha256.create();
    }

    return updateDigester_;
  };
}

function formatKey(key) {
  // Convert key into 32 bit integers.
  var tmp = forge.util.createBuffer(key);
  key = [
  	tmp.getInt32(),
  	tmp.getInt32(),
  	tmp.getInt32(),
  	tmp.getInt32(),
  	tmp.getInt32(),
  	tmp.getInt32(),
  	tmp.getInt32(),
  	tmp.getInt32()        	
  ];

  // return the expanded key
  return forge.aes._expandKey(key, false);
}

function formatSeed(seed) {
  // Convert seed into 32 bit integers.
  var tmp = forge.util.createBuffer(seed);
  seed = [
  	tmp.getInt32(),
  	tmp.getInt32(),
  	tmp.getInt32(),
  	tmp.getInt32()
  ];
  
  return seed;
}