We know that ZIP compression and file encryption are based on HTTP, so I’m using Node to implement a few functions

Zip compression/decompression

let zlib = require('zlib'); / / core
let path = require('path');
let fs = require('fs');

// The compression stream compresses 1.txt into 1.txt.gz
function gzip(source){ //source File directory
    let gzip = zlib.createGzip(); // The conversion stream can be read and written
    fs.createReadStream(source).pipe(gzip).pipe(fs.createWriteStream(source+'.gz')); // Read => compress => write new
}
//gzip(path.join(__dirname, '1.txt'));
/ /
function ungzip(source) {
    let ungz = zlib.createGunzip();
    fs.createReadStream(source).pipe(ungz).pipe(fs.createWriteStream(path.join(__dirname,path.basename(source,'.gz'))));
}
ungzip(path.join(__dirname, '1.txt.gz'))
Copy the code

When sending a request, it will have the fields Accept-encoding: gzip, deflate, br which compression method is supported. When writing to the server, the browser will have a field and the response header will have content-encoding: Gzip, the browser will automatically decompress in this way, let’s implement the compression function

let http = require('http');
let url=  require('url');
let path = require('path');
let fs = require('fs');
let zlib = require('zlib');
let server = http.createServer(function (req,res) {
    let {pathname} = url.parse(req.url,true);
    if(pathname === '/' || pathname === '\ \') pathname = '\index.html';
    let p = path.join(__dirname,pathname);
    fs.stat(p,function (err,stat) {
        if(! err){let encoding = req.headers['accept-encoding'];
            if (encoding.match(/\bgzip\b/)) {//:, both are called boundaries
                res.setHeader('Content-Encoding'.'gzip');
                let gzip = zlib.createGzip();
                fs.createReadStream(p).pipe(gzip).pipe(res);
            } else if (encoding.match(/\bdeflate\b/)){
                res.setHeader('Content-Encoding'.'bdeflate');
                let deflate = zlib.createDeflate();
                fs.createReadStream(p).pipe(deflate).pipe(res);
            }else{
                fs.createReadStream(p).pipe(res);// Return it to the client intact if it is not supported}}else{
          res.end();
        }
    })
})
server.listen(3000);
Copy the code

File encryption

The process of encryption is reversible, but MD5 is irreversible. There are many algorithms for encryption, such as symmetric encryption, asymmetric encryption (HTTPS), signature, etc. These algorithms are generally built in node (crypto). Here we only talk about the usage

In Node.js, OpenSSL class library is used as an internal means to implement encryption and decryption. OpenSSL is a strict tested and reliable implementation tool for encryption and decryption algorithms

Hash algorithm salt algorithm

Hash algorithm, also called hash algorithm, is used to transform arbitrary length of input into fixed length of output, the common md5, SHA1, etc

let crypto = require('crypto'); // Common encryption module
// console.log(crypto.getHashes());
//1) Md5 is not encryption, it is called abstract algorithm, characteristic is not reversible, output results of the same length, different content of the output results are different, and vice versa

let md5 = crypto.createHash('md5') // Create an algorithm that often passes files in this way
md5.update('123456'); // Update which text to encrypt
let result1 = md5.digest('hex');/ / base64 hex16 into the system
let md52 = crypto.createHash('md5') // Create an algorithm that often passes files in this way
md52.update('1234567'); // Update which text to encrypt
let result = md52.digest('base64');/ / base64 hex16 into the system
// If the stored password is encrypted multiple times. Drag the library
Copy the code
// The disadvantages of encrypting files, the file will be read into memory, when the file is very large, usually in sections to read,
let fs = require('fs');
let str = fs.readFileSync(__dirname+'/index.html'.'utf8');
let md53 = crypto.createHash('md5');
md53.update(str);
let result2 = md53.digest('hex');
console.log(result2);

// The second time the client requests the file, the server will first check whether the encryption is consistent. If it is consistent, it will return 304 to read from the cache.
let md54 = crypto.createHash('md5');
let rs = fs.createReadStream(__dirname + '/index.html', {highWaterMark:3});
rs.on('data'.function (data) {
      md54.update(data); // Update can be called multiple times
});
rs.on('end'.function (data) {
    console.log(md54.digest('hex'));
})
Copy the code

HMAC algorithm

Available digest algorithms, such as SHA1, MD5, sha256

// ------------ Add salt algorithm
let crypto = require('crypto');
let hmac = crypto.createHmac('sha1'.'zdl'); ZDL is a string that specifies a key in PEM format. Different types of PEM generate different keys
hmac.update('123456');
let result = hmac.digest('hex');
console.log(result);
Copy the code

In the process of sending, it may be hijacked. We can use openssl genrsa -out rsa_private.key 1024 to generate 1024 bytes of secret key

// PEM is the standard format of OpenSSL. OpenSSL stores certificates and keys in the PEM file format and is base64-encoded.
let fs = require('fs');
let pem  = fs.readFileSync(__dirname+'/rsa_private.key');
let key = pem.toString('ascii');
let hmac = crypto.createHmac('sha1', key);
hmac.update('zdl');
let result = hmac.digest('hex');
console.log(result);
Copy the code

Symmetric encryption

The Blowfish algorithm is a symmetric encryption algorithm. Symmetric means that the encryption and decryption use the same key.

Cons: Yes, the name is limited, up to 14 characters can be accepted

let crypto = require('crypto');
let fs = require('fs');
let key = fs.readFileSync(__dirname + '/rsa_private.key')
let cipher = crypto.createCipher('blowfish', key);
cipher.update('zdl');
let result = cipher.final('hex');
console.log(result);

/ / decryption
let deciper = crypto.createDecipher('blowfish', key);
// Tell him it was hex
deciper.update(result,'hex');
let r = deciper.final('utf8');
console.log(r);
Copy the code

Asymmetric encryption

Public key encryption private key decryption

Calculate the public key openssl rsa -in rsa_privately. key -pubout -out rsa_public.key

// Asymmetric encryption
let crypto = require('crypto');
let fs = require('fs');
let public = fs.readFileSync(__dirname+'/rsa_public.key'.'utf8');
let private = fs.readFileSync(__dirname +'/rsa_private.key'.'utf8');
let result = crypto.publicEncrypt(public, Buffer.from('hello'));
let r = crypto.privateDecrypt(private, result);
console.log(r.toString());
Copy the code

Relatively safe, if the client to the server to add a certificate, this case needs to be encrypted after sending, before writing an algorithm, the current string before a few after a few out to do the middle sort, then put back, every period of time to change ~~~

The signature is interpreted in the cookie