https采用了非对称加密技术,加密用的东西和解密用的东西不同,分别是公钥和私钥。在经过私钥加密之前,还有一次对称的加密技术,双重保障。总的来说,就是客户端数据->对称加密->非对称加密(私钥)--->服务器--->非对称解密(公钥)--->对称加密的数据,客户端发送的数据包括了明文和非对称加密后的数据,服务端拿到明文和对称加密的数据后,自己对明文进行一次对称加密,如果数据和客户端送来的一致,说明数据是安全的。
对称加密方法之一---md5加密
function Hash(plainText) {
// 明文加密
let encryptedAbstracted = crypto.createHash('md5')
//返回128位长度的数字摘要
return encryptedAbstracted.update(plainText).digest('hex')
}
非对称加密
非对称加密需要公钥和私钥,指令是ssh-keygen -t rsa -C your_email@example.com
class RSAEncrypto {
constructor(){
this.prvKey = this.loadKey('./rsa-prv.pem'),
this.pubKey = this.loadKey('./rsa-pub.pem');
}
//发送者私钥加密
loadKey(file) {
// key实际上就是PEM编码的字符串:
return fs.readFileSync(file, 'utf8');
}
privateEncrypt(data){
// 使用私钥加密:
let encryptByprivate = crypto.privateEncrypt(this.prvKey, Buffer.from(data, 'utf8'));
//encryptByprivate是buffer
console.log('encrypted by private key: ' + encryptByprivate.toString('hex'));
return encryptByprivate
}
publicDecrypt(encryptByprivate){
/**
* 公钥解密
*/
let decodeByPublic = crypto.publicDecrypt(this.pubKey, encryptByprivate);
//decodeByPublic 也是buffer
console.log('decrypted by public key: ' + decodeByPublic.toString('utf8'));
return decodeByPublic.toString('utf8')
}
}
完整的代码如下:
/**
* 1. 客户端和服务端都要有hash函数,hash函数加密的过程叫做数字摘要或者数字指纹
* 2. 客户端有私钥,服务端有公钥,这是非对称加密
* 数字签名=1+2
*/
const fs = require('fs')
const crypto = require('crypto')
function Hash(plainText) {
// 明文加密
let encryptedAbstracted = crypto.createHash('md5')
//返回128位长度的数字摘要
return encryptedAbstracted.update(plainText).digest('hex')
}
class RSAEncrypto {
constructor(){
this.prvKey = this.loadKey('./rsa-prv.pem'),
this.pubKey = this.loadKey('./rsa-pub.pem');
}
//发送者私钥加密
loadKey(file) {
// key实际上就是PEM编码的字符串:
return fs.readFileSync(file, 'utf8');
}
privateEncrypt(data){
// 使用私钥加密:
let encryptByprivate = crypto.privateEncrypt(this.prvKey, Buffer.from(data, 'utf8'));
//encryptByprivate是buffer
console.log('encrypted by private key: ' + encryptByprivate.toString('hex'));
return encryptByprivate
}
publicDecrypt(encryptByprivate){
/**
* 公钥解密
*/
let decodeByPublic = crypto.publicDecrypt(this.pubKey, encryptByprivate);
//decodeByPublic 也是buffer
console.log('decrypted by public key: ' + decodeByPublic.toString('utf8'));
return decodeByPublic.toString('utf8')
}
}
let message = Hash('123')
console.log("message", message);
let rsa = new RSAEncrypto()
let priMessage = rsa.privateEncrypt(message)
let pubMessage = rsa.publicDecrypt(priMessage)
console.log("pubMessage", pubMessage);if(pubMessage==message){
console.log('https加密解密成功');
}