优化 b64u 的定义,用 . 代替 -,因为 - 和空格一样导致 css white-space 自动换行

This commit is contained in:
陆柯 2022-04-29 15:21:52 +08:00
parent fcf41dd77e
commit b2abb16e81

View File

@ -726,7 +726,7 @@ class TICrypto {
if (hex) { if (hex) {
return hex.slice(2) // 去除网络前缀 return hex.slice(2) // 去除网络前缀
} }
} else if (/^[Tt][0-9a-zA-Z\-_]{31}$/.test(address)) { // TIC } else if (/^[Tt][0-9a-zA-Z\._]{31}$/.test(address)) { // TIC
// 格式合法 // 格式合法
let hex = this.b64u2hex(address) let hex = this.b64u2hex(address)
let [all, prefix, position, checksum] = hex.match(/^([\da-fA-F]{2})([\da-fA-F]{40})([\da-fA-F]{6})$/) let [all, prefix, position, checksum] = hex.match(/^([\da-fA-F]{2})([\da-fA-F]{40})([\da-fA-F]{6})$/)
@ -754,10 +754,9 @@ class TICrypto {
if (prefixedPosition && prefixedPosition.length === 42) if (prefixedPosition && prefixedPosition.length === 42)
// 内容合法 // 内容合法
return 'BTC' return 'BTC'
} else if (/^[Ttd][0-9a-zA-Z\-_]{31}$/.test(address)) { } else if (/^[Ttd][0-9a-zA-Z\._]{31}$/.test(address)) {
// 格式合法 // 格式合法
let b64 = address.replace('-', '+').replace('_', '/') let hex = Buffer.from(this.b64u_to_b64(address), 'base64').toString('hex')
let hex = Buffer.from(b64, 'base64').toString('hex')
let [all, prefix, position, checksum] = hex.match(/^([\da-fA-F]{2})([\da-fA-F]{40})([\da-fA-F]{6})$/) // 内容合法 let [all, prefix, position, checksum] = hex.match(/^([\da-fA-F]{2})([\da-fA-F]{40})([\da-fA-F]{6})$/) // 内容合法
if (this.hash(this.hash(prefix + position)).slice(0, 6) === checksum) if (this.hash(this.hash(prefix + position)).slice(0, 6) === checksum)
// [todo] 校验码里要不要包含 prefix? // [todo] 校验码里要不要包含 prefix?
@ -1254,6 +1253,22 @@ class TICrypto {
} }
} }
/**
* b64 字符串为 a-zA-Z0-9+/
* 其中+ / 会在 url query string 里被转成 %2B %2F
* 因此定义 b64u (base64 for url) . _ 替换
* 为何不用 -因为 - 和空格一样导致 css white-space 自动换行
* @param {*} b64
* @returns
*/
static b64_to_b64u(b64='') {
return b64.replace(/\+/g, '.').replace(/\//g, '_').replace(/=/g, '')
}
static b64u_to_b64(b64u='') {
return b64u.replace(/\./g, '+').replace(/_/g, '/')
}
/** /**
* 十六进制转b64u * 十六进制转b64u
* *
@ -1264,7 +1279,7 @@ class TICrypto {
*/ */
static hex2b64u(hex) { static hex2b64u(hex) {
if (/^[0-9a-fA-F]+$/.test(hex)) { if (/^[0-9a-fA-F]+$/.test(hex)) {
return Buffer.from(hex, 'hex').toString('base64').replace(/\+/g, '-').replace(/\//g, '_') return this.b64_to_b64u(Buffer.from(hex, 'hex').toString('base64'))
} }
return null return null
} }
@ -1278,9 +1293,8 @@ class TICrypto {
* @memberof TICrypto * @memberof TICrypto
*/ */
static b64u2hex(b64u) { static b64u2hex(b64u) {
if (/^[0-9a-zA-Z\-_]+$/.test(b64u)) { if (/^[0-9a-zA-Z\._]+$/.test(b64u)) {
let b64 = b64u.replace(/\-/g, '+').replace(/_/g, '/') return Buffer.from(this.b64u_to_b64(b64u), 'base64').toString('hex')
return Buffer.from(b64, 'base64').toString('hex')
} }
return null return null
} }