예제 #1
0
def stringToDN(string, tag=None):
    """Takes a string representing a distinguished name or directory
    name and returns a Name for use by pyasn1. See the documentation
    for the issuer and subject fields for more details. Takes an
    optional implicit tag in cases where the Name needs to be tagged
    differently."""
    if '/' not in string:
        string = '/CN=%s' % string
    rdns = rfc2459.RDNSequence()
    pos = 0
    pattern = '/(C|ST|L|O|OU|CN|emailAddress)='
    split = re.split(pattern, string)
    # split should now be [[encoding], <type>, <value>, <type>, <value>, ...]
    if split[0]:
        encoding = split[0]
    else:
        encoding = 'utf8String'
    for (nameType, value) in zip(split[1::2], split[2::2]):
        ava = rfc2459.AttributeTypeAndValue()
        if nameType == 'C':
            ava.setComponentByName('type', rfc2459.id_at_countryName)
            nameComponent = rfc2459.X520countryName(value)
        elif nameType == 'ST':
            ava.setComponentByName('type', rfc2459.id_at_stateOrProvinceName)
            nameComponent = rfc2459.X520StateOrProvinceName()
        elif nameType == 'L':
            ava.setComponentByName('type', rfc2459.id_at_localityName)
            nameComponent = rfc2459.X520LocalityName()
        elif nameType == 'O':
            ava.setComponentByName('type', rfc2459.id_at_organizationName)
            nameComponent = rfc2459.X520OrganizationName()
        elif nameType == 'OU':
            ava.setComponentByName('type',
                                   rfc2459.id_at_organizationalUnitName)
            nameComponent = rfc2459.X520OrganizationalUnitName()
        elif nameType == 'CN':
            ava.setComponentByName('type', rfc2459.id_at_commonName)
            nameComponent = rfc2459.X520CommonName()
        elif nameType == 'emailAddress':
            ava.setComponentByName('type', rfc2459.emailAddress)
            nameComponent = rfc2459.Pkcs9email(value)
        else:
            raise UnknownDNTypeError(nameType)
        if not nameType == 'C' and not nameType == 'emailAddress':
            # The value may have things like '\0' (i.e. a slash followed by
            # the number zero) that have to be decoded into the resulting
            # '\x00' (i.e. a byte with value zero).
            nameComponent.setComponentByName(
                encoding, value.decode(encoding='string_escape'))
        ava.setComponentByName('value', nameComponent)
        rdn = rfc2459.RelativeDistinguishedName()
        rdn.setComponentByPosition(0, ava)
        rdns.setComponentByPosition(pos, rdn)
        pos = pos + 1
    if tag:
        name = rfc2459.Name().subtype(implicitTag=tag)
    else:
        name = rfc2459.Name()
    name.setComponentByPosition(0, rdns)
    return name
예제 #2
0
    def __init__(self, attrs):
        if isinstance(attrs, list):
            self.asn = rfc2459.Name()
            vals = rfc2459.RDNSequence()

            for (i, attr) in enumerate(attrs):
                if not isinstance(attr, list):
                    attr = [attr]
                pairset = rfc2459.RelativeDistinguishedName()
                for (j, (oid, val)) in enumerate(attr):
                    pair = rfc2459.AttributeTypeAndValue()
                    pair.setComponentByName('type',
                                            rfc2459.AttributeType(str(oid)))
                    code, enc = self.special_encs.get(
                        oid, (char.UTF8String, 'utf-8'))
                    pair.setComponentByName(
                        'value',
                        rfc2459.AttributeValue(
                            univ.OctetString(
                                encoder.encode(
                                    code(unicode(val).encode(enc,
                                                             'replace'))))))
                    pairset.setComponentByPosition(j, pair)

                vals.setComponentByPosition(i, pairset)

            self.asn.setComponentByPosition(0, vals)
        else:
            self.asn = attrs
예제 #3
0
def stringToDN(string, tag=None):
    """Takes a string representing a distinguished name or directory
    name and returns a Name for use by pyasn1. See the documentation
    for the issuer and subject fields for more details. Takes an
    optional implicit tag in cases where the Name needs to be tagged
    differently."""
    if string and "/" not in string:
        string = "/CN=%s" % string
    rdns = rfc2459.RDNSequence()
    pattern = "/(C|ST|L|O|OU|CN|emailAddress)="
    split = re.split(pattern, string)
    # split should now be [[encoding], <type>, <value>, <type>, <value>, ...]
    if split[0]:
        encoding = split[0]
    else:
        encoding = "utf8String"
    for pos, (nameType, value) in enumerate(zip(split[1::2], split[2::2])):
        ava = rfc2459.AttributeTypeAndValue()
        if nameType == "C":
            ava["type"] = rfc2459.id_at_countryName
            nameComponent = rfc2459.X520countryName(value)
        elif nameType == "ST":
            ava["type"] = rfc2459.id_at_stateOrProvinceName
            nameComponent = rfc2459.X520StateOrProvinceName()
        elif nameType == "L":
            ava["type"] = rfc2459.id_at_localityName
            nameComponent = rfc2459.X520LocalityName()
        elif nameType == "O":
            ava["type"] = rfc2459.id_at_organizationName
            nameComponent = rfc2459.X520OrganizationName()
        elif nameType == "OU":
            ava["type"] = rfc2459.id_at_organizationalUnitName
            nameComponent = rfc2459.X520OrganizationalUnitName()
        elif nameType == "CN":
            ava["type"] = rfc2459.id_at_commonName
            nameComponent = rfc2459.X520CommonName()
        elif nameType == "emailAddress":
            ava["type"] = rfc2459.emailAddress
            nameComponent = rfc2459.Pkcs9email(value)
        else:
            raise UnknownDNTypeError(nameType)
        if not nameType == "C" and not nameType == "emailAddress":
            # The value may have things like '\0' (i.e. a slash followed by
            # the number zero) that have to be decoded into the resulting
            # '\x00' (i.e. a byte with value zero).
            nameComponent[encoding] = six.ensure_binary(value).decode(
                encoding="unicode_escape"
            )
        ava["value"] = nameComponent
        rdn = rfc2459.RelativeDistinguishedName()
        rdn.setComponentByPosition(0, ava)
        rdns.setComponentByPosition(pos, rdn)
    if tag:
        name = rfc2459.Name().subtype(implicitTag=tag)
    else:
        name = rfc2459.Name()
    name.setComponentByPosition(0, rdns)
    return name
