關于RSA加密技術的使用,js前端加密,Golang 后端解密 詳細
關于rsa 加密演算法
可自行參考 rsa演算法
前端JS如何使用rsa進行加密
安裝jsencrypt【二選一】
- github下載地址:鏈接: jsencrypt ,下載完成之后可得到
如下目錄
- npm 安裝
npm i jsencrypt
生成openssl 公鑰和私鑰【公鑰加密,私鑰服務端解密】
- 在需要存盤公鑰和私鑰的檔案夾下,進入控制臺cmd
- 輸入命令,生成私鑰
openssl genrsa -out rsa_1024_priv.pem 1024
- 輸入命令,生成公鑰
openssl rsa -pubout -in rsa_1024_priv.pem -out rsa_1024_pub.pem
修改庫【在小程式上使用必看,瀏覽器可忽略】
在小程式中,引入這個庫會報這樣的錯誤

原因是這個第三方庫使用了 window 物件,而微信小程式的頁面的腳本邏輯是在 JsCore 中運行,JsCore 是一個沒有視窗物件的環境,所以不能在腳本中使用 window,也無法在腳本中操作組件,
給第三方庫添加 window2 和 navigator2 變數
將程式中用到 window 和 navigator 的地方進行全域替換 為window2 和 navigator2,

JS前端加密 rsa.js
# 此處匯入根據自己存放檔案夾的位置
# 注意的是 小程式中 使用此包會出錯 可參考
import {JSEncrypt} from '../jsencrypt/bin/jsencrypt.js';
export function encode(){
var PUBLIC_KEY = '此處填寫你生成的公鑰';
//使用公鑰加密
var encrypt = new JSEncrypt();
encrypt.setPublicKey(PUBLIC_KEY);
var str = {"uid":"1223334","pwd":"asd"}
//此處需要注意,encrypt.encrypt() 中只能傳入字串
return encrypt.encrypt(JSON.stringify(str));
}
Golang服務端解密
# cipherText:加密后的文本 path:存放私鑰的地址
func RSA_Decrypt(cipherText []byte, path string) string {
code, _:= base64.StdEncoding.DecodeString(cipherText)
//打開檔案
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
//獲取檔案內容
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
//pem解碼
block, _ := pem.Decode(buf)
//X509解碼
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
//對密文進行解密
plainText, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, code)
//回傳明文
return string(plainText)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/246907.html
標籤:區塊鏈
上一篇:2021-01-09
