JS + Rails 加密密钥(App Secret 之类的)

js 引入 jsencrypt,直接下载jsencrypt文件也可以

思路是在 js 里生成密钥对,然后把公钥传到 Rails 后端,后端利用公钥加密 Secret 后,返回加密结果,当用户点击查看密钥详情的时候,通过密钥对里的 私钥 + 加密串 = 真实 Secret,这样我们只暴露公钥和加密串,

xxxx.js:

import JSEncrypt form 'js/jsencrypt.min.js'

// default_key_size default: 1024 the key size in bit
let crypt = new JSEncrypt({ default_key_size: 2048 })
let publicKey = crypt.getPublicKey()
let encryptedInformationResult = null

$.ajax({
  type: 'POST',
  url: your_url, // 需要把 publicKey 传到后台,然后将 Secret 加密然后返回加密后的结果
  data: { public_key: publicKey },
  success: function (data) {
    if (data.success) {
      encryptedInformationResult = data.result
    } else {
      console.error(data.message)
    }
  },
})

// 当得到 encryptedInformationResult 后,可以绑定事件了,这里前端没用框架,直接是 .html.slim

// 我这里可能有多个 secret,所以是 json 串,在获取原 secret 串的时候,需要给定一个唯一值,例如 uid
let uncrypted = crypt.decrypt(encryptedInformationResult[uid])
// uncrypted 就是未加密的结果

xxxx.rb

def create
  rsa_key = OpenSSL::PKey::RSA.new(params[:public_key])
  # Applications 有多个
  result = Applications.each_with_object({}) do |app, memo|
    memo[app.uid] = Base64.encode64(rsa_key.public_encrypt(app.secret))
  end
  render_ajax_success(result: result)
rescue => e
  render_ajax_failure("#{e.message}, 请刷新页面并重试!")
end
posted @ 2021-11-07 19:27  Mr-Ran  阅读(385)  评论(0编辑  收藏  举报