国密 GM/T 系列(sm2,sm3,sm4) 纯 JavaScript 实现

8,197 阅读1分钟
2014 年国务院办公厅就颁发了《国务院办公厅转发密码局等部门关于金融领域密码应用指导意见》,指出在我国涉及到金融领域信息安全的产品和系统要自主可控,在金融领域使用国产加密标准是机构走向合规化的重要一步。常用的国密算法包括:SM2、SM3、SM4等。

特性

  • 兼容 Node.js & Browsers 环境
  • 支持多种数据类型 String & ArrayBuffer & Buffer
  • 支持多种编码  hex & utf8 & base64

安装

npm install gm-crypto

yarn add gm-crypto

快速开始

 浏览器端写法调整为 import { SM2, SM3, SM4 } from 'gm-crypto'

SM2

const { SM2 } = require('gm-crypto')

const { publicKey, privateKey } = SM2.generateKeyPair()
const originalData = 'SM2 椭圆曲线公钥密码算法'

const encryptedData = SM2.encrypt(originalData, publicKey, {
  inputEncoding: 'utf8',
  outputEncoding: 'base64'
})

const decryptedData = SM2.decrypt(encryptedData, privateKey, {
  inputEncoding: 'base64',
  outputEncoding: 'utf8'
})

SM3

const { SM3 } = require('gm-crypto')

console.log(SM3.digest('abc'))
console.log(SM3.digest('YWJj', 'base64'))
console.log(SM3.digest('616263', 'hex', 'base64'))

SM4

const { SM4 } = require('gm-crypto')

const key = '0123456789abcdeffedcba9876543210' // Any string of 32 hexadecimal digits
const originalData = 'SM4 国标对称加密'

/**
 * Block cipher modes:
 * - ECB: electronic codebook
 * - CBC: cipher block chaining
 */

let encryptedData, decryptedData

// ECB
encryptedData = SM4.encrypt(originalData, key, {
  inputEncoding: 'utf8',
  outputEncoding: 'base64'
})
decryptedData = SM4.decrypt(encryptedData, key, {
  inputEncoding: 'base64',
  outputEncoding: 'utf8'
})

// CBC
const iv = '0123456789abcdeffedcba9876543210' // Initialization vector(any string of 32 hexadecimal digits)
encryptedData = SM4.encrypt(originalData, key, {
  iv,
  mode: SM2.constants.CBC,
  inputEncoding: 'utf8',
  outputEncoding: 'hex'
})
decryptedData = SM4.decrypt(encryptedData, key, {
  iv,
  mode: SM2.constants.CBC,
  inputEncoding: 'hex',
  outputEncoding: 'utf8'
})

详情参看 github.com/byte-fe/gm-…