This commit is contained in:
houjunxiang
2025-10-09 18:19:55 +08:00
parent f2ffc65094
commit 386f1e7466
1553 changed files with 284685 additions and 32820 deletions

View File

@@ -0,0 +1,3 @@
export const C1C2C3 = 0
export const C1C3C2 = 1
export const PC = '04' // 未压缩

View 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

View 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
)
// ab: 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,n2]
* b) G 为基点,计算点 P = (xP,yP) = [d]G
* c) 密钥对是 (d,P),其中 d 为私钥P 为公钥
*/
export const generateKeyPair = () => {
// a) 用随机数发生器产生整数 d ∈ [1,n2]
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 }
}
/**
* 设需要发送的消息为比特串 Mklen 为 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)
}