You need to enable JavaScript to run this app. 如何使用Node.js crypto模块生成34到50字符长度的短公钥
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node.js crypto模块生成34到50字符长度的短公钥

解决方案

首先明确一个前提:你当前用的2048位RSA算法的公钥本身原始数据长度就超过200字节,无论用什么编码格式都不可能压缩到34~50字符的区间,必须更换更轻量化的非对称加密算法才能满足需求。


推荐方案:使用Ed25519椭圆曲线算法

Ed25519是目前应用最广的轻量化签名算法,公钥原始长度仅32字节,使用Base58编码后长度约为4344字符,刚好落在你要求的3450字符区间内,安全性和2048位RSA相当,性能还远高于RSA。

Node.js 实现代码

const crypto = require('crypto')
const fs = require('fs')
const bs58 = require('bs58') // 需先执行npm install bs58安装

function generateEd25519KeyPair() {
  if (fs.existsSync('privateKey.pem') || fs.existsSync('publicKey.pem')) {
    console.log("已存在密钥文件,如需生成新密钥请先移除原有privateKey.pem和publicKey.pem")
    return
  }
  // 生成Ed25519密钥对
  const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519', {
    publicKeyEncoding: { type: 'raw', format: 'der' },
    privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
  })
  // 公钥转Base58编码,得到短公钥
  const shortPublicKey = bs58.encode(publicKey)
  console.log('短公钥(Base58编码):', shortPublicKey)
  console.log('短公钥长度:', shortPublicKey.length) // 输出通常为43或44,符合要求
  // 保存私钥和短公钥
  fs.writeFileSync('privateKey.pem', privateKey)
  fs.writeFileSync('shortPublicKey.txt', shortPublicKey)
  console.log('密钥文件已生成保存到当前目录')
}

generateEd25519KeyPair()

必须保留RSA算法的替代方案

如果业务要求必须使用RSA,那只能对公钥做哈希摘要取固定长度片段作为公钥标识:

const crypto = require('crypto')
// publicKey为你之前生成的RSA公钥PEM内容
const publicKeyFingerprint = crypto.createHash('sha256').update(publicKey).digest('hex').slice(0, 40)
console.log(publicKeyFingerprint) // 长度固定为40字符,符合要求

注意:这个指纹不能直接当作公钥做加密/验签操作,只能作为公钥的唯一标识使用,业务中需要存储指纹和原公钥的映射关系。


内容的提问来源于stack exchange,提问作者kevin richard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 11:36:03