From b2abb16e81ed6aa4b1a130fab1050f4c08bd7cfa Mon Sep 17 00:00:00 2001 From: Luk Lu Date: Fri, 29 Apr 2022 15:21:52 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=20b64u=20=E7=9A=84=E5=AE=9A?= =?UTF-8?q?=E4=B9=89=EF=BC=8C=E7=94=A8=20.=20=E4=BB=A3=E6=9B=BF=20-?= =?UTF-8?q?=EF=BC=8C=E5=9B=A0=E4=B8=BA=20-=20=E5=92=8C=E7=A9=BA=E6=A0=BC?= =?UTF-8?q?=E4=B8=80=E6=A0=B7=E5=AF=BC=E8=87=B4=20css=20white-space=20?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=8D=A2=E8=A1=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.js | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/index.js b/index.js index 72101db..8667817 100644 --- a/index.js +++ b/index.js @@ -726,7 +726,7 @@ class TICrypto { if (hex) { 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 [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) // 内容合法 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(b64, 'base64').toString('hex') + let hex = Buffer.from(this.b64u_to_b64(address), 'base64').toString('hex') 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) // [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 * @@ -1264,7 +1279,7 @@ class TICrypto { */ static hex2b64u(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 } @@ -1278,9 +1293,8 @@ class TICrypto { * @memberof TICrypto */ static b64u2hex(b64u) { - if (/^[0-9a-zA-Z\-_]+$/.test(b64u)) { - let b64 = b64u.replace(/\-/g, '+').replace(/_/g, '/') - return Buffer.from(b64, 'base64').toString('hex') + if (/^[0-9a-zA-Z\._]+$/.test(b64u)) { + return Buffer.from(this.b64u_to_b64(b64u), 'base64').toString('hex') } return null }