在PKCS#15中有一个结构,CommonObjectAttributes
其中描述了访问对象的规则。令我非常懊恼的是,它是递归的,即它可以包含自己:
SecurityCondition ::= CHOICE {
authId Identifier,
not [0] SecurityCondition,
and [1] SEQUENCE SIZE (2..pkcs15-ub-securityConditions) OF SecurityCondition,
or [2] SEQUENCE SIZE (2..pkcs15-ub-securityConditions) OF SecurityCondition,
... -- For future extensions
}
我对如何用 pyasn1 建模感到困惑。我想我可以强加一个固定级别的递归并简单地让它们相互依赖,但在我看来这不是一个非常有吸引力的解决方案。有没有人有更好的主意?
更新
通过省略最初的定义来测试 Ilya Etingofs 方法,SecurityCondition
我得到了这个:
class SecurityCondition(univ.Choice):
pass
securityConditionComponentType = namedtype.NamedTypes(
namedtype.NamedType('authId', univ.OctetString().subtype(
subtypeSpec=constraint.ValueSizeConstraint(0, univ.Integer(255)))
),
namedtype.NamedType('not', SecurityCondition().subtype(
implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)
)
),
namedtype.NamedType('and', univ.SequenceOf(componentType=SecurityCondition).subtype(
#implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1),
#subtypeSpec=constraint.ValueSizeConstraint(2, univ.Integer(255))
)
),
namedtype.NamedType('or', univ.SequenceOf(componentType=SecurityCondition).subtype(
#implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2),
#subtypeSpec=constraint.ValueSizeConstraint(2, univ.Integer(255))
)
)
)
SecurityCondition.componentType = securityConditionComponentType
使用示例:
# Example usage
inner = univ.SequenceOf()
inner.setComponentByPosition(0, SecurityCondition().setComponentByName("authId", "\x02"))
inner.setComponentByPosition(1, SecurityCondition().setComponentByName("authId", "\x03"))
outer = univ.SequenceOf()
outer.setComponentByPosition(0, SecurityCondition().setComponentByName("authId", "\x01"))
outer.setComponentByPosition(1, SecurityCondition().setComponentByName("or", inner))
wrapper = SecurityCondition().setComponentByName("and", outer)
如果没有使用子类型规范或隐式标签,它似乎可以工作:
>>> print wrapper.prettyPrint()
SecurityCondition:
and=SequenceOf:
SecurityCondition:
authId=0x01
SecurityCondition:
or=SequenceOf:
SecurityCondition:
authId=0x02
SecurityCondition:
authId=0x03
SEQUENCE(2 elem)
OCTET STRING(2 byte) 01
SEQUENCE(2 elem)
OCTET STRING(1 byte) 02
OCTET STRING(1 byte) 03
如果implicitTag
并且subtypeSpec
取消注释错误
PyAsn1Error: Component type error SequenceOf() vs
SequenceOf().setComponentByPosition(0, SecurityCondition().setComponentByPosition(0,
OctetString(hexValue='02'))).setComponentByPosition(1,
SecurityCondition().setComponentByPosition(0, OctetString(hexValue='03')))
发生。巧合的是,如果尝试固定数量的递归,我会遇到同样的错误。