This is the 21st day of my participation in the August Text Challenge.More challenges in August

encryption

The process of communication between the front end and the back end is actually the process of data transmission.

In this process, there will be a lot of unexpected situations, such as typical middleman hijacking attack, some time ago, The events of Du ** and Wu ** are just like typical middleman hijacking attack.

In traditional HTTP requests, data is transmitted in plaintext, and the front and back ends, including middlemen, are WYSIWYG, so it is difficult to ensure that data will not be leaked.

So the solution is that many applications deploy the HTTPS protocol.

What if there is no interface to deploy HTTPS? Generally, sensitive data is transmitted through data encryption.

And it’s not just the data transfer phase. In data storage, important data is also encrypted. I’m sure you all know about security issues like database leaks.

When it comes to encryption and decryption, there are many ways. Examples include JsENCRYPT, MD5, and so on. Crypto is similar to this blog post, except that crypto is a nodeJs module, similar to FS.

crypto

Crypto is a built-in module of Node that provides encryption functionality, including a complete package of functions for OpenSSL hashing, HMAC, encryption, decryption, signature, and authentication.

Before crypto was used, jsENCRYPT was used for encryption on the front end and Node-RSA was used for decryption on the back end. The public and private keys were generated by Node-RAS. The code is as follows

const NodeRSA = require('node-rsa')

let key = new NodeRSA({ b: 1024 })
    key.setOptions({ encryptionScheme:'pkcs1'})
    
let pubkey = key.exportKey('public') // Generate a public key and send it to the front end for data encryption
let privkey = key.exportKey('private')// Generate a private key for data decryption
Copy the code

The decryption code is also simple

let key = new NodeRSA(privkey)
	key.setOptions({ encryptionScheme: 'pkcs1' })
//encryptData is encrypted data
const encryptData = 'damkiuh34r09u323rbnavjaf9uerjfqefqqb09023h43ibcae9uoue5bin'
const s = encryptData.replace(/\s+/g.'+')
const decryptData = key.decrypt(s, 'utf8')
Copy the code

I’m going to skip over the logic of using JsENCRYPT on the front end. However, Node-RSA is not an inherent nodeJs module and should be installed before use

npm install node-rsa

Crypto is the built-in module of Node, so I chose Crypto to rewrite the logic of data encryption and decryption.

The process of encryption and decryption is quite simple:

  1. Generate public and private keys for encryption and decryption
  2. Use the public key to encrypt data
  3. Decrypt data using a private key

code

Let’s start by implementing code that generates public and private keys

const { generateKeyPairSync, publicEncrypt, privateDecrypt } = require('crypto')

const { publicKey, privateKey } = generateKeyPairSync('rsa', {
    modulusLength: 1024.publicKeyEncoding: {
        type: 'spki'.format: 'pem'
    },
    privateKeyEncoding: {
        type: 'pkcs8'.format: 'pem'}});Copy the code

Next, try to encrypt a piece of data

// Data that needs to be encrypted
const data = "data to crypto"
const pub = publicKey.toString('ascii')

// Public key encryption process
const encryptData = publicEncrypt(pub, Buffer.from(data)).toString('base64');
console.log('encode:', encryptData);
Copy the code

The encrypted result is a base64 string

encode: Me+2EbDsMVLQHPKR8ZB3K88EDs4jNKuHsAZzMIjY3DCO7JEJGu3Tfkwv0tX4kDMiQvrxyJkR7tlpHQ1f91BrweAK6mkeyeyNQ3XOfsHwIEZJB+iv8IZpKiIl yE1KOGaUsN2Q8MyTRZ86IF+Qj4MwotDggXH/ADAHC0oJB/D5H5s=

The encrypted data is then decrypted

const pri = privateKey.toString('ascii')
// Private key decryption
const decryptData = privateDecrypt(pri, Buffer.from(encryptData.toString('base64'), 'base64'));
console.log('decode:', decryptData.toString());
Copy the code

Decryption result

decode: data to crypto

As you can see from the above code, you only need to call publicEncrypt and privateDecrypt respectively, which are the methods thrown by the built-in module Crypto.

So it seems that the process of encryption and decryption is not more simple ~