【JAVASCRIPT】-【RSA加密解密】02、前端RSA加密解密的实现方式

前言

应项目需求需要使用RSA方式对数据进行加密解密

关于对称非对称加密解密详解参见:浩星博主的文章https://blog.csdn.net/qq_41619796/article/details/118604950

效果

【JAVASCRIPT】-【RSA加密解密】02、前端RSA加密解密的实现方式_第1张图片

前置

1、生成公私钥对

  • 访问在线工具生成:https://www.bejson.com/enc/rsa/
  • 【JAVASCRIPT】-【RSA加密解密】02、前端RSA加密解密的实现方式_第2张图片

实现

1、引入相关依赖jsencrypt.min.js
https://github.com/travist/jsencrypt/blob/master/bin/jsencrypt.min.js
2、代码实现

<button onclick="encrypt()">加密button>
<button onclick="decrypt()">解密button>
<script src="./jsencrypt.min.js">script>
<script type="text/javascript">
  const publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCE0EzejzdAWvix/fHXvwfs5N1JXKAsRsOSwocYGf3rKdlasQwxArdXgyES1ShxqrFgX2rVnBAvlvIQWioTJBAXim7wDrcJFjVF0TPAHzZtLamd/qp0w8ikK99P+ivb5bxniPhIvHFREUvR4hAWQ2gfNHqC3PKuICo655QMOp1rjQIDAQAB'
  const privateKey = 'MIICWwIBAAKBgQCE0EzejzdAWvix/fHXvwfs5N1JXKAsRsOSwocYGf3rKdlasQwxArdXgyES1ShxqrFgX2rVnBAvlvIQWioTJBAXim7wDrcJFjVF0TPAHzZtLamd/qp0w8ikK99P+ivb5bxniPhIvHFREUvR4hAWQ2gfNHqC3PKuICo655QMOp1rjQIDAQABAoGAC4TVZegd7qL1NtrDgua6lT00RAyYh76Lb8sXVGvMrfyvMUJxwD5wEFL7J1r9av5W6/jalzQ14yrAS9LGG2rhSklZ9jF58a55+cVr3VrZxEPzQ3Gs4J2k+xQwb7seG6Z0dHV+YVOwi3SOltk9RssetM2iCnrXsbP9/MA+xddNx4ECQQDDME8qr5YQhXQRxbe9dD7xPEKw4Dnfb9Y3TUFmqUnn62kfACE1YILtk2KFbrrhk4hmUk3sqWSwHHlyfwFswvL1AkEArjEjKwEAbMAzx3aOHVbZICoBi2NwSM0m5i4TGaR+sIZ1aJSU9/A8WDvLbb1HjBlpZBkRlqbDPIscJ6MXJConOQJAROKSvfTT2CbRDMijjNgusoJa4wNvSTy19DRupWWPcKrzIX6xOZ5C9sdyGLc4ew3PMJVRbPlnUIPsFI1gGls+1QJACNsuso0GfID5IPcCGrPDrkL0eSXBG7Jye9lz1yXp2we7CGoleMWaC9JecWHiNVlFZnVv03z/CCD6eXltP8V04QJAN5hqgfbfprfN6tGmlbwW+4GXNkxrr1rF/yA5lVsucpzAKBD3Q9pwTAuTpEiNfEVK0Gi3HfOAHkUD8vTx+K+D2w=='
  const str = 'test 123'

  let enStr = '' // 加密后的字符串

  // 加密
  function encrypt() {
    const crypt = new JSEncrypt({ default_key_size: 1024 }) // 默认密钥字节长度
    crypt.setPublicKey(publicKey) // 公钥加密
    enStr = crypt.encrypt(str)
    console.log('对' + str + '进行加密:', enStr)
  }
  // 解密
  function decrypt(params) {
    const crypt = new JSEncrypt({ default_key_size: 1024 })
    crypt.setPrivateKey(privateKey) // 私钥解密
    console.log('对' + enStr + '进行解密:', crypt.decrypt(enStr))
  }
script>

你可能感兴趣的:(前端,JAVASCRIPT+加密解密)