예제 #4
0
def _RDNSeqFromTuple(values):
    seq = rfc2459.RDNSequence()
    for i, v in enumerate(values):
        oi_type = '.'.join([str(x) for x in v[0]])
        typevalue = rfc2459.AttributeTypeAndValue()
        typevalue.setComponentByPosition(0, rfc2459.AttributeType(oi_type))
        typevalue.setComponentByPosition(1, rfc2459.AttributeValue(v[1]))
        seq.setComponentByPosition(
            i,
            rfc2459.RelativeDistinguishedName().setComponentByPosition(
                0, typevalue))

    return rfc2459.Name().setComponentByPosition(0, seq)
예제 #5
0
def parse_rdn(rdn_str: str) -> rfc2459.RDNSequence:
    rdn_parts = rdn_str.split(',')
    rdn_seq = rfc2459.RDNSequence()

    for i, part in enumerate(rdn_parts):
        k, v = [item.strip() for item in part.split('=')]

        attr = rfc2459.AttributeTypeAndValue()
        attr['type'] = RDN_OID_LOOKUP[k]
        attr['value'] = OctetString(encoder.encode(RDN_TYPE_LOOKUP[k](v)))

        rdn = rfc2459.RelativeDistinguishedName()
        rdn.setComponentByPosition(0, attr)
        rdn_seq.setComponentByPosition(i, rdn)

    return rdn_seq
예제 #6
0
def stringToCommonName(string):
    """Helper function for taking a string and building an x520 name
    representation usable by the pyasn1 package. Currently returns one
    RDN with one AVA consisting of a Common Name encoded as a
    UTF8String."""
    commonName = rfc2459.X520CommonName()
    commonName.setComponentByName('utf8String', string)
    ava = rfc2459.AttributeTypeAndValue()
    ava.setComponentByName('type', rfc2459.id_at_commonName)
    ava.setComponentByName('value', commonName)
    rdn = rfc2459.RelativeDistinguishedName()
    rdn.setComponentByPosition(0, ava)
    rdns = rfc2459.RDNSequence()
    rdns.setComponentByPosition(0, rdn)
    name = rfc2459.Name()
    name.setComponentByPosition(0, rdns)
    return name
예제 #7
0
파일: name.py 프로젝트: jqxin2006/anchor
 def add_name_entry(self, oid, text):
     if not isinstance(oid, asn1_univ.ObjectIdentifier):
         raise errors.X509Error("oid '%s' is not valid" % (oid, ))
     entry = rfc2459.RelativeDistinguishedName()
     entry[0] = rfc2459.AttributeTypeAndValue()
     entry[0]['type'] = oid
     name_type = name_oids[oid]
     try:
         if name_type in (rfc2459.X520countryName, rfc2459.Pkcs9email):
             val = name_type(text)
         else:
             val = name_type()
             val['utf8String'] = text
     except asn1_error.ValueConstraintError:
         raise errors.X509Error("Name '%s' is not valid" % text)
     entry[0]['value'] = rfc2459.AttributeValue(encoder.encode(val))
     self._name_obj[len(self)] = entry
예제 #8
0
def stringToCommonName(string):
    """Helper function for taking a string and building an x520 name
    representation usable by the pyasn1 package. Currently returns one
    RDN with one AVA consisting of a Common Name encoded as a
    UTF8String."""
    commonName = rfc2459.X520CommonName()
    # The string may have things like '\0' (i.e. a slash followed by
    # the number zero) that have to be decoded into the resulting
    # '\x00' (i.e. a byte with value zero).
    commonName.setComponentByName('utf8String',
                                  string.decode(encoding='string_escape'))
    ava = rfc2459.AttributeTypeAndValue()
    ava.setComponentByName('type', rfc2459.id_at_commonName)
    ava.setComponentByName('value', commonName)
    rdn = rfc2459.RelativeDistinguishedName()
    rdn.setComponentByPosition(0, ava)
    rdns = rfc2459.RDNSequence()
    rdns.setComponentByPosition(0, rdn)
    name = rfc2459.Name()
    name.setComponentByPosition(0, rdns)
    return name