crypto-js(GitHub)
是谷歌开发的一个纯JavaScript的加密算法类库
,可以非常方便的在前端进行其所支持的加解密操作。目前crypto-js已支持的算法有:MD5,SHA-1,SHA-256,AES,Rabbit,MARC4,HMAC,HMAC-MD5,HMAC-SHA1,HMAC-SHA256,PBKDF2
。常用的加密方式有MD5和AES
使用时可以引用总文件,也可以单独引用某一文件。
http.js
import AES from 'crypto-js/aes'
import Utf8 from 'crypto-js/enc-utf8'
var http = axios.create({
baseURL: '/page'
})
export const createAPI = (url, method, params, config = {}) => {
params._req = Math.random().toString(36).substr(2)
params._enc = AES.encrypt(Utf8.parse(params._req), Utf8.parse('0CoJUm6Qyw8W8jud'), { iv: Utf8.parse('0102030405060708') }).toString()
if (method === 'get') {
config.params = params
} else {
config.data = querystring.stringify(params)
config.headers = { 'Content-Type': 'application/x-www-form-urlencoded', ...config }
}
return http({
url,
method,
...config
})
}
index.js
import { createAPI } from './http'
export default {
// 更新数据
update: params => {
return createAPI('/update', 'post', params)
}
}
import CryptoJS from 'crypto-js'
import axios from 'axios'
axios.post('/users/signin',{
username:self.username,
password:CryptoJS.MD5(self.password).toString()
})
let time = new Date()
let cartNo = md5(Math.random() * 1000 + time).toString()
console.log(cartNo) // 'be39bd8b83cf1349f1b8d11b2c83fc02'