Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

前端 DES 加密实践 #37

Open
lulujianglab opened this issue Dec 3, 2018 · 0 comments
Open

前端 DES 加密实践 #37

lulujianglab opened this issue Dec 3, 2018 · 0 comments

Comments

@lulujianglab
Copy link
Owner

由于项目中需要对用户登录的密码进行加密处理,特意学习了下,网上有很多 DES 加密的 js 代码,也有一些 java 解密不成功的,问题大都是 解密出来乱码的问题

今天分享的是前端 js 的 DES 加密 - 对称加密,后端使用 java 进行 DES 解密的,这里就不做介绍了

JS端加密过程处理中,比较重要的对 key 的设定以及 DES 加密模式的配定

  1. key 的处理:通过创建指定的 key ,key 必须是 16 位 / 24 位 / 32 位中的一种,常见的加密 Key 24 位的 16 进制

  2. DES 加密模式:常见的两种加密方式是 ECB 和 CBC 模式

我们可以直接采用谷歌的 crypto-js

根据它的文档介绍,需要先安装 crypto-js 依赖

npm install crypto-js

然后引入 crypto-js const CryptoJS = require("crypto-js")

在 github 上,我们可以看到其文档相当详细

image

根据文档介绍我们就可以写出具体的demo了

JS 端的 Demo ,通过DES加密,Base64 编码,需要引入封装好的 DES加密解密算法

// DES加密用户密码
encryptByDES(message) {
  const now = new Date()
  const day = now.getDate() < 10? `0${now.getDate()}` : now.getDate()
  const username = 'zhangsan'
  const firstName = JSON.parse(JSON.stringify(username)).charAt(0)
  const secondName = JSON.parse(JSON.stringify(username)).charAt(1)
  // 秘钥 key
  const key = `${firstName}HAH_${secondName}${day}`
  // 把私钥转换成24位的16进制的字符串,不足24位自动以0(最小位数是0)补齐,如果多余24位,则截取前24位,后面多余则舍弃掉
  const keyHex = CryptoJS.enc.Utf8.parse(key);
  // 加密模式为ECB padding为PKcs7
  const encrypted = CryptoJS.DES.encrypt(message, keyHex, {
      mode: CryptoJS.mode.ECB, // ECB 模式
      padding: CryptoJS.pad.Pkcs7 // padding 处理
  });
  // 加密出来是一个16进制的字符串
  return encrypted.toString();
}

encryptByDES('123456')

这样就对 '123456' 密码进行了 DES 加密,key 在这里设置的是 'zHAH_h03', '03' 表示的当天的日期

加密后的结果类似于

1JQhSMa4Mhk=

参考资料

https://blog.csdn.net/bob_Xing_Yang/article/details/80417383

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant