1
This commit is contained in:
3
nx/utils/gm-crypto/lib/sm2/const.js
Normal file
3
nx/utils/gm-crypto/lib/sm2/const.js
Normal file
@@ -0,0 +1,3 @@
|
||||
export const C1C2C3 = 0
|
||||
export const C1C3C2 = 1
|
||||
export const PC = '04' // 未压缩
|
||||
415
nx/utils/gm-crypto/lib/sm2/ec.js
Normal file
415
nx/utils/gm-crypto/lib/sm2/ec.js
Normal file
@@ -0,0 +1,415 @@
|
||||
// Basic Javascript Elliptic Curve implementation
|
||||
// Ported loosely from BouncyCastle's Java EC code
|
||||
// Only Fp curves implemented for now
|
||||
|
||||
// Requires jsbn.js and jsbn2.js
|
||||
import { BigInteger } from 'jsbn'
|
||||
const { Barrett } = BigInteger.prototype
|
||||
|
||||
// Basic Javascript Elliptic Curve implementation
|
||||
// Ported loosely from BouncyCastle's Java EC code
|
||||
// Only Fp curves implemented for now
|
||||
|
||||
// Requires jsbn.js and jsbn2.js
|
||||
|
||||
// ----------------
|
||||
// ECFieldElementFp
|
||||
|
||||
// constructor
|
||||
function ECFieldElementFp(q, x) {
|
||||
this.x = x
|
||||
// TODO if(x.compareTo(q) >= 0) error
|
||||
this.q = q
|
||||
}
|
||||
|
||||
function feFpEquals(other) {
|
||||
if (other == this) return true
|
||||
return this.q.equals(other.q) && this.x.equals(other.x)
|
||||
}
|
||||
|
||||
function feFpToBigInteger() {
|
||||
return this.x
|
||||
}
|
||||
|
||||
function feFpNegate() {
|
||||
return new ECFieldElementFp(this.q, this.x.negate().mod(this.q))
|
||||
}
|
||||
|
||||
function feFpAdd(b) {
|
||||
return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q))
|
||||
}
|
||||
|
||||
function feFpSubtract(b) {
|
||||
return new ECFieldElementFp(
|
||||
this.q,
|
||||
this.x.subtract(b.toBigInteger()).mod(this.q)
|
||||
)
|
||||
}
|
||||
|
||||
function feFpMultiply(b) {
|
||||
return new ECFieldElementFp(
|
||||
this.q,
|
||||
this.x.multiply(b.toBigInteger()).mod(this.q)
|
||||
)
|
||||
}
|
||||
|
||||
function feFpSquare() {
|
||||
return new ECFieldElementFp(this.q, this.x.square().mod(this.q))
|
||||
}
|
||||
|
||||
function feFpDivide(b) {
|
||||
return new ECFieldElementFp(
|
||||
this.q,
|
||||
this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)
|
||||
)
|
||||
}
|
||||
|
||||
ECFieldElementFp.prototype.equals = feFpEquals
|
||||
ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger
|
||||
ECFieldElementFp.prototype.negate = feFpNegate
|
||||
ECFieldElementFp.prototype.add = feFpAdd
|
||||
ECFieldElementFp.prototype.subtract = feFpSubtract
|
||||
ECFieldElementFp.prototype.multiply = feFpMultiply
|
||||
ECFieldElementFp.prototype.square = feFpSquare
|
||||
ECFieldElementFp.prototype.divide = feFpDivide
|
||||
|
||||
// ----------------
|
||||
// ECPointFp
|
||||
|
||||
// constructor
|
||||
export function ECPointFp(curve, x, y, z) {
|
||||
this.curve = curve
|
||||
this.x = x
|
||||
this.y = y
|
||||
// Projective coordinates: either zinv == null or z * zinv == 1
|
||||
// z and zinv are just BigIntegers, not fieldElements
|
||||
if (z == null) {
|
||||
this.z = BigInteger.ONE
|
||||
} else {
|
||||
this.z = z
|
||||
}
|
||||
this.zinv = null
|
||||
//TODO: compression flag
|
||||
}
|
||||
|
||||
function pointFpGetX() {
|
||||
if (this.zinv == null) {
|
||||
this.zinv = this.z.modInverse(this.curve.q)
|
||||
}
|
||||
var r = this.x.toBigInteger().multiply(this.zinv)
|
||||
this.curve.reduce(r)
|
||||
return this.curve.fromBigInteger(r)
|
||||
}
|
||||
|
||||
function pointFpGetY() {
|
||||
if (this.zinv == null) {
|
||||
this.zinv = this.z.modInverse(this.curve.q)
|
||||
}
|
||||
var r = this.y.toBigInteger().multiply(this.zinv)
|
||||
this.curve.reduce(r)
|
||||
return this.curve.fromBigInteger(r)
|
||||
}
|
||||
|
||||
function pointFpEquals(other) {
|
||||
if (other == this) return true
|
||||
if (this.isInfinity()) return other.isInfinity()
|
||||
if (other.isInfinity()) return this.isInfinity()
|
||||
var u, v
|
||||
// u = Y2 * Z1 - Y1 * Z2
|
||||
u = other.y
|
||||
.toBigInteger()
|
||||
.multiply(this.z)
|
||||
.subtract(this.y.toBigInteger().multiply(other.z))
|
||||
.mod(this.curve.q)
|
||||
if (!u.equals(BigInteger.ZERO)) return false
|
||||
// v = X2 * Z1 - X1 * Z2
|
||||
v = other.x
|
||||
.toBigInteger()
|
||||
.multiply(this.z)
|
||||
.subtract(this.x.toBigInteger().multiply(other.z))
|
||||
.mod(this.curve.q)
|
||||
return v.equals(BigInteger.ZERO)
|
||||
}
|
||||
|
||||
function pointFpIsInfinity() {
|
||||
if (this.x == null && this.y == null) return true
|
||||
return (
|
||||
this.z.equals(BigInteger.ZERO) &&
|
||||
!this.y.toBigInteger().equals(BigInteger.ZERO)
|
||||
)
|
||||
}
|
||||
|
||||
function pointFpNegate() {
|
||||
return new ECPointFp(this.curve, this.x, this.y.negate(), this.z)
|
||||
}
|
||||
|
||||
function pointFpAdd(b) {
|
||||
if (this.isInfinity()) return b
|
||||
if (b.isInfinity()) return this
|
||||
|
||||
// u = Y2 * Z1 - Y1 * Z2
|
||||
var u = b.y
|
||||
.toBigInteger()
|
||||
.multiply(this.z)
|
||||
.subtract(this.y.toBigInteger().multiply(b.z))
|
||||
.mod(this.curve.q)
|
||||
// v = X2 * Z1 - X1 * Z2
|
||||
var v = b.x
|
||||
.toBigInteger()
|
||||
.multiply(this.z)
|
||||
.subtract(this.x.toBigInteger().multiply(b.z))
|
||||
.mod(this.curve.q)
|
||||
|
||||
if (BigInteger.ZERO.equals(v)) {
|
||||
if (BigInteger.ZERO.equals(u)) {
|
||||
return this.twice() // this == b, so double
|
||||
}
|
||||
return this.curve.getInfinity() // this = -b, so infinity
|
||||
}
|
||||
|
||||
var THREE = new BigInteger('3')
|
||||
var x1 = this.x.toBigInteger()
|
||||
var y1 = this.y.toBigInteger()
|
||||
var x2 = b.x.toBigInteger()
|
||||
var y2 = b.y.toBigInteger()
|
||||
|
||||
var v2 = v.square()
|
||||
var v3 = v2.multiply(v)
|
||||
var x1v2 = x1.multiply(v2)
|
||||
var zu2 = u.square().multiply(this.z)
|
||||
|
||||
// x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
|
||||
var x3 = zu2
|
||||
.subtract(x1v2.shiftLeft(1))
|
||||
.multiply(b.z)
|
||||
.subtract(v3)
|
||||
.multiply(v)
|
||||
.mod(this.curve.q)
|
||||
// y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
|
||||
var y3 = x1v2
|
||||
.multiply(THREE)
|
||||
.multiply(u)
|
||||
.subtract(y1.multiply(v3))
|
||||
.subtract(zu2.multiply(u))
|
||||
.multiply(b.z)
|
||||
.add(u.multiply(v3))
|
||||
.mod(this.curve.q)
|
||||
// z3 = v^3 * z1 * z2
|
||||
var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q)
|
||||
|
||||
return new ECPointFp(
|
||||
this.curve,
|
||||
this.curve.fromBigInteger(x3),
|
||||
this.curve.fromBigInteger(y3),
|
||||
z3
|
||||
)
|
||||
}
|
||||
|
||||
function pointFpTwice() {
|
||||
if (this.isInfinity()) return this
|
||||
if (this.y.toBigInteger().signum() == 0) return this.curve.getInfinity()
|
||||
|
||||
// TODO: optimized handling of constants
|
||||
var THREE = new BigInteger('3')
|
||||
var x1 = this.x.toBigInteger()
|
||||
var y1 = this.y.toBigInteger()
|
||||
|
||||
var y1z1 = y1.multiply(this.z)
|
||||
var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q)
|
||||
var a = this.curve.a.toBigInteger()
|
||||
|
||||
// w = 3 * x1^2 + a * z1^2
|
||||
var w = x1.square().multiply(THREE)
|
||||
if (!BigInteger.ZERO.equals(a)) {
|
||||
w = w.add(this.z.square().multiply(a))
|
||||
}
|
||||
w = w.mod(this.curve.q)
|
||||
//this.curve.reduce(w);
|
||||
// x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
|
||||
var x3 = w
|
||||
.square()
|
||||
.subtract(x1.shiftLeft(3).multiply(y1sqz1))
|
||||
.shiftLeft(1)
|
||||
.multiply(y1z1)
|
||||
.mod(this.curve.q)
|
||||
// y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
|
||||
var y3 = w
|
||||
.multiply(THREE)
|
||||
.multiply(x1)
|
||||
.subtract(y1sqz1.shiftLeft(1))
|
||||
.shiftLeft(2)
|
||||
.multiply(y1sqz1)
|
||||
.subtract(w.square().multiply(w))
|
||||
.mod(this.curve.q)
|
||||
// z3 = 8 * (y1 * z1)^3
|
||||
var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q)
|
||||
|
||||
return new ECPointFp(
|
||||
this.curve,
|
||||
this.curve.fromBigInteger(x3),
|
||||
this.curve.fromBigInteger(y3),
|
||||
z3
|
||||
)
|
||||
}
|
||||
|
||||
// Simple NAF (Non-Adjacent Form) multiplication algorithm
|
||||
// TODO: modularize the multiplication algorithm
|
||||
function pointFpMultiply(k) {
|
||||
if (this.isInfinity()) return this
|
||||
if (k.signum() == 0) return this.curve.getInfinity()
|
||||
|
||||
var e = k
|
||||
var h = e.multiply(new BigInteger('3'))
|
||||
|
||||
var neg = this.negate()
|
||||
var R = this
|
||||
|
||||
var i
|
||||
for (i = h.bitLength() - 2; i > 0; --i) {
|
||||
R = R.twice()
|
||||
|
||||
var hBit = h.testBit(i)
|
||||
var eBit = e.testBit(i)
|
||||
|
||||
if (hBit != eBit) {
|
||||
R = R.add(hBit ? this : neg)
|
||||
}
|
||||
}
|
||||
|
||||
return R
|
||||
}
|
||||
|
||||
// Compute this*j + x*k (simultaneous multiplication)
|
||||
function pointFpMultiplyTwo(j, x, k) {
|
||||
var i
|
||||
if (j.bitLength() > k.bitLength()) i = j.bitLength() - 1
|
||||
else i = k.bitLength() - 1
|
||||
|
||||
var R = this.curve.getInfinity()
|
||||
var both = this.add(x)
|
||||
while (i >= 0) {
|
||||
R = R.twice()
|
||||
if (j.testBit(i)) {
|
||||
if (k.testBit(i)) {
|
||||
R = R.add(both)
|
||||
} else {
|
||||
R = R.add(this)
|
||||
}
|
||||
} else {
|
||||
if (k.testBit(i)) {
|
||||
R = R.add(x)
|
||||
}
|
||||
}
|
||||
--i
|
||||
}
|
||||
|
||||
return R
|
||||
}
|
||||
|
||||
ECPointFp.prototype.getX = pointFpGetX
|
||||
ECPointFp.prototype.getY = pointFpGetY
|
||||
ECPointFp.prototype.equals = pointFpEquals
|
||||
ECPointFp.prototype.isInfinity = pointFpIsInfinity
|
||||
ECPointFp.prototype.negate = pointFpNegate
|
||||
ECPointFp.prototype.add = pointFpAdd
|
||||
ECPointFp.prototype.twice = pointFpTwice
|
||||
ECPointFp.prototype.multiply = pointFpMultiply
|
||||
ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo
|
||||
|
||||
// ----------------
|
||||
// ECCurveFp
|
||||
|
||||
// constructor
|
||||
export function ECCurveFp(q, a, b) {
|
||||
this.q = q
|
||||
this.a = this.fromBigInteger(a)
|
||||
this.b = this.fromBigInteger(b)
|
||||
this.infinity = new ECPointFp(this, null, null)
|
||||
this.reducer = new Barrett(this.q)
|
||||
}
|
||||
|
||||
function curveFpGetQ() {
|
||||
return this.q
|
||||
}
|
||||
|
||||
function curveFpGetA() {
|
||||
return this.a
|
||||
}
|
||||
|
||||
function curveFpGetB() {
|
||||
return this.b
|
||||
}
|
||||
|
||||
function curveFpEquals(other) {
|
||||
if (other == this) return true
|
||||
return (
|
||||
this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)
|
||||
)
|
||||
}
|
||||
|
||||
function curveFpGetInfinity() {
|
||||
return this.infinity
|
||||
}
|
||||
|
||||
function curveFpFromBigInteger(x) {
|
||||
return new ECFieldElementFp(this.q, x)
|
||||
}
|
||||
|
||||
function curveReduce(x) {
|
||||
this.reducer.reduce(x)
|
||||
}
|
||||
|
||||
// for now, work with hex strings because they're easier in JS
|
||||
function curveFpDecodePointHex(s) {
|
||||
switch (
|
||||
parseInt(s.substr(0, 2), 16) // first byte
|
||||
) {
|
||||
case 0:
|
||||
return this.infinity
|
||||
case 2:
|
||||
case 3:
|
||||
// point compression not supported yet
|
||||
return null
|
||||
case 4:
|
||||
case 6:
|
||||
case 7:
|
||||
var len = (s.length - 2) / 2
|
||||
var xHex = s.substr(2, len)
|
||||
var yHex = s.substr(len + 2, len)
|
||||
|
||||
return new ECPointFp(
|
||||
this,
|
||||
this.fromBigInteger(new BigInteger(xHex, 16)),
|
||||
this.fromBigInteger(new BigInteger(yHex, 16))
|
||||
)
|
||||
|
||||
default:
|
||||
// unsupported
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function curveFpEncodePointHex(p) {
|
||||
if (p.isInfinity()) return '00'
|
||||
var xHex = p.getX().toBigInteger().toString(16)
|
||||
var yHex = p.getY().toBigInteger().toString(16)
|
||||
var oLen = this.getQ().toString(16).length
|
||||
if (oLen % 2 != 0) oLen++
|
||||
while (xHex.length < oLen) {
|
||||
xHex = '0' + xHex
|
||||
}
|
||||
while (yHex.length < oLen) {
|
||||
yHex = '0' + yHex
|
||||
}
|
||||
return '04' + xHex + yHex
|
||||
}
|
||||
|
||||
ECCurveFp.prototype.getQ = curveFpGetQ
|
||||
ECCurveFp.prototype.getA = curveFpGetA
|
||||
ECCurveFp.prototype.getB = curveFpGetB
|
||||
ECCurveFp.prototype.equals = curveFpEquals
|
||||
ECCurveFp.prototype.getInfinity = curveFpGetInfinity
|
||||
ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger
|
||||
ECCurveFp.prototype.reduce = curveReduce
|
||||
ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex
|
||||
ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex
|
||||
238
nx/utils/gm-crypto/lib/sm2/index.js
Normal file
238
nx/utils/gm-crypto/lib/sm2/index.js
Normal file
@@ -0,0 +1,238 @@
|
||||
import toArrayBuffer from 'to-arraybuffer'
|
||||
import { Buffer } from 'buffer' // 兼容浏览器环境
|
||||
import { BigInteger, SecureRandom } from 'jsbn'
|
||||
|
||||
import { ECCurveFp } from './ec'
|
||||
import { C1C2C3, C1C3C2, PC } from './const'
|
||||
import { leftPad } from '../utils'
|
||||
import { digest } from '../sm3'
|
||||
|
||||
// SM2 相关常量
|
||||
export const constants = { C1C2C3, C1C3C2, PC }
|
||||
|
||||
const rng = new SecureRandom()
|
||||
const { curve, G, n } = (() => {
|
||||
// p: 大于 3 的素数
|
||||
const p = new BigInteger(
|
||||
'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF',
|
||||
16
|
||||
)
|
||||
// a,b: Fq 中的元素,它们定义 Fq 上的一条椭圆曲线 E
|
||||
const a = new BigInteger(
|
||||
'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC',
|
||||
16
|
||||
)
|
||||
const b = new BigInteger(
|
||||
'28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93',
|
||||
16
|
||||
)
|
||||
const curve = new ECCurveFp(p, a, b)
|
||||
|
||||
// 椭圆曲线的一个基点,其阶为素数
|
||||
const gxHex =
|
||||
'32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7'
|
||||
const gyHex =
|
||||
'BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0'
|
||||
const G = curve.decodePointHex(PC + gxHex + gyHex)
|
||||
|
||||
// 基点 G 的阶
|
||||
const n = new BigInteger(
|
||||
'FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123',
|
||||
16
|
||||
)
|
||||
|
||||
return { curve, G, n }
|
||||
})()
|
||||
|
||||
/**
|
||||
* 密钥派生函数
|
||||
* a) 初始化一个 32 比特构成的计数器 ct=0x00000001
|
||||
* b) 对 i 从 1 到 ⌈klen/v⌉ 执行
|
||||
* b.1) 计算 Hai=Hv(Z ∥ ct)
|
||||
* b.2) ct++;
|
||||
* c) 若 klen/v 是整数,令 Ha!⌈klen/v⌉ = Ha⌈klen/v⌉,否则令 Ha!⌈klen/v⌉ 为 Ha⌈klen/v⌉ 最左边的 (klen − (v × ⌊klen/v⌋)) 比特
|
||||
* d) 令K = Ha1||Ha2|| · · · ||Ha⌈klen/v⌉−1||Ha!⌈klen/v⌉
|
||||
*/
|
||||
function KDF(Z, klen) {
|
||||
const list = []
|
||||
const times = Math.ceil(klen / 32)
|
||||
const mod = klen % 32
|
||||
|
||||
for (let i = 1; i <= times; i++) {
|
||||
const ct = Buffer.allocUnsafe(4)
|
||||
ct.writeUInt32BE(i)
|
||||
|
||||
const hash = digest(Buffer.concat([Z, ct]))
|
||||
// Fix: 浏览器端 Buffer.concat 实现有问题,处理不了 list 总长度超过 klen 的情况
|
||||
list.push(
|
||||
i === times && mod ? Buffer.from(hash).slice(0, mod) : Buffer.from(hash)
|
||||
)
|
||||
}
|
||||
|
||||
return Buffer.concat(list, klen)
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成密钥对
|
||||
* a) 用随机数发生器产生整数 d ∈ [1,n−2]
|
||||
* b) G 为基点,计算点 P = (xP,yP) = [d]G
|
||||
* c) 密钥对是 (d,P),其中 d 为私钥,P 为公钥
|
||||
*/
|
||||
export const generateKeyPair = () => {
|
||||
// a) 用随机数发生器产生整数 d ∈ [1,n−2]
|
||||
const d = new BigInteger(n.bitLength(), rng)
|
||||
.mod(n.subtract(new BigInteger('2')))
|
||||
.add(BigInteger.ONE)
|
||||
|
||||
const privateKey = leftPad(d.toString(16), 64)
|
||||
|
||||
// b) G 为基点,计算点 P = (xP,yP) = [d]G
|
||||
const P = G.multiply(d)
|
||||
const Px = leftPad(P.getX().toBigInteger().toString(16), 64)
|
||||
const Py = leftPad(P.getY().toBigInteger().toString(16), 64)
|
||||
const publicKey = PC + Px + Py
|
||||
|
||||
// 密钥对是 (d,P),其中 d 为私钥,P 为公钥
|
||||
return { privateKey, publicKey }
|
||||
}
|
||||
|
||||
/**
|
||||
* 设需要发送的消息为比特串 M,klen 为 M 的比特长度。
|
||||
* 为了对明文 M 进行加密,作为加密者的用户 A 应实现以下运算步骤:
|
||||
* A1:用随机数发生器产生随机数 k∈[1,n-1]
|
||||
* A2:计算椭圆曲线点 C1=[k]G=(x1,y1)
|
||||
* A3:计算椭圆曲线点 S=[h]PB,若 S 是无穷远点,则报错并退出
|
||||
* A4:计算椭圆曲线点 [k]PB=(x2,y2)
|
||||
* A5:计算 t=KDF(x2 ∥ y2, klen),若 t 为全 0 比特串,则返回 A1
|
||||
* A6:计算 C2 = M ⊕ t;
|
||||
* A7:计算 C3 = Hash(x2 ∥ M ∥ y2);
|
||||
* A8:输出密文 C = C1 ∥ C2 ∥ C3 or C1 ∥ C3 ∥ C2
|
||||
*
|
||||
* @param {string|Buffer|ArrayBuffer} data
|
||||
* @param {string} publicKey
|
||||
*/
|
||||
export function encrypt(data, publicKey, options) {
|
||||
const { mode = C1C3C2, inputEncoding, outputEncoding, pc } = options || {}
|
||||
|
||||
// 明文消息类型校验 `string` | `ArrayBuffer` | `Buffer`
|
||||
if (typeof data === 'string') {
|
||||
data = Buffer.from(data, inputEncoding || 'utf8')
|
||||
} else if (data instanceof ArrayBuffer) {
|
||||
data = Buffer.from(data)
|
||||
}
|
||||
if (!Buffer.isBuffer(data)) {
|
||||
throw new TypeError(
|
||||
`Expected "string" | "Buffer" | "ArrayBuffer" but received "${Object.prototype.toString.call(
|
||||
data
|
||||
)}"`
|
||||
)
|
||||
}
|
||||
|
||||
// 随机数 k∈[1,n-1]
|
||||
const k = new BigInteger(n.bitLength(), rng)
|
||||
.mod(n.subtract(BigInteger.ONE))
|
||||
.add(BigInteger.ONE)
|
||||
|
||||
// C1 = [k]G = (x1,y1)
|
||||
const point1 = G.multiply(k)
|
||||
const x1 = leftPad(point1.getX().toBigInteger().toString(16), 64)
|
||||
const y1 = leftPad(point1.getY().toBigInteger().toString(16), 64)
|
||||
const C1 = x1 + y1
|
||||
|
||||
// TODO: 计算椭圆曲线点 S=[h]PB,若 S 是无穷远点,则报错并退出
|
||||
|
||||
// [k]PB = (x2,y2)
|
||||
const point2 = curve.decodePointHex(publicKey).multiply(k)
|
||||
const x2 = leftPad(point2.getX().toBigInteger().toString(16), 64)
|
||||
const y2 = leftPad(point2.getY().toBigInteger().toString(16), 64)
|
||||
|
||||
// t = KDF(x2 ∥ y2, klen),若 t 为全 0 比特串,则返回 A1
|
||||
const t = KDF(Buffer.from(x2 + y2, 'hex'), data.length)
|
||||
|
||||
// C2 = M ⊕ t
|
||||
const C2 = leftPad(
|
||||
new BigInteger(data.toString('hex'), 16)
|
||||
.xor(new BigInteger(t.toString('hex'), 16))
|
||||
.toString(16),
|
||||
data.length * 2
|
||||
)
|
||||
|
||||
// C3 = Hash(x2 ∥ M ∥ y2)
|
||||
const C3 = digest(x2 + data.toString('hex') + y2, 'hex', 'hex')
|
||||
|
||||
const buff = Buffer.from((pc ? '04' : '') + (mode === C1C2C3 ? C1 + C2 + C3 : C1 + C3 + C2), 'hex')
|
||||
return outputEncoding ? buff.toString(outputEncoding) : toArrayBuffer(buff)
|
||||
}
|
||||
|
||||
/**
|
||||
* 设 klen 为密文中 C2 的比特长度
|
||||
* 为了对密文 C= C1 ∥ C2 ∥ C3 进行解密,作为解密者的用户B应实现以下运算步骤:
|
||||
* B1:从 C 中取出比特串 C1,转换为椭圆曲线上的点
|
||||
* B2:计算椭圆曲线点 S=[h]C1,若 S 是无穷远点,则报错并退出;
|
||||
* B3:计算 [dB]C1=(x2,y2),将坐标 x2、y2 的数据类型转换为比特串;
|
||||
* B4:计算 t=KDF(x2 ∥ y2, klen),若 t 为全 0 比特串,则报错并退出;
|
||||
* B5:从 C 中取出比特串 C2,计算 M′ = C2 ⊕ t;
|
||||
* B6:计算 u = Hash(x2 ∥ M′ ∥ y2),从 C 中取出比特串 C3,若u ̸= C3,则报错并退出;
|
||||
* B7:输出明文M′
|
||||
*
|
||||
* @param {string|Buffer|ArrayBuffer} data
|
||||
* @param {string} publicKey
|
||||
*/
|
||||
export function decrypt(data, privateKey, options) {
|
||||
const { mode = C1C3C2, inputEncoding, outputEncoding, pc } = options || {}
|
||||
|
||||
// 密文数据类型校验 `string` | `ArrayBuffer` | `Buffer`
|
||||
if (typeof data === 'string') {
|
||||
data = Buffer.from(data, inputEncoding)
|
||||
} else if (data instanceof ArrayBuffer) {
|
||||
data = Buffer.from(data)
|
||||
}
|
||||
if (!Buffer.isBuffer(data)) {
|
||||
throw new TypeError(
|
||||
`Expected "string" | "Buffer" | "ArrayBuffer" but received "${Object.prototype.toString.call(
|
||||
data
|
||||
)}"`
|
||||
)
|
||||
}
|
||||
data = pc ? data.slice(1) : data
|
||||
|
||||
const unit = 32
|
||||
|
||||
// 从 C 中取出比特串 C1,转换为椭圆曲线上的点
|
||||
const x1 = data.slice(0, unit).toString('hex')
|
||||
const y1 = data.slice(unit, 2 * unit).toString('hex')
|
||||
const point1 = curve.decodePointHex(PC + x1 + y1)
|
||||
|
||||
// TODO: 计算椭圆曲线点 S=[h]C1,若 S 是无穷远点,则报错并退出;
|
||||
|
||||
// [dB]C1 = (x2,y2)
|
||||
const point2 = point1.multiply(new BigInteger(privateKey, 16))
|
||||
const x2 = leftPad(point2.getX().toBigInteger().toString(16), 64)
|
||||
const y2 = leftPad(point2.getY().toBigInteger().toString(16), 64)
|
||||
|
||||
// 根据拼接模式拆分数据 C2, C3
|
||||
let C3 = data.slice(2 * unit, 3 * unit)
|
||||
let C2 = data.slice(3 * unit)
|
||||
|
||||
if (mode === C1C2C3) {
|
||||
C3 = data.slice(data.length - unit)
|
||||
C2 = data.slice(2 * unit, data.length - unit)
|
||||
}
|
||||
|
||||
// t = KDF(x2 ∥ y2, klen),若 t 为全 0 比特串,则返回 A1
|
||||
const t = KDF(Buffer.from(x2 + y2, 'hex'), C2.length)
|
||||
|
||||
// M′ = C2 ⊕ t
|
||||
const M = new BigInteger(C2.toString('hex'), 16)
|
||||
.xor(new BigInteger(t.toString('hex'), 16))
|
||||
.toString(16)
|
||||
|
||||
// 计算 u = Hash(x2 ∥ M′ ∥ y2)
|
||||
const u = digest(x2 + M + y2, 'hex', 'hex')
|
||||
|
||||
// 合法性校验
|
||||
const verified = u === C3.toString('hex')
|
||||
|
||||
const buff = verified ? Buffer.from(M, 'hex') : Buffer.alloc(0)
|
||||
return outputEncoding ? buff.toString(outputEncoding) : toArrayBuffer(buff)
|
||||
}
|
||||
147
nx/utils/gm-crypto/lib/sm3.js
Normal file
147
nx/utils/gm-crypto/lib/sm3.js
Normal file
@@ -0,0 +1,147 @@
|
||||
import toArrayBuffer from 'to-arraybuffer'
|
||||
import { Buffer } from 'buffer' // 兼容浏览器环境
|
||||
import { leftShift } from './utils'
|
||||
|
||||
// 官方文档以比特作为操作单位,此处以字节作为操作单位。
|
||||
const padding = (buf) => {
|
||||
// 首字节 0b10000000 填充
|
||||
const p1 = Buffer.alloc(1, 0x80)
|
||||
|
||||
// 取值 "0" 的 k 比特填充
|
||||
let k = buf.length % 64 // 64 * 8 === 512
|
||||
k = k >= 56 ? 64 - (k % 56) - 1 : 56 - k - 1 // 56 * 8 === 448
|
||||
const p2 = Buffer.alloc(k, 0)
|
||||
|
||||
// 64 比特(8 字节)的消息长度填充
|
||||
const p3 = Buffer.alloc(8)
|
||||
const size = buf.length * 8 // 不超过 2^53 -1
|
||||
p3.writeUInt32BE(Math.floor(size / 2 ** 32), 0) // 高 32 位
|
||||
p3.writeUInt32BE(size % 2 ** 32, 4) // 低 32 位
|
||||
|
||||
return Buffer.concat([buf, p1, p2, p3], buf.length + 1 + k + 8)
|
||||
}
|
||||
|
||||
const T = (j) => (j < 16 ? 0x79cc4519 : 0x7a879d8a)
|
||||
const FF = (X, Y, Z, j) => (j < 16 ? X ^ Y ^ Z : (X & Y) | (X & Z) | (Y & Z))
|
||||
const GG = (X, Y, Z, j) => (j < 16 ? X ^ Y ^ Z : (X & Y) | (~X & Z))
|
||||
const P0 = (X) => X ^ leftShift(X, 9) ^ leftShift(X, 17)
|
||||
const P1 = (X) => X ^ leftShift(X, 15) ^ leftShift(X, 23)
|
||||
|
||||
// 消息扩展(512-bits): 16 个字 => 132 个字
|
||||
const extendFn = (Bi) => {
|
||||
const W = new Array(132)
|
||||
|
||||
// 将消息分组 B(i) 划分为 16 个字 W0, W1, · · · , W15
|
||||
Bi.forEach((v, i) => {
|
||||
W[i] = v
|
||||
})
|
||||
|
||||
/**
|
||||
FOR j=16 TO 67
|
||||
Wj ← P1(Wj−16 ⊕ Wj−9 ⊕ (Wj−3 ≪ 15)) ⊕ (Wj−13 ≪ 7) ⊕ Wj−6
|
||||
ENDFOR
|
||||
*/
|
||||
for (let j = 16; j < 68; j++) {
|
||||
W[j] =
|
||||
P1(W[j - 16] ^ W[j - 9] ^ leftShift(W[j - 3], 15)) ^
|
||||
leftShift(W[j - 13], 7) ^
|
||||
W[j - 6]
|
||||
}
|
||||
|
||||
/**
|
||||
FOR j=0 TO 63
|
||||
W′j = Wj ⊕ Wj+4
|
||||
ENDFOR
|
||||
*/
|
||||
for (let j = 0; j < 64; j++) {
|
||||
W[j + 68] = W[j] ^ W[j + 4]
|
||||
}
|
||||
|
||||
return W
|
||||
}
|
||||
|
||||
// 压缩函数
|
||||
// - Vi => 8 个字(256-bits)
|
||||
// - Bi => 16 个字(512-bits)
|
||||
const CF = (Vi, Bi, i) => {
|
||||
const W = extendFn(Bi) // 消息扩展, 返回 132 个字
|
||||
|
||||
let [A, B, C, D, E, F, G, H] = Vi
|
||||
let SS1, SS2, TT1, TT2
|
||||
|
||||
for (let j = 0; j < 64; j++) {
|
||||
SS1 = leftShift(leftShift(A, 12) + E + leftShift(T(j), j), 7)
|
||||
SS2 = SS1 ^ leftShift(A, 12)
|
||||
TT1 = FF(A, B, C, j) + D + SS2 + W[j + 68]
|
||||
TT2 = GG(E, F, G, j) + H + SS1 + W[j]
|
||||
D = C
|
||||
C = leftShift(B, 9)
|
||||
B = A
|
||||
A = TT1
|
||||
H = G
|
||||
G = leftShift(F, 19)
|
||||
F = E
|
||||
E = P0(TT2)
|
||||
}
|
||||
|
||||
return [
|
||||
A ^ Vi[0],
|
||||
B ^ Vi[1],
|
||||
C ^ Vi[2],
|
||||
D ^ Vi[3],
|
||||
E ^ Vi[4],
|
||||
F ^ Vi[5],
|
||||
G ^ Vi[6],
|
||||
H ^ Vi[7]
|
||||
]
|
||||
}
|
||||
|
||||
export const digest = (data, inputEncoding, outputEncoding) => {
|
||||
// 输入参数校验 `string` | `ArrayBuffer` | `Buffer`
|
||||
if (typeof data === 'string') {
|
||||
data = Buffer.from(data, inputEncoding || 'utf8')
|
||||
} else if (data instanceof ArrayBuffer) {
|
||||
data = Buffer.from(data)
|
||||
}
|
||||
if (!Buffer.isBuffer(data)) {
|
||||
throw new TypeError(
|
||||
`Expected "string" | "Buffer" | "ArrayBuffer" but received "${Object.prototype.toString.call(
|
||||
data
|
||||
)}"`
|
||||
)
|
||||
}
|
||||
|
||||
data = padding(data) // 数据填充
|
||||
const n = data.length / 64 // 512 比特对应 64 字节
|
||||
|
||||
const B = new Array(n)
|
||||
for (let i = 0; i < n; i++) {
|
||||
B[i] = new Array(16)
|
||||
for (let j = 0; j < 16; j++) {
|
||||
const offset = i * 64 + j * 4
|
||||
B[i][j] = data.readUInt32BE(offset)
|
||||
}
|
||||
}
|
||||
|
||||
const V = new Array(n)
|
||||
V[0] = [
|
||||
0x7380166f,
|
||||
0x4914b2b9,
|
||||
0x172442d7,
|
||||
0xda8a0600,
|
||||
0xa96f30bc,
|
||||
0x163138aa,
|
||||
0xe38dee4d,
|
||||
0xb0fb0e4e
|
||||
]
|
||||
|
||||
// 迭代压缩
|
||||
for (let i = 0; i < n; i++) {
|
||||
V[i + 1] = CF(V[i], B[i], i)
|
||||
}
|
||||
|
||||
const hash = Buffer.alloc(32)
|
||||
V[n].forEach((i32, j) => hash.writeInt32BE(i32, j * 4))
|
||||
|
||||
return outputEncoding ? hash.toString(outputEncoding) : toArrayBuffer(hash)
|
||||
}
|
||||
604
nx/utils/gm-crypto/lib/sm4.js
Normal file
604
nx/utils/gm-crypto/lib/sm4.js
Normal file
@@ -0,0 +1,604 @@
|
||||
import toArrayBuffer from 'to-arraybuffer'
|
||||
import { Buffer } from 'buffer' // 兼容浏览器环境
|
||||
import { leftShift } from './utils'
|
||||
|
||||
// 两种分组模式
|
||||
const ECB = 1
|
||||
const CBC = 2
|
||||
|
||||
// SM4 相关常量
|
||||
export const constants = { ECB, CBC }
|
||||
|
||||
// S 盒(非线性变换)
|
||||
const SBOX_TABLE = [
|
||||
[
|
||||
0xd6,
|
||||
0x90,
|
||||
0xe9,
|
||||
0xfe,
|
||||
0xcc,
|
||||
0xe1,
|
||||
0x3d,
|
||||
0xb7,
|
||||
0x16,
|
||||
0xb6,
|
||||
0x14,
|
||||
0xc2,
|
||||
0x28,
|
||||
0xfb,
|
||||
0x2c,
|
||||
0x05
|
||||
],
|
||||
[
|
||||
0x2b,
|
||||
0x67,
|
||||
0x9a,
|
||||
0x76,
|
||||
0x2a,
|
||||
0xbe,
|
||||
0x04,
|
||||
0xc3,
|
||||
0xaa,
|
||||
0x44,
|
||||
0x13,
|
||||
0x26,
|
||||
0x49,
|
||||
0x86,
|
||||
0x06,
|
||||
0x99
|
||||
],
|
||||
[
|
||||
0x9c,
|
||||
0x42,
|
||||
0x50,
|
||||
0xf4,
|
||||
0x91,
|
||||
0xef,
|
||||
0x98,
|
||||
0x7a,
|
||||
0x33,
|
||||
0x54,
|
||||
0x0b,
|
||||
0x43,
|
||||
0xed,
|
||||
0xcf,
|
||||
0xac,
|
||||
0x62
|
||||
],
|
||||
[
|
||||
0xe4,
|
||||
0xb3,
|
||||
0x1c,
|
||||
0xa9,
|
||||
0xc9,
|
||||
0x08,
|
||||
0xe8,
|
||||
0x95,
|
||||
0x80,
|
||||
0xdf,
|
||||
0x94,
|
||||
0xfa,
|
||||
0x75,
|
||||
0x8f,
|
||||
0x3f,
|
||||
0xa6
|
||||
],
|
||||
[
|
||||
0x47,
|
||||
0x07,
|
||||
0xa7,
|
||||
0xfc,
|
||||
0xf3,
|
||||
0x73,
|
||||
0x17,
|
||||
0xba,
|
||||
0x83,
|
||||
0x59,
|
||||
0x3c,
|
||||
0x19,
|
||||
0xe6,
|
||||
0x85,
|
||||
0x4f,
|
||||
0xa8
|
||||
],
|
||||
[
|
||||
0x68,
|
||||
0x6b,
|
||||
0x81,
|
||||
0xb2,
|
||||
0x71,
|
||||
0x64,
|
||||
0xda,
|
||||
0x8b,
|
||||
0xf8,
|
||||
0xeb,
|
||||
0x0f,
|
||||
0x4b,
|
||||
0x70,
|
||||
0x56,
|
||||
0x9d,
|
||||
0x35
|
||||
],
|
||||
[
|
||||
0x1e,
|
||||
0x24,
|
||||
0x0e,
|
||||
0x5e,
|
||||
0x63,
|
||||
0x58,
|
||||
0xd1,
|
||||
0xa2,
|
||||
0x25,
|
||||
0x22,
|
||||
0x7c,
|
||||
0x3b,
|
||||
0x01,
|
||||
0x21,
|
||||
0x78,
|
||||
0x87
|
||||
],
|
||||
[
|
||||
0xd4,
|
||||
0x00,
|
||||
0x46,
|
||||
0x57,
|
||||
0x9f,
|
||||
0xd3,
|
||||
0x27,
|
||||
0x52,
|
||||
0x4c,
|
||||
0x36,
|
||||
0x02,
|
||||
0xe7,
|
||||
0xa0,
|
||||
0xc4,
|
||||
0xc8,
|
||||
0x9e
|
||||
],
|
||||
[
|
||||
0xea,
|
||||
0xbf,
|
||||
0x8a,
|
||||
0xd2,
|
||||
0x40,
|
||||
0xc7,
|
||||
0x38,
|
||||
0xb5,
|
||||
0xa3,
|
||||
0xf7,
|
||||
0xf2,
|
||||
0xce,
|
||||
0xf9,
|
||||
0x61,
|
||||
0x15,
|
||||
0xa1
|
||||
],
|
||||
[
|
||||
0xe0,
|
||||
0xae,
|
||||
0x5d,
|
||||
0xa4,
|
||||
0x9b,
|
||||
0x34,
|
||||
0x1a,
|
||||
0x55,
|
||||
0xad,
|
||||
0x93,
|
||||
0x32,
|
||||
0x30,
|
||||
0xf5,
|
||||
0x8c,
|
||||
0xb1,
|
||||
0xe3
|
||||
],
|
||||
[
|
||||
0x1d,
|
||||
0xf6,
|
||||
0xe2,
|
||||
0x2e,
|
||||
0x82,
|
||||
0x66,
|
||||
0xca,
|
||||
0x60,
|
||||
0xc0,
|
||||
0x29,
|
||||
0x23,
|
||||
0xab,
|
||||
0x0d,
|
||||
0x53,
|
||||
0x4e,
|
||||
0x6f
|
||||
],
|
||||
[
|
||||
0xd5,
|
||||
0xdb,
|
||||
0x37,
|
||||
0x45,
|
||||
0xde,
|
||||
0xfd,
|
||||
0x8e,
|
||||
0x2f,
|
||||
0x03,
|
||||
0xff,
|
||||
0x6a,
|
||||
0x72,
|
||||
0x6d,
|
||||
0x6c,
|
||||
0x5b,
|
||||
0x51
|
||||
],
|
||||
[
|
||||
0x8d,
|
||||
0x1b,
|
||||
0xaf,
|
||||
0x92,
|
||||
0xbb,
|
||||
0xdd,
|
||||
0xbc,
|
||||
0x7f,
|
||||
0x11,
|
||||
0xd9,
|
||||
0x5c,
|
||||
0x41,
|
||||
0x1f,
|
||||
0x10,
|
||||
0x5a,
|
||||
0xd8
|
||||
],
|
||||
[
|
||||
0x0a,
|
||||
0xc1,
|
||||
0x31,
|
||||
0x88,
|
||||
0xa5,
|
||||
0xcd,
|
||||
0x7b,
|
||||
0xbd,
|
||||
0x2d,
|
||||
0x74,
|
||||
0xd0,
|
||||
0x12,
|
||||
0xb8,
|
||||
0xe5,
|
||||
0xb4,
|
||||
0xb0
|
||||
],
|
||||
[
|
||||
0x89,
|
||||
0x69,
|
||||
0x97,
|
||||
0x4a,
|
||||
0x0c,
|
||||
0x96,
|
||||
0x77,
|
||||
0x7e,
|
||||
0x65,
|
||||
0xb9,
|
||||
0xf1,
|
||||
0x09,
|
||||
0xc5,
|
||||
0x6e,
|
||||
0xc6,
|
||||
0x84
|
||||
],
|
||||
[
|
||||
0x18,
|
||||
0xf0,
|
||||
0x7d,
|
||||
0xec,
|
||||
0x3a,
|
||||
0xdc,
|
||||
0x4d,
|
||||
0x20,
|
||||
0x79,
|
||||
0xee,
|
||||
0x5f,
|
||||
0x3e,
|
||||
0xd7,
|
||||
0xcb,
|
||||
0x39,
|
||||
0x48
|
||||
]
|
||||
]
|
||||
|
||||
/**
|
||||
* 密钥扩展算法
|
||||
* - FK: 系统参数
|
||||
* - CK: 固定参数
|
||||
*/
|
||||
const FK = [0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc]
|
||||
const CK = [
|
||||
0x00070e15,
|
||||
0x1c232a31,
|
||||
0x383f464d,
|
||||
0x545b6269,
|
||||
0x70777e85,
|
||||
0x8c939aa1,
|
||||
0xa8afb6bd,
|
||||
0xc4cbd2d9,
|
||||
0xe0e7eef5,
|
||||
0xfc030a11,
|
||||
0x181f262d,
|
||||
0x343b4249,
|
||||
0x50575e65,
|
||||
0x6c737a81,
|
||||
0x888f969d,
|
||||
0xa4abb2b9,
|
||||
0xc0c7ced5,
|
||||
0xdce3eaf1,
|
||||
0xf8ff060d,
|
||||
0x141b2229,
|
||||
0x30373e45,
|
||||
0x4c535a61,
|
||||
0x686f767d,
|
||||
0x848b9299,
|
||||
0xa0a7aeb5,
|
||||
0xbcc3cad1,
|
||||
0xd8dfe6ed,
|
||||
0xf4fb0209,
|
||||
0x10171e25,
|
||||
0x2c333a41,
|
||||
0x484f565d,
|
||||
0x646b7279
|
||||
]
|
||||
|
||||
// 分组大小
|
||||
const BLOCK_SIZE = 16 // 16 bytes
|
||||
// 十六进制表示的加密密钥和初始化向量 iv
|
||||
const REG_EXP_KEY = /^[0-9a-f]{32}$/i
|
||||
|
||||
// 非线性变换 τ(.)
|
||||
const Tau = (a) => {
|
||||
const b1 = SBOX_TABLE[(a & 0xf0000000) >>> 28][(a & 0x0f000000) >>> 24]
|
||||
const b2 = SBOX_TABLE[(a & 0x00f00000) >>> 20][(a & 0x000f0000) >>> 16]
|
||||
const b3 = SBOX_TABLE[(a & 0x0000f000) >>> 12][(a & 0x00000f00) >>> 8]
|
||||
const b4 = SBOX_TABLE[(a & 0x000000f0) >>> 4][(a & 0x0000000f) >>> 0]
|
||||
return (b1 << 24) | (b2 << 16) | (b3 << 8) | (b4 << 0)
|
||||
}
|
||||
|
||||
// 线性变换 L(B) = B xor (B <<< 2) xor (B <<< 10) xor (B <<< 18) xor (B <<< 24)
|
||||
const L = (B) =>
|
||||
B ^ leftShift(B, 2) ^ leftShift(B, 10) ^ leftShift(B, 18) ^ leftShift(B, 24)
|
||||
|
||||
// 合成置换 T(A) = L(τ(A))
|
||||
const T = (A) => L(Tau(A))
|
||||
|
||||
// 线性变换 L'(B) = B xor (B <<< 13) xor (B <<< 23)
|
||||
const Li = (B) => B ^ leftShift(B, 13) ^ leftShift(B, 23)
|
||||
|
||||
// 合成置换 T'(A) = L'(τ(A))
|
||||
const Ti = (A) => Li(Tau(A))
|
||||
|
||||
// 密钥扩展算法
|
||||
const extendKeys = (MK) => {
|
||||
const K = new Array(36)
|
||||
K[0] = MK[0] ^ FK[0]
|
||||
K[1] = MK[1] ^ FK[1]
|
||||
K[2] = MK[2] ^ FK[2]
|
||||
K[3] = MK[3] ^ FK[3]
|
||||
|
||||
const rk = new Array(32)
|
||||
for (let i = 0; i < 32; i++) {
|
||||
K[i + 4] = K[i] ^ Ti(K[i + 1] ^ K[i + 2] ^ K[i + 3] ^ CK[i])
|
||||
rk[i] = K[i + 4]
|
||||
}
|
||||
|
||||
return rk
|
||||
}
|
||||
|
||||
// 分组加密
|
||||
const encryptBlock = (X, MK) => {
|
||||
const rk = extendKeys(MK)
|
||||
|
||||
for (let i = 0; i < 32; i++) {
|
||||
X[i + 4] = X[i] ^ T(X[i + 1] ^ X[i + 2] ^ X[i + 3] ^ rk[i])
|
||||
}
|
||||
|
||||
return [X[35], X[34], X[33], X[32]]
|
||||
}
|
||||
|
||||
// 分组解密
|
||||
const decryptBlock = (X, MK) => {
|
||||
const rk = extendKeys(MK).reverse()
|
||||
|
||||
for (let i = 0; i < 32; i++) {
|
||||
X[i + 4] = X[i] ^ T(X[i + 1] ^ X[i + 2] ^ X[i + 3] ^ rk[i])
|
||||
}
|
||||
|
||||
return [X[35], X[34], X[33], X[32]]
|
||||
}
|
||||
|
||||
// 分组填充 https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS#5_and_PKCS#7
|
||||
const pkcs7Padding = (data) => {
|
||||
const paddingSize = BLOCK_SIZE - (data.length % BLOCK_SIZE)
|
||||
const paddingBuff = Buffer.alloc(paddingSize, paddingSize)
|
||||
return Buffer.concat([data, paddingBuff], data.length + paddingSize)
|
||||
}
|
||||
|
||||
// Block Buffer => Int32 Array
|
||||
const toInt32Array = (block) => [
|
||||
block.readInt32BE(0),
|
||||
block.readInt32BE(4),
|
||||
block.readInt32BE(8),
|
||||
block.readInt32BE(12)
|
||||
]
|
||||
|
||||
// Int32 Array => Block Buffer
|
||||
const toCipcherBlock = (array) => {
|
||||
const block = Buffer.alloc(16)
|
||||
for (let i = 0; i < 4; i++) {
|
||||
block.writeInt32BE(array[i], i * 4)
|
||||
}
|
||||
return block
|
||||
}
|
||||
|
||||
const _encrypt = (data, key, iv, outputEncoding) => {
|
||||
// 初始化向量转换
|
||||
iv && (iv = toInt32Array(iv))
|
||||
// 密钥转换
|
||||
key = toInt32Array(key)
|
||||
// 分组填充
|
||||
data = pkcs7Padding(data)
|
||||
|
||||
// 分组加密结果
|
||||
const blocks = []
|
||||
// 分组数(每组 16 字节)
|
||||
const num = data.length / BLOCK_SIZE
|
||||
|
||||
for (let i = 0; i < num; i++) {
|
||||
if (iv) {
|
||||
const offset = i * BLOCK_SIZE
|
||||
const plainBlock = [
|
||||
iv[0] ^ data.readInt32BE(offset),
|
||||
iv[1] ^ data.readInt32BE(offset + 4),
|
||||
iv[2] ^ data.readInt32BE(offset + 8),
|
||||
iv[3] ^ data.readInt32BE(offset + 12)
|
||||
]
|
||||
const cipherBlock = encryptBlock(plainBlock, key)
|
||||
blocks.push(toCipcherBlock(cipherBlock))
|
||||
iv = cipherBlock.slice(0) // 将本次密文作为下一次加密的 iv
|
||||
} else {
|
||||
const offset = i * BLOCK_SIZE
|
||||
const plainBlock = [
|
||||
data.readInt32BE(offset),
|
||||
data.readInt32BE(offset + 4),
|
||||
data.readInt32BE(offset + 8),
|
||||
data.readInt32BE(offset + 12)
|
||||
]
|
||||
const cipherBlock = encryptBlock(plainBlock, key)
|
||||
blocks.push(toCipcherBlock(cipherBlock))
|
||||
}
|
||||
}
|
||||
|
||||
const buff = Buffer.concat(blocks, data.length)
|
||||
return outputEncoding ? buff.toString(outputEncoding) : toArrayBuffer(buff)
|
||||
}
|
||||
|
||||
const _decrypt = (data, key, iv, outputEncoding) => {
|
||||
// 初始化向量转换
|
||||
iv && (iv = toInt32Array(iv))
|
||||
// 密钥转换
|
||||
key = toInt32Array(key)
|
||||
|
||||
// 分组解密结果
|
||||
const blocks = []
|
||||
// 按每组 16 字节分组后得到的总分组数
|
||||
const num = data.length / BLOCK_SIZE
|
||||
|
||||
if (iv) {
|
||||
for (let i = num - 1; i >= 0; i--) {
|
||||
const offset = i * BLOCK_SIZE
|
||||
|
||||
let vector
|
||||
if (i > 0) {
|
||||
vector = [
|
||||
data.readInt32BE(offset - BLOCK_SIZE),
|
||||
data.readInt32BE(offset - BLOCK_SIZE + 4),
|
||||
data.readInt32BE(offset - BLOCK_SIZE + 8),
|
||||
data.readInt32BE(offset - BLOCK_SIZE + 12)
|
||||
]
|
||||
} else {
|
||||
vector = iv
|
||||
}
|
||||
|
||||
const cipherBlock = [
|
||||
data.readInt32BE(offset),
|
||||
data.readInt32BE(offset + 4),
|
||||
data.readInt32BE(offset + 8),
|
||||
data.readInt32BE(offset + 12)
|
||||
]
|
||||
const [b0, b1, b2, b3] = decryptBlock(cipherBlock, key)
|
||||
const plainBlock = [
|
||||
b0 ^ vector[0],
|
||||
b1 ^ vector[1],
|
||||
b2 ^ vector[2],
|
||||
b3 ^ vector[3]
|
||||
]
|
||||
|
||||
blocks.unshift(toCipcherBlock(plainBlock))
|
||||
}
|
||||
} else {
|
||||
for (let i = 0; i < num; i++) {
|
||||
const offset = i * BLOCK_SIZE
|
||||
const cipherBlock = [
|
||||
data.readInt32BE(offset),
|
||||
data.readInt32BE(offset + 4),
|
||||
data.readInt32BE(offset + 8),
|
||||
data.readInt32BE(offset + 12)
|
||||
]
|
||||
const plainBlock = decryptBlock(cipherBlock, key)
|
||||
blocks.push(toCipcherBlock(plainBlock))
|
||||
}
|
||||
}
|
||||
|
||||
// 移除分组填充
|
||||
const buff = Buffer.concat(
|
||||
blocks,
|
||||
data.length - blocks[blocks.length - 1][BLOCK_SIZE - 1]
|
||||
)
|
||||
return outputEncoding ? buff.toString(outputEncoding) : toArrayBuffer(buff)
|
||||
}
|
||||
|
||||
export const encrypt = (data, key, options) => {
|
||||
let { mode, iv, inputEncoding, outputEncoding } = options || {}
|
||||
|
||||
// 输入参数校验 `string` | `ArrayBuffer` | `Buffer`
|
||||
if (typeof data === 'string') {
|
||||
data = Buffer.from(data, inputEncoding || 'utf8')
|
||||
} else if (data instanceof ArrayBuffer) {
|
||||
data = Buffer.from(data)
|
||||
}
|
||||
if (!Buffer.isBuffer(data)) {
|
||||
throw new TypeError(
|
||||
`Expected "string" | "Buffer" | "ArrayBuffer" but received "${Object.prototype.toString.call(
|
||||
data
|
||||
)}"`
|
||||
)
|
||||
}
|
||||
|
||||
// 十六进制表示的密钥
|
||||
if (!REG_EXP_KEY.test(key)) {
|
||||
throw new TypeError('Invalid value of cipher `key`')
|
||||
}
|
||||
key = Buffer.from(key, 'hex')
|
||||
|
||||
// CBC 分组必须制定 iv
|
||||
if (mode === CBC && !REG_EXP_KEY.test(iv)) {
|
||||
throw new TypeError('Invalid value of `iv` option')
|
||||
}
|
||||
iv = mode === CBC ? Buffer.from(iv, 'hex') : null
|
||||
|
||||
return _encrypt(data, key, iv, outputEncoding)
|
||||
}
|
||||
|
||||
export const decrypt = (data, key, options) => {
|
||||
let { mode, iv, inputEncoding, outputEncoding } = options || {}
|
||||
|
||||
// 输入参数校验 `string` | `ArrayBuffer` | `Buffer`
|
||||
if (typeof data === 'string') {
|
||||
data = Buffer.from(data, inputEncoding)
|
||||
} else if (data instanceof ArrayBuffer) {
|
||||
data = Buffer.from(data)
|
||||
}
|
||||
if (!Buffer.isBuffer(data)) {
|
||||
throw new TypeError(
|
||||
`Expected "string" | "Buffer" | "ArrayBuffer" but received "${Object.prototype.toString.call(
|
||||
data
|
||||
)}"`
|
||||
)
|
||||
}
|
||||
|
||||
// 十六进制表示的密钥
|
||||
if (!REG_EXP_KEY.test(key)) {
|
||||
throw new TypeError('Invalid value of cipher `key`')
|
||||
}
|
||||
key = Buffer.from(key, 'hex')
|
||||
|
||||
// CBC 分组必须制定 iv
|
||||
if (mode === CBC && !REG_EXP_KEY.test(iv)) {
|
||||
throw new TypeError('Invalid value of `iv` option')
|
||||
}
|
||||
iv = mode === CBC ? Buffer.from(iv, 'hex') : null
|
||||
|
||||
return _decrypt(data, key, iv, outputEncoding)
|
||||
}
|
||||
11
nx/utils/gm-crypto/lib/utils.js
Normal file
11
nx/utils/gm-crypto/lib/utils.js
Normal file
@@ -0,0 +1,11 @@
|
||||
// 32 位整数无符号循环左移
|
||||
export const leftShift = (a, n) => {
|
||||
n = n % 32
|
||||
return (a << n) | (a >>> (32 - n))
|
||||
}
|
||||
|
||||
// 补全 16 进制字符串
|
||||
export const leftPad = (str, num) => {
|
||||
const padding = num - str.length
|
||||
return (padding > 0 ? '0'.repeat(padding) : '') + str
|
||||
}
|
||||
Reference in New Issue
Block a user