Front-end and back-end encryption and decryption [JS encryption module (md5, crypto, crypto-js, jsencrypt) python RSA encryption and decryption (pycryptodome) module installation and use]

JS encryption module [js-md5 (AES), crypto (AES), crypto-js(), jsencrypt (asymmetric encryption, RSA)]

1. Installation

npm install js-md5
npm install crypto
npm install crypto-js
npm install jsencrypt

2. Use

1. js-md5
js-md5 is not exactly encryption. It should be said that it serializes the ciphertext. You can directly parse the md5 encrypted characters through the following website, so the security is very low https://
www .cmd5.com/

const md5 = require('js-md5');
function md5Encryption(pwd){
    
    
  return md5(pwd) 
}
console.log(md5Encryption('abc123')); //e99a18c428cb38d5f260853678922e03

2.
After adding random keys to crypto, the security is much improved compared to MD5. It can no longer be decrypted through the above decryption website.

'use strict'
const crypto  = require('crypto');
// 加密
function encryption(message){
    
    
  // 初始化数据
  const key = crypto.randomBytes(32) //32位随机共享密钥
  const iv = crypto.randomBytes(16); //初始向量,16字节
  const algorithm = 'aes-256-gcm'; //加密算法和操作模式
  const text = String(message); //将需要加密的数据转成字符串
  //初始化加密算法
  const cipher = crypto.createCipheriv(algorithm,key,iv); //传入创建密钥所需参数
  let encrypted = cipher.update(text,'utf8','hex'); // 初始化加密密文
  encrypted += cipher.final('hex') //加密密文
  const tag = cipher.getAuthTag() //生成标签,用于验证密文的来源
  return [encrypted,tag,key,iv,algorithm] //返回加密密文和密文来源信息
}
// 解密
function decrypt(cipherTextList){
    
    
  const [encrypted,tag,key,iv,algorithm] = cipherTextList //导入解密内容和解密需要用到的密钥
  const decipher = crypto.createDecipheriv(algorithm,key,iv)
  decipher.setAuthTag(tag) //传入验证标签,验证密文来源,当验证标签不一致时代码报错
  let decrypted = decipher.update(encrypted,'hex','utf8');
  decrypted += decipher.final('utf8')
  return decrypted
}

let ciphered = encryption(1234556344) //加密后返回密文数组
let cipher = decrypt(ciphered) //解密后返回解密密文
console.log(ciphered[0])  // 628e1b71ae1d27ef5e01
console.log(cipher); // 1234556344

3. Crypto-js
uses customized keys to encrypt and decrypt, which can encrypt and decrypt ciphertext more flexibly. However, because the key of ciphertext can be seen through the front end, although the encrypted information cannot be decrypted through the decryption website, it can be Decrypt through the public key obtained at the front end

// crypto-js加密
const CryptoJS  = require('crypto-js');
function cryptoEncryption(aseKey,message){
    
     //aseKey为密钥(必须为:8/16/32位),message为要加密的密文
  var encrypt = CryptoJS.AES.encrypt(message,CryptoJS.enc.Utf8.parse(aseKey),{
    
    
    mode:CryptoJS.mode.ECB,
    padding:CryptoJS.pad.Pkcs7
  }).toString();
  return encrypt
}
// crypto-js解密
function cryptoDecrypt(aseKey,message){
    
    
  var decrypt = CryptoJS.AES.decrypt(message, CryptoJS.enc.Utf8.parse(aseKey), {
    
    
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  }).toString(CryptoJS.enc.Utf8);
  return decrypt
}

var aseKey = "12345678" //密钥一致才能进行解密     
var encrpytText = "abc12345";
var decryptText = 'KLqoT18E3l+OoDFLwS8DsA=='
console.log(cryptoEncryption(aseKey,encrpytText)); //调用加密方法
console.log(cryptoDecrypt(aseKey,decryptText));//调用解密方法

