在Node.js/TypeScript中解析CRL遇'slice'未定义错误求助
TypeScript解析PEM格式CRL时出现"Cannot read properties of undefined (reading 'slice')"错误的解决方向
我需要解析PEM格式的CRL(证书吊销列表)以查看哪些证书已被吊销。此前用JavaScript实现正常,但切换到TypeScript后出现问题。
当前代码
import { fromBER } from 'asn1js'; import { CertificateRevocationList } from 'pkijs'; import fs from 'fs'; fs.readFile('./pathToMyCrlFile.crl', (err, crlData) => { if (err) { throw err; } const buffer = new Uint8Array(crlData).buffer; const asn1crl = fromBER(buffer); const crl = new CertificateRevocationList({ schema: asn1crl.result }) for (const { userCertificate } of crl.revokedCertificates) { // do something } })
报错信息
Cannot read properties of undefined (reading 'slice'). Stacktrace: TypeError: Cannot read properties of undefined (reading 'slice') at RelativeDistinguishedNames.fromSchema (<project_path>/node_modules/pkijs/build/index.js:408:72)
已确认PEM文件有效,以下是问题的解决方向:
- 修正PEM格式处理逻辑:PEM是Base64编码的文本文件,直接按二进制读取会导致解析错误。需先读取为字符串,提取首尾标记间的Base64内容,再解码为二进制数据。
- 增加解析结果校验:在创建
CertificateRevocationList前,检查asn1crl.result是否存在、asn1crl.offset是否不为-1,确保BER解析成功。 - 处理可选字段的类型安全:TypeScript对可选字段校验更严格,
crl.revokedCertificates可能为undefined,遍历前需先判断其存在性。 - 核对pkijs版本:JavaScript环境正常但TypeScript出错,可能是版本兼容性问题,尝试升级pkijs到最新稳定版,或保持与原JS环境一致的版本。
修正后的示例代码
import { fromBER } from 'asn1js'; import { CertificateRevocationList } from 'pkijs'; import fs from 'fs'; fs.readFile('./pathToMyCrlFile.crl', 'utf8', (err, crlText) => { if (err) { throw err; } // 提取PEM中的Base64内容 const pemMatch = crlText.match(/-----BEGIN X509 CRL-----\n([\s\S]*?)\n-----END X509 CRL-----/); if (!pemMatch) { throw new Error('无效的PEM格式CRL文件'); } const crlBase64 = pemMatch[1]; const crlBuffer = Buffer.from(crlBase64, 'base64'); const uint8Buffer = new Uint8Array(crlBuffer).buffer; const asn1crl = fromBER(uint8Buffer); if (asn1crl.offset === -1 || !asn1crl.result) { throw new Error('BER格式解析失败'); } const crl = new CertificateRevocationList({ schema: asn1crl.result }); if (crl.revokedCertificates) { for (const { userCertificate } of crl.revokedCertificates) { // 执行你的处理逻辑 console.log('已吊销证书序列号:', userCertificate.valueBlock.valueHex.toString('hex')); } } });
内容的提问来源于stack exchange,提问作者user7849416
相关产品推荐
相关产品推荐

