var _crypto = require('crypto');

//SHA1加密
function sha1(msg){
    var md5sum = _crypto.createHash('sha1');
    md5sum.update(msg);
    msg = md5sum.digest('hex');
    return msg;
}
exports.sha1 = sha1;

//MD5加密
function md5(str){
    var md5sum = _crypto.createHash('md5');
    md5sum.update(str);
    str = md5sum.digest('hex');
    return str;
}
exports.md5 = md5;

//AES加密
function aesEncrypt(data,e_key) {
    //防止中文加密后解密乱码 先将中文编码后进行加密
    //data = encodeURIComponent(encodeURIComponent(encodeURIComponent(data)));
    data = encodeURIComponent(data);
    //md5加密Password，生成key
    var m = _crypto.createHash('md5');
    m.update(e_key)
    var key = m.digest('hex');
    //生成iv
    m = _crypto.createHash('md5');
    m.update(e_key + key)
    var iv = m.digest('hex').slice(0, 16);
    //utf8格式化需要加密的明文
    data = new Buffer(data, 'utf8').toString('binary');
    //生成aes-256-cbc模式
    var cipher = _crypto.createCipheriv('aes-256-cbc', key, iv);
    var encrypted;
    encrypted = cipher.update(data, 'utf8', 'binary') + cipher.final('binary');
    //Base64编码
    var encoded = new Buffer(encrypted, 'binary').toString('base64');
    return encoded;
}
exports.aesEncrypt = aesEncrypt;

//AES解密
function aesDecrypt(data,d_key) {
    try {
        data = data.replace(/\-/g, '+').replace(/_/g, '/');
        var edata = new Buffer(data, 'base64').toString('binary');
        // Create key from password
        var m = _crypto.createHash('md5');
        m.update(d_key)
        var key = m.digest('hex');
        m = _crypto.createHash('md5');
        m.update(d_key + key)
        var iv = m.digest('hex');
        var decipher = _crypto.createDecipheriv('aes-256-cbc', key, iv.slice(0, 16));
        var decrypted, plaintext;
        plaintext = (decipher.update(edata, 'binary', 'utf8') + decipher.final('utf8'));
        //解码返回
        //plaintext = decodeURIComponent(decodeURIComponent(decodeURIComponent(plaintext)));
        plaintext = decodeURIComponent(plaintext);
        return plaintext;
    }
    catch (ex) {
        return "";
    }
}
exports.aesDecrypt = aesDecrypt;