4. Asymmetric (RSA) encryption: jsencrypt
asymmetric encryption key generation website: http://web.chacuo.net/netrsakeypair
About this encryption module, it appears in a backend management system project I made. The front end is vue. The backend is Java. The application scenario requires the front-end to encrypt the ciphertext that needs to be encrypted through the public key, and the back-end to decrypt the ciphertext encrypted by the front-end through the private key. This can greatly improve the security of ciphertext compared to the previous three. For related usage methods, please refer to the second article below about other good encryption and decryption articles on the front end . The simplified code
about the front- end is posted below for reference. For reference about the back-end, please refer to the second blog post linked below.

let encryptor = new JSEncrypt() // 新建JSEncrypt对象
 
let publicKey = `公钥`  //设置公钥,可以从上面的非对称加密密钥生成网站中得到
 
encryptor.setPublicKey(publicKey) // 将得到的公钥通过setPbulicKey方法设置到JSEncrypt对象中
 
let rsaPassWord = encryptor.encrypt('加密密文') // 对需要加密的数据进行加密,rspPassWord就是加密密文

python RSA encryption and decryption

The pub.key and pri.key in the file are generated locally on the website http://web.chacuo.net/netrsakeypair and saved locally. Save them yourself.

Install third-party libraries

pip uninstall crypto pycryptodome  #安装的如果导入不成功卸载了
pip install pycryptodome     #再次安装

code

import base64
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5
from Crypto.PublicKey import RSA
import os

dir_path = os.path.dirname(__file__)


def encrpt(msg):
    with open(dir_path+"\\pub.key", 'r', encoding='utf-8') as f:
        pub = f.read()  # 加密公钥
        public_key = '-----BEGIN PUBLIC KEY-----\n' + pub + '\n-----END PUBLIC KEY-----'
        rsakey = RSA.importKey(public_key)
        cipher = Cipher_pksc1_v1_5.new(rsakey)
        cipher_text = base64.b64encode(cipher.encrypt(msg.encode()))
        return cipher_text.decode()


def decrypt(encrypt_msg):
    with open(dir_path+"\\pri.key", 'r', encoding='utf-8') as f:
        pri = f.read()  # 加密私钥
        private_key = '-----BEGIN PRIVATE KEY-----\n' + \
            pri + '\n-----END PRIVATE KEY-----'
        decodeStr = base64.b64decode(encrypt_msg)  # cipher_text是上面rsa加密的内容
        rsakey = RSA.importKey(private_key)
        prikey = Cipher_pksc1_v1_5.new(rsakey)
        encry_text = prikey.decrypt(decodeStr, b'rsa')
        return encry_text.decode('utf8')

#前端经过加密的密文
ciphertext = "dOESS/7V8a1+RB5xweXnJCGr0SLQqf5H6tNQW/b78HDn9N6kEN2fzeEO4t3AqLkAlOzLXGtYKdONN8Hxs6lV7hPa2bHRJz5X4kzOqj/HsDqy9zd/1ZSoMxl7pi9B0dzhjThFqgydLSPvgAMyVQhvLjo/jOvtUJ6nPrd3pwmLCyJP9fP4vhC7KmJEJMzaOSbgQLFKksiR3Bv0O+mubcgTTSFKHMxgwcAQ+cPGtMNtnUMkCVruMZWUwQ23/0dm3KOWAALlumA59p+JMZNG4zThiXrIIkyGMZ62wmxfINEeTWBvI/7vq0kCOEPMf2RWpNnR+kxnZxKlp1ih7AIOvqAaLg=="

# ciphertext = encrpt('admin*cc123') #测试密钥
# print('密文:', ciphertext)

plaintext = decrypt(ciphertext)
print('明文:', plaintext)

Other good articles about encryption and decryption on the front end:

1. Several encryption methods using CryptoJS on the front end
https://www.jianshu.com/p/7b5eb33512fd
2. Asymmetric encryption (vue project)
https://blog.csdn.net/weixin_42423019/article/details/82468626

Guess you like

Origin blog.csdn.net/weixin_51033461/article/details/121697575#comments_28488713