/*
 * 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
 */
/* global require */
/* global CL */
/* global forge */

// This file is marked for DEPRECATION
// use require('./client/authenticate.js').deriveKey instead.

module.exports = (function() {

    'use strict';

    var session = require('../client/session.js');

    var derive = function(startVotingKey, salt) {
        var deriver = CL.primitives.service.getPbkdfSecretKeyGenerator();
        var hashedSalt = CL.primitives.service.getHash([forge.util.encode64(salt)]);
        var derived = deriver.generateSecret(forge.util.encode64(startVotingKey), hashedSalt);
        return forge.util.bytesToHex(forge.util.decode64(derived));
    };

    // parse startVotingKey 
    // returns: { credentialId, pin } if valid

    var validateStartVotingKey = function(startVotingKey, eeid) {

        // derive voting card Id
        var credentialId = derive(startVotingKey, 'credentialid' + eeid);

        // derive pin
        var pin = derive(startVotingKey, 'keystorepin' + eeid);

        session('pin', pin);
        session('credentialId', credentialId);

        return {
            credentialId: credentialId,
            pin: pin
        };
    };

    return validateStartVotingKey;

})();
