@peculiar/asn1-schema是否默认将TypeScript对象包装为ASN.1 SEQUENCE?能否仅输出INTEGER?
解决方法
可以实现,问题出在你当前的Element类未指定ASN.1类型,@peculiar/asn1-schema默认会将类序列化为ASN.1 SEQUENCE,把类的属性作为序列成员。要输出单个INTEGER,有两种常用方案:
方案一:给类添加ASN.1类型注解
通过@AsnType和@AsnProp装饰器,明确指定类对应ASN.1的INTEGER类型,而非默认的SEQUENCE。修改后的代码如下:
import { AsnSerializer, AsnType, AsnTypes, AsnProp } from '@peculiar/asn1-schema'; import BigInteger from 'big-integer'; @AsnType({ type: AsnTypes.Integer }) export class Element { @AsnProp({ type: AsnTypes.Integer }) public value: BigInteger; constructor(value: BigInteger) { this.value = value; } public ToASN1(): ArrayBuffer { try { return AsnSerializer.serialize(this); } catch (error) { // 这里添加你的错误处理逻辑 } } }
方案二:直接序列化单个INTEGER值
不需要用类包装,直接将BigInteger转换后的字节数组序列化为ASN.1 INTEGER,跳过类的默认SEQUENCE序列化逻辑:
import { AsnSerializer, AsnTypes } from '@peculiar/asn1-schema'; import BigInteger from 'big-integer'; export class Element { constructor( public value: BigInteger ) {} public ToASN1(): ArrayBuffer { try { // 将BigInteger转为Uint8Array const byteArray = this.value.toByteArray(); const uint8Array = new Uint8Array(byteArray); // 直接序列化Uint8Array为ASN.1 INTEGER return AsnSerializer.serialize(uint8Array, { type: AsnTypes.Integer }); } catch (error) { // 这里添加你的错误处理逻辑 } } }
两种方案都能让输出的ASN.1结构变为单个INTEGER,而非外层带SEQUENCE的结构。
内容的提问来源于stack exchange,提问作者ojacomarket
相关产品推荐
相关产品推荐

