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

发布时间:2022-06-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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

脚本宝典总结

以上是脚本宝典为你收集整理的JS + Rails 加密密钥(App Secret 之类的)全部内容,希望文章能够帮你解决JS + Rails 加密密钥(App Secret 之类的)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: