优化引入方式,及uuid算法

master 3.1.0
yutent 2023-02-13 17:19:05 +08:00
parent 3cc8c53a72
commit 5281159c21
4 changed files with 203 additions and 120 deletions

View File

@ -2,6 +2,10 @@
> 本模块是对原生的`crypto`模块二次封装的,在使用上更加简单方便。 > 本模块是对原生的`crypto`模块二次封装的,在使用上更加简单方便。
## 更新日志 ## 更新日志
+ v3.1.0
- 优化`uuid(),rand()`
- 优化库引用方式
+ v3.0.0 + v3.0.0
- Node.js 10.0.0之后不再推荐使用`crypto.createCipher()`, 所以 本库的`cipher()`方法, 内部改为调用`cipheriv()` (Node.js大于10.5.0时, 旧版本的不变) - Node.js 10.0.0之后不再推荐使用`crypto.createCipher()`, 所以 本库的`cipher()`方法, 内部改为调用`cipheriv()` (Node.js大于10.5.0时, 旧版本的不变)
@ -25,7 +29,7 @@ npm install crypto.js
```js ```js
// 1、 传统的 commonJS引入, 所有的方法都在上面 // 1、 传统的 commonJS引入, 所有的方法都在上面
var { var {
default: crypto, origin, // 原生crypto对象
uuid, uuid,
rand, rand,
md5, md5,
@ -41,7 +45,8 @@ var {
// 2、 全新的 ESM 方式 // 2、 全新的 ESM 方式
import crypto from 'crypto.js' import crypto from 'crypto.js'
import { import crypto, {
origin,
uuid, uuid,
rand, rand,
md5, md5,

View File

@ -1,6 +1,6 @@
{ {
"name": "crypto.js", "name": "crypto.js",
"version": "3.0.0", "version": "3.1.0",
"description": "原生crypto加密模块的二次封装,简化常用加密函数的使用", "description": "原生crypto加密模块的二次封装,简化常用加密函数的使用",
"keywords": [ "keywords": [
"md5", "md5",
@ -21,7 +21,9 @@
"dependencies": {}, "dependencies": {},
"devDependencies": {}, "devDependencies": {},
"main": "dist/index.js", "main": "dist/index.js",
"files": ["dist/*"], "files": [
"dist/*"
],
"scripts": { "scripts": {
"start": "node ./build.js" "start": "node ./build.js"
}, },

View File

@ -11,42 +11,73 @@ const AUTH_MODE = [
'aes-192-ocb', 'aes-192-ocb',
'aes-256-ocb' 'aes-256-ocb'
] ]
const VERSION = +process.versions.node const VERSION = +process.versions.node.split('.').slice(0, 2).join('.')
.split('.')
.slice(0, 2)
.join('.')
// <Buffer d7 2c 87 d0 f0 77 c7 76 6f 29 85 df ab 30 e8 95> // <Buffer d7 2c 87 d0 f0 77 c7 76 6f 29 85 df ab 30 e8 95>
const EMPTY_KEY = crypto.scryptSync const EMPTY_KEY = crypto.scryptSync
? crypto.scryptSync('', '', 16) ? crypto.scryptSync('', '', 16)
: Buffer.from( : Buffer.from(
'0xd7 0x2c 0x87 0xd0 0xf0 0x77 0xc7 0x76 0x6f 0x29 0x85 0xdf 0xab 0x30 0xe8 0x95'.split(' ') '0xd7 0x2c 0x87 0xd0 0xf0 0x77 0xc7 0x76 0x6f 0x29 0x85 0xdf 0xab 0x30 0xe8 0x95'.split(
' '
) )
)
//
if (!crypto.randomUUID) {
crypto.randomUUID = function () {
let str = crypto.randomBytes(16).toString('hex')
return (
str.slice(0, 8) +
'-' +
str.slice(8, 12) +
'-' +
str.slice(12, 16) +
'-' +
str.slice(16, 20) +
'-' +
str.slice(-12)
)
}
}
if (!crypto.randomInt) {
crypto.randomInt = function (max) {
if (max === void 0) {
throw new TypeError(
'[ERR_INVALID_ARG_TYPE]: The "max" argument must be a safe integer. Received undefined'
)
}
return ~~(Math.random() * max)
}
}
export default { export const origin = crypto
origin: crypto,
hash(mode, data, outEncode) { export const hash = function (mode, data, outEncode) {
let sum = crypto.createHash(mode) let sum = crypto.createHash(mode)
let isBuffer = Buffer.isBuffer(data) let isBuffer = Buffer.isBuffer(data)
sum.update(data, isBuffer ? 'binary' : 'utf8') sum.update(data, isBuffer ? 'binary' : 'utf8')
return sum.digest(outEncode || 'hex') return sum.digest(outEncode || 'hex')
}, }
hmac(mode, data, key, outEncode) { export const hmac = function (mode, data, key, outEncode) {
key = key || '' key = key || ''
let sum = crypto.createHmac(mode, key) let sum = crypto.createHmac(mode, key)
let isBuffer = Buffer.isBuffer(data) let isBuffer = Buffer.isBuffer(data)
sum.update(data, isBuffer ? 'binary' : 'utf8') sum.update(data, isBuffer ? 'binary' : 'utf8')
return sum.digest(outEncode || 'hex') return sum.digest(outEncode || 'hex')
}, }
cipher(mode, data, key = EMPTY_KEY, inEncode, outEncode) { export const cipher = function (
mode,
data,
key = EMPTY_KEY,
inEncode,
outEncode
) {
// 10.0.0之后, createCipher方法不推荐使用了 // 10.0.0之后, createCipher方法不推荐使用了
if (VERSION >= 10.5) { if (VERSION >= 10.5) {
return this.cipheriv(mode, data, key, EMPTY_KEY, inEncode, outEncode) return cipheriv(mode, data, key, EMPTY_KEY, inEncode, outEncode)
} }
let isBuffer = Buffer.isBuffer(data) let isBuffer = Buffer.isBuffer(data)
inEncode = isBuffer ? 'binary' : inEncode || 'utf8' inEncode = isBuffer ? 'binary' : inEncode || 'utf8'
@ -60,12 +91,19 @@ export default {
return { enStr, authTag } return { enStr, authTag }
} }
return enStr return enStr
}, }
decipher(mode, data, key = EMPTY_KEY, tag, inEncode, outEncode) { export const decipher = function (
mode,
data,
key = EMPTY_KEY,
tag,
inEncode,
outEncode
) {
// 10.0.0之后, createCipher方法不推荐使用了 // 10.0.0之后, createCipher方法不推荐使用了
if (VERSION >= 10.5) { if (VERSION >= 10.5) {
return this.decipheriv(mode, data, key, EMPTY_KEY, tag, inEncode, outEncode) return decipheriv(mode, data, key, EMPTY_KEY, tag, inEncode, outEncode)
} }
let isBuffer = Buffer.isBuffer(data) let isBuffer = Buffer.isBuffer(data)
@ -79,9 +117,16 @@ export default {
let deStr = cd.update(data, inEncode, outEncode) let deStr = cd.update(data, inEncode, outEncode)
deStr += cd.final(outEncode) deStr += cd.final(outEncode)
return deStr return deStr
}, }
cipheriv(mode, data, key = EMPTY_KEY, iv = EMPTY_KEY, inEncode, outEncode) { export const cipheriv = function (
mode,
data,
key = EMPTY_KEY,
iv = EMPTY_KEY,
inEncode,
outEncode
) {
let isBuffer = Buffer.isBuffer(data) let isBuffer = Buffer.isBuffer(data)
inEncode = isBuffer ? 'binary' : inEncode || 'utf8' inEncode = isBuffer ? 'binary' : inEncode || 'utf8'
outEncode = outEncode || 'base64' outEncode = outEncode || 'base64'
@ -94,9 +139,17 @@ export default {
return { enStr, authTag } return { enStr, authTag }
} }
return enStr return enStr
}, }
decipheriv(mode, data, key = EMPTY_KEY, iv = EMPTY_KEY, tag, inEncode, outEncode) { export const decipheriv = function (
mode,
data,
key = EMPTY_KEY,
iv = EMPTY_KEY,
tag,
inEncode,
outEncode
) {
let isBuffer = Buffer.isBuffer(data) let isBuffer = Buffer.isBuffer(data)
inEncode = isBuffer ? 'binary' : inEncode || 'base64' inEncode = isBuffer ? 'binary' : inEncode || 'base64'
outEncode = outEncode || 'utf8' outEncode = outEncode || 'utf8'
@ -108,5 +161,4 @@ export default {
let deStr = dcpiv.update(data, inEncode, outEncode) let deStr = dcpiv.update(data, inEncode, outEncode)
deStr += dcpiv.final(outEncode) deStr += dcpiv.final(outEncode)
return deStr return deStr
}
} }

View File

@ -6,19 +6,28 @@
import os from 'os' import os from 'os'
import fs from 'fs' import fs from 'fs'
import Helper from './helper.mjs' import {
origin,
hash,
hmac,
cipher,
decipher,
cipheriv,
decipheriv
} from './helper.mjs'
const MAC = (function(ns) { const MAC = (function (ns) {
for (let k in ns) { for (let k in ns) {
if (k === 'lo') {
continue
}
let _ = ns[k].pop() let _ = ns[k].pop()
if (_.mac !== '00:00:00:00:00:00') { return _.mac.replace(/:/g, '').slice(-4)
return _.mac
} }
} return Math.random().toString(16).slice(-4)
return process.pid.toString(16) + process.ppid.toString(16)
})(os.networkInterfaces()) })(os.networkInterfaces())
var __inc__ = 1024 var __inc__ = 1
/** /**
* [base64encode base64编码] * [base64encode base64编码]
@ -37,10 +46,7 @@ export function base64encode(str, urlFriendly) {
str64 = buf.toString('base64') str64 = buf.toString('base64')
if (urlFriendly) { if (urlFriendly) {
return str64 return str64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '')
} }
return str64 return str64
} }
@ -73,25 +79,23 @@ export function rand(len, forceNum) {
let max = str.length let max = str.length
let tmp = '' let tmp = ''
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
let r = (Math.random() * max) >> 0 tmp += str[origin.randomInt(max)]
tmp += str[r]
} }
return tmp return tmp
} }
// 返回一个如下格式的 xxxxxxxx-xxxx-xxxx-xxxxxxxx 的唯一ID // 返回一个如下格式的 xxxxxxxx-xxxx-xxxx-xxxxxxxx 的唯一ID
export function uuid(pipe = '-') { export function uuid(pipe = '-') {
var rand = Helper.origin.randomBytes(8).toString('hex') var str = origin.randomUUID()
var now = (~~(Date.now() / 1000)).toString(16) var now = (~~(Date.now() / 1000)).toString(16)
var str
__inc__++ __inc__++
if (__inc__ > 65535) { if (__inc__ > 65535) {
__inc__ = 1024 __inc__ = 1
} }
str = md5(MAC + rand + __inc__) str += __inc__.toString(16)
return now + pipe + str.slice(0, 4) + pipe + str.slice(4, 8) + pipe + str.slice(-8) return now + pipe + MAC + pipe + str.slice(0, 4) + pipe + str.slice(-8)
} }
/** /**
@ -105,7 +109,7 @@ export function md5(str, encode) {
} }
if (typeof str === 'string' || Buffer.isBuffer(str)) { if (typeof str === 'string' || Buffer.isBuffer(str)) {
return Helper.hash('md5', str, encode) return hash('md5', str, encode)
} }
return str return str
@ -118,7 +122,7 @@ export function md5(str, encode) {
export function md5Sign(file) { export function md5Sign(file) {
if (fs.accessSync(file, fs.constants.R_OK)) { if (fs.accessSync(file, fs.constants.R_OK)) {
var buf = fs.readFileSync(file) var buf = fs.readFileSync(file)
return Helper.hash('md5', buf) return hash('md5', buf)
} }
return null return null
} }
@ -133,7 +137,7 @@ export function sha1(str, encode) {
str += '' str += ''
} }
if (typeof str === 'string' || Buffer.isBuffer(str)) { if (typeof str === 'string' || Buffer.isBuffer(str)) {
return Helper.hash('sha1', str, encode) return hash('sha1', str, encode)
} }
return str return str
@ -146,7 +150,7 @@ export function sha1(str, encode) {
export function sha1Sign(file) { export function sha1Sign(file) {
if (fs.accessSync(file, fs.constants.R_OK)) { if (fs.accessSync(file, fs.constants.R_OK)) {
var buf = fs.readFileSync(file) var buf = fs.readFileSync(file)
return Helper.hash('sha1', buf) return hash('sha1', buf)
} }
return null return null
} }
@ -161,7 +165,7 @@ export function sha256(str, encoding) {
str += '' str += ''
} }
if (typeof str === 'string' || Buffer.isBuffer(str)) { if (typeof str === 'string' || Buffer.isBuffer(str)) {
return Helper.hash('sha256', str, encoding) return hash('sha256', str, encoding)
} }
return str return str
@ -174,9 +178,29 @@ export function sha256(str, encoding) {
export function sha256Sign(file) { export function sha256Sign(file) {
if (fs.accessSync(file, fs.constants.R_OK)) { if (fs.accessSync(file, fs.constants.R_OK)) {
var buf = fs.readFileSync(file) var buf = fs.readFileSync(file)
return Helper.hash('sha256', buf) return hash('sha256', buf)
} }
return null return null
} }
export default Helper export { origin, hash, hmac, cipher, decipher, cipheriv, decipheriv }
export default {
base64encode,
base64decode,
rand,
uuid,
md5,
md5Sign,
sha1,
sha1Sign,
sha256,
sha256Sign,
origin,
hash,
hmac,
cipher,
decipher,
cipheriv,
decipheriv
}