Esempio n. 1
0
def _decode_bitstring(description: str,
                      data: str) -> Tuple[int, base.Asn1Item]:
    """ Decodes an ASN.1 PER Encoded bitstring object

    Args:
        description: The description string of the bitstring (containing constraints, etc)
        data: The PER unaligned encoded binary string

    Returns:
        A tuple containing the PyASN.1 object populated with the decoded data and the
        length of the data processed (used for error checking)

    """
    dec_constraint = _extract_value_size_constraint(description)

    if dec_constraint == -1:
        return 0, univ.BitString(
        )  # No decoding required if length constrained to zero
    elif dec_constraint[0] == dec_constraint[1]:
        decoded_bitstring = '\'' + data[:dec_constraint[0]] + '\'B'
        return dec_constraint[0], univ.BitString(decoded_bitstring)
    else:  # if ub != lb
        offset_bitfield_range = len(
            str(bin(dec_constraint[1] - dec_constraint[0]))[2:])
        length = int(data[:offset_bitfield_range], 2)
        decoded_bitstring = '\'' + data[:length] + '\'B'
        return offset_bitfield_range + length, univ.BitString(
            decoded_bitstring)
Esempio n. 2
0
class _TBSCertificate(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType(
            'version',
            univ.Integer().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 0))),
        namedtype.NamedType('serialNumber', univ.Integer()),
        namedtype.NamedType('signature', univ.Sequence()),
        namedtype.NamedType('issuer', univ.Sequence()),
        namedtype.NamedType('validity', univ.Sequence()),
        namedtype.NamedType('subject', univ.Sequence()),
        namedtype.NamedType('subjectPublicKeyInfo', univ.Sequence()),
        namedtype.OptionalNamedType(
            'issuerUniquedID',
            univ.BitString().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 1))),
        namedtype.OptionalNamedType(
            'subjectUniquedID',
            univ.BitString().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 2))),
        namedtype.OptionalNamedType(
            'extensions',
            univ.Sequence().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 3))),
    )
Esempio n. 3
0
class AccessDescription(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.OptionalNamedType(
            'accessMethod',
            univ.ObjectIdentifier().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 0))),
        namedtype.OptionalNamedType(
            'accessLocation',
            GeneralName().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 1))),
        namedtype.OptionalNamedType(
            'b2',
            univ.BitString().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 2))),
        namedtype.OptionalNamedType(
            'b3',
            univ.BitString().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 3))),
        namedtype.OptionalNamedType(
            'b4',
            univ.BitString().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 4))),
        namedtype.OptionalNamedType(
            'b5',
            univ.BitString().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 5))),
        namedtype.OptionalNamedType(
            'b6',
            univ.BitString().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 6))))
Esempio n. 4
0
class POPOPrivKey(univ.Choice):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType(
            'thisMessage',
            univ.BitString().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 0))),
        namedtype.NamedType(
            'subsequentMessage',
            SubsequentMessage().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 1))),
        namedtype.NamedType(
            'dhMAC',
            univ.BitString().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatSimple, 2))))
Esempio n. 5
0
def convert_PKCS1_to_PKCS8_pubkey(data: bytes) -> bytes:
    pubkey_pkcs1_b64 = b''.join(data.split(b'\n')[1:-2])
    pubkey_pkcs1, restOfInput = der_decoder.decode(
        base64.b64decode(pubkey_pkcs1_b64))
    bit_str = univ.Sequence()
    bit_str.setComponentByPosition(0, univ.Integer(pubkey_pkcs1[0]))
    bit_str.setComponentByPosition(1, univ.Integer(pubkey_pkcs1[1]))
    bit_str = der_encoder.encode(bit_str)
    try:
        bit_str = ''.join([('00000000' + bin(ord(x))[2:])[-8:]
                           for x in list(bit_str)])
    except Exception:
        bit_str = ''.join([('00000000' + bin(x)[2:])[-8:]
                           for x in list(bit_str)])
    bit_str = univ.BitString("'%s'B" % bit_str)
    pubkeyid = univ.Sequence()
    pubkeyid.setComponentByPosition(
        0, univ.ObjectIdentifier(
            '1.2.840.113549.1.1.1'))  # == OID for rsaEncryption
    pubkeyid.setComponentByPosition(1, univ.Null(''))
    pubkey_seq = univ.Sequence()
    pubkey_seq.setComponentByPosition(0, pubkeyid)
    pubkey_seq.setComponentByPosition(1, bit_str)
    pubkey = der_encoder.encode(pubkey_seq)
    return b'-----BEGIN PUBLIC KEY-----\n' + base64.encodebytes(
        pubkey) + b'-----END PUBLIC KEY-----\n'
Esempio n. 6
0
class PubKey(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('b', univ.BitString("'0'B")),
        namedtype.NamedType('c', univ.Integer(32)),
        namedtype.NamedType('x', univ.Integer(0)),
        namedtype.NamedType('y', univ.Integer(0)),
    )
Esempio n. 7
0
def ExportRsaX509(params):
  oid = ASN1Sequence(RSA_OID, univ.Null())
  key = ASN1Sequence(univ.Integer(params['n']), univ.Integer(params['e']))
  binkey = BytesToBin(encoder.encode(key))
  pubkey = univ.BitString("'%s'B" % binkey)  # needs to be a BIT STRING
  seq = ASN1Sequence(oid, pubkey)
  return Base64WSEncode(encoder.encode(seq))
Esempio n. 8
0
def _build_signature(key, tbs, network):
    ''' Takes a utility.ECPrivateKey() as key, tbs as rfc2459.TBSCertificate, and network as pycoin.NETWORK_NAMES
    '''
    secret_exponent = encoding.to_long(256, encoding.byte_to_int,
                                       key[0][1].asOctets())[0]
    coin = Key(secret_exponent=secret_exponent, netcode=network)
    public_pair = coin.public_pair()
    coin_address = coin.address()
    print "building signature for %s address %s" % (network, coin_address)
    pubkeybitstring = (key[0].getComponentByPosition(2),
                       key[0].getComponentByPosition(3))
    tbsder = encoder.encode(tbs)
    hashvalue = SHA256.new(tbsder)
    dgst = hashvalue.digest()
    dgstaslong = encoding.to_long(256, encoding.byte_to_int, dgst)[0]
    order2 = pycoin.ecdsa.generator_secp256k1.order()
    ## random sign
    generator = pycoin.ecdsa.generator_secp256k1
    rawsig2 = randomsign(generator, secret_exponent, dgstaslong)
    # deterministic sign
    ##rawsig2 = pycoin.ecdsa.sign(pycoin.ecdsa.generator_secp256k1, secret_exponent, dgstaslong)
    r2, s2 = rawsig2
    print "signature: r: %x s: %x" % (r2, s2)
    if not pycoin.ecdsa.verify(generator, coin.public_pair(), dgstaslong,
                               rawsig2):
        raise SignatureVerifyException(
            "Generated signature r: %x s: %x does not verify against public key %s"
            % (r2, s2, public_pair))
    signature = utility.ECDSASigValue()
    signature.setComponentByName('r', r2)
    signature.setComponentByName('s', s2)
    dersig = encoder.encode(signature)
    signaturevalue = "'{0}'H".format(binascii.hexlify(dersig))
    bitstring = univ.BitString(value=signaturevalue)
    return rfc2314.Signature(bitstring)
Esempio n. 9
0
class _CertificationRequest(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('certificationRequestInfo',
                            _CertificationRequestInfo()),
        namedtype.NamedType('signatureAlgorithm', univ.Sequence()),
        namedtype.NamedType('signatureValue', univ.BitString()),
        )
Esempio n. 10
0
    def getRSAPublicKey(self):
        """ Gets an ASN.1-encoded form of this RSA key's public key. """
        # Get a RSAPublicKey structure
        pkinfo = univ.Sequence()
        rsakey = self.getRSAKey()
        pkinfo.setComponentByPosition(0, univ.Integer(rsakey.n))
        pkinfo.setComponentByPosition(1, univ.Integer(rsakey.e))

        # Encode the public key info as a bit string
        pklong = long(encoder.encode(pkinfo).encode('hex'), 16)
        pkbitstring = univ.BitString("'00%s'B" % self.toBitString_(pklong))

        # Get the rsaEncryption identifier:
        idrsaencryption = univ.ObjectIdentifier('1.2.840.113549.1.1.1')

        # Get the AlgorithmIdentifier for rsaEncryption
        idinfo = univ.Sequence()
        idinfo.setComponentByPosition(0, idrsaencryption)
        idinfo.setComponentByPosition(1, univ.Null(''))

        # Get the SubjectPublicKeyInfo structure
        publickeyinfo = univ.Sequence()
        publickeyinfo.setComponentByPosition(0, idinfo)
        publickeyinfo.setComponentByPosition(1, pkbitstring)

        # Encode the public key structure
        publickey = encoder.encode(publickeyinfo)
        return publickey
Esempio n. 11
0
class KeyAgreePublicKey(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('algorithm', AlgorithmIdentifier()),
        namedtype.NamedType('publicKey', univ.BitString()),
        namedtype.NamedType('macAlgorithm', AlgorithmIdentifier()),
        namedtype.OptionalNamedType('kDF', AlgorithmIdentifier())
    )
Esempio n. 12
0
def convert_RSA_to_PEM(rsa_key):
    print(rsa_key)
    keydata = base64.b64decode(rsa_key.split()[1])

    parts = []
    while keydata:
        dlen = struct.unpack('>I', keydata[:4])[0]
        data, keydata = keydata[4:dlen + 4], keydata[4 + dlen:]
        parts.append(data)

    e_val = int(parts[1].hex(), 16)
    n_val = int(parts[2].hex(), 16)

    pkcs1_seq = univ.Sequence()
    pkcs1_seq.setComponentByPosition(0, univ.Integer(n_val))
    pkcs1_seq.setComponentByPosition(1, univ.Integer(e_val))
    pkcs1_val = der_encoder.encode(pkcs1_seq)

    head_seq = univ.Sequence()
    head_seq.setComponentByPosition(
        0, univ.ObjectIdentifier('1.2.840.113549.1.1.1'))
    head_seq.setComponentByPosition(1, univ.Null(''))

    out_seq = univ.Sequence()
    out_seq.setComponentByPosition(0, head_seq)
    out_seq.setComponentByPosition(1,
                                   univ.BitString("'%s'H" % pkcs1_val.hex()))
    out = '-----BEGIN PUBLIC KEY-----\n'
    out += base64.encodebytes(der_encoder.encode(out_seq)).strip().decode()
    out += '\n-----END PUBLIC KEY-----\n'
    return out
Esempio n. 13
0
def convertPKCS1toPKCS8pubKey(bitsdata):
    pubkey_pkcs1_b64 = b''.join(bitsdata.split(b'\n')[1:-2])
    pubkey_pkcs1, restOfInput = der_decoder.decode(
        base64.b64decode(pubkey_pkcs1_b64))
    bitstring = univ.Sequence()
    bitstring.setComponentByPosition(0, univ.Integer(pubkey_pkcs1[0]))
    bitstring.setComponentByPosition(1, univ.Integer(pubkey_pkcs1[1]))
    bitstring = der_encoder.encode(bitstring)
    try:
        bitstring = ''.join([('00000000' + bin(ord(x))[2:])[-8:]
                             for x in list(bitstring)])
    except:
        bitstring = ''.join([('00000000' + bin(x)[2:])[-8:]
                             for x in list(bitstring)])
    bitstring = univ.BitString("'%s'B" % bitstring)
    pubkeyid = univ.Sequence()
    pubkeyid.setComponentByPosition(
        0, univ.ObjectIdentifier(
            '1.2.840.113549.1.1.1'))  # == OID for rsaEncryption
    pubkeyid.setComponentByPosition(1, univ.Null(''))
    pubkey_seq = univ.Sequence()
    pubkey_seq.setComponentByPosition(0, pubkeyid)
    pubkey_seq.setComponentByPosition(1, bitstring)
    base64.MAXBINSIZE = (64 // 4) * 3
    res = b"-----BEGIN PUBLIC KEY-----\n"
    res += base64.encodestring(der_encoder.encode(pubkey_seq))
    res += b"-----END PUBLIC KEY-----\n"
    return res
Esempio n. 14
0
class Signature(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('signatureAlgorithm', rfc2459.AlgorithmIdentifier()),
        namedtype.NamedType('signature', univ.BitString()),
        namedtype.OptionalNamedType('certs', univ.SequenceOf(componentType=rfc2459.Certificate()).subtype(
            explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)))
    )
Esempio n. 15
0
 def addNSCertType(self, certType, critical):
     if certType != "sslServer":
         raise UnknownNSCertTypeError(certType)
     self.addExtension(
         univ.ObjectIdentifier("2.16.840.1.113730.1.1"),
         univ.BitString("'01'B"),
         critical,
     )
Esempio n. 16
0
 class ASN1_X9_63_Private_Key(univ.Sequence):
     componentType = namedtype.NamedTypes(
         namedtype.NamedType('flags', univ.BitString()),
         namedtype.NamedType('size', univ.Integer()),
         namedtype.NamedType('x', univ.Integer()),  # public x
         namedtype.NamedType('y', univ.Integer()),
         namedtype.NamedType('k', univ.Integer())  # private key
     )
Esempio n. 17
0
class BasicOCSPResponse(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('tbsResponseData', ResponseData()),
        namedtype.NamedType('signatureAlgorithm',
                            rfc2459.AlgorithmIdentifier()),
        namedtype.NamedType('signature', univ.BitString()),
        namedtype.OptionalNamedType('certs', Certs().subtype(
            explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0))))
Esempio n. 18
0
class POPOSigningKey(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.OptionalNamedType(
            'poposkInput',
            POPOSigningKeyInput().subtype(implicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 0))),
        namedtype.NamedType('algorithmIdentifier', AlgorithmIdentifier()),
        namedtype.NamedType('signature', univ.BitString()))
Esempio n. 19
0
class BitStringDecoder(AbstractSimpleDecoder):
    protoComponent = univ.BitString(())
    tagFormats = (tag.tagFormatSimple, tag.tagFormatConstructed)
    supportConstructedForm = True

    def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length,
                     state, decodeFun, substrateFun):
        head, tail = substrate[:length], substrate[length:]
        if tagSet[
                0].tagFormat == tag.tagFormatSimple:  # XXX what tag to check?
            if not head:
                raise error.PyAsn1Error('Empty substrate')
            trailingBits = oct2int(head[0])
            if trailingBits > 7:
                raise error.PyAsn1Error('Trailing bits overflow %s' %
                                        trailingBits)
            head = head[1:]
            value = self.protoComponent.fromOctetString(head, trailingBits)
            return self._createComponent(asn1Spec, tagSet, value), tail

        if not self.supportConstructedForm:
            raise error.PyAsn1Error(
                'Constructed encoding form prohibited at %s' %
                self.__class__.__name__)

        bitString = self._createComponent(asn1Spec, tagSet)

        if substrateFun:
            return substrateFun(bitString, substrate, length)

        while head:
            component, head = decodeFun(head, self.protoComponent)
            bitString += component

        return bitString, tail

    def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet,
                             length, state, decodeFun, substrateFun):
        bitString = self._createComponent(asn1Spec, tagSet)

        if substrateFun:
            return substrateFun(bitString, substrate, length)

        while substrate:
            component, substrate = decodeFun(substrate,
                                             self.protoComponent,
                                             allowEoo=True)
            if eoo.endOfOctets.isSameTypeWith(
                    component) and component == eoo.endOfOctets:
                break

            bitString += component

        else:
            raise error.SubstrateUnderrunError(
                'No EOO seen before substrate ends')

        return bitString, substrate
Esempio n. 20
0
class BitStringDecoder(AbstractSimpleDecoder):
    protoComponent = univ.BitString(())
    tagFormats = (tag.tagFormatSimple, tag.tagFormatConstructed)
    supportConstructedForm = True

    def valueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet, length,
                     state, decodeFun, substrateFun):
        head, tail = substrate[:length], substrate[length:]
        if tagSet[0][1] == tag.tagFormatSimple:  # XXX what tag to check?
            if not head:
                raise error.PyAsn1Error('Empty substrate')
            trailingBits = oct2int(head[0])
            if trailingBits > 7:
                raise error.PyAsn1Error('Trailing bits overflow %s' %
                                        trailingBits)
            head = head[1:]
            lsb = p = 0
            l = len(head) - 1
            b = []
            while p <= l:
                if p == l:
                    lsb = trailingBits
                j = 7
                o = oct2int(head[p])
                while j >= lsb:
                    b.append((o >> j) & 0x01)
                    j -= 1
                p += 1
            return self._createComponent(asn1Spec, tagSet, b), tail
        if not self.supportConstructedForm:
            raise error.PyAsn1Error(
                'Constructed encoding form prohibited at %s' %
                self.__class__.__name__)
        r = self._createComponent(asn1Spec, tagSet, ())
        if substrateFun:
            return substrateFun(r, substrate, length)
        while head:
            component, head = decodeFun(head, self.protoComponent)
            r = r + component
        return r, tail

    def indefLenValueDecoder(self, fullSubstrate, substrate, asn1Spec, tagSet,
                             length, state, decodeFun, substrateFun):
        r = self._createComponent(asn1Spec, tagSet, '')
        if substrateFun:
            return substrateFun(r, substrate, length)
        while substrate:
            component, substrate = decodeFun(substrate,
                                             self.protoComponent,
                                             allowEoo=True)
            if eoo.endOfOctets.isSameTypeWith(component) and \
                    component == eoo.endOfOctets:
                break
            r = r + component
        else:
            raise error.SubstrateUnderrunError(
                'No EOO seen before substrate ends')
        return r, substrate
Esempio n. 21
0
def ExportDsaX509(params):
  alg_params = ASN1Sequence(univ.Integer(params['p']),
                            univ.Integer(params['q']),
                            univ.Integer(params['g']))
  oid = ASN1Sequence(DSA_OID, alg_params)
  binkey = BytesToBin(encoder.encode(univ.Integer(params['y'])))
  pubkey = univ.BitString("'%s'B" % binkey)  # needs to be a BIT STRING
  seq = ASN1Sequence(oid, pubkey)
  return Base64WSEncode(encoder.encode(seq))
def getPubkey(self, privkey):
    k = gdata.tlslite.utils.keyfactory.parsePEMKey(privkey, private=True)
    oid = ASN1Sequence(univ.ObjectIdentifier('1.2.840.113549.1.1.1'),
                       univ.Null())
    key = ASN1Sequence(univ.Integer(k.n), univ.Integer(k.e))
    binkey = BytesToBin(encoder.encode(key))
    pubkey = univ.BitString("'%s'B" % binkey)
    seq = ASN1Sequence(oid, pubkey)
    pubkeydata = encoder.encode(seq)
    return pubkeydata
Esempio n. 23
0
 def asSubjectPublicKeyInfo(self):
     """Returns a subject public key info representing
     this key for use by pyasn1."""
     algorithmIdentifier = rfc2459.AlgorithmIdentifier()
     algorithmIdentifier['algorithm'] = ecPublicKey
     algorithmIdentifier['parameters'] = self.keyOID
     spki = rfc2459.SubjectPublicKeyInfo()
     spki['algorithm'] = algorithmIdentifier
     spki['subjectPublicKey'] = univ.BitString(self.getPublicKeyHexifiedString())
     return spki
Esempio n. 24
0
def _build_subject_publickey_info(key):
    pubkeybitstring = key[0].getComponentByPosition(3)
    algorithm = univ.Sequence()
    algorithm.setComponentByPosition(0, utility.OID_idEcPublicKey)
    algorithm.setComponentByPosition(1, utility.OID_SECP256K1)
    subjectPublicKeyInfo = SubjectPublicKeyInfo()
    subjectPublicKeyInfo.setComponentByName('algorithm', algorithm)
    subjectPublicKeyInfo.setComponentByName(
        'subjectPublicKey', univ.BitString(value=pubkeybitstring))
    # print subjectPublicKeyInfo
    return subjectPublicKeyInfo
Esempio n. 25
0
class KdcReqBody(univ.Sequence):
    componentType = namedtype.NamedTypes(
        _sequence_component('kdc-options', 0, univ.BitString()),
        _sequence_optional_component('cname', 1, PrincipalName()),
        _sequence_component('realm', 2, char.GeneralString()),
        _sequence_optional_component('sname', 3, PrincipalName()),
        _sequence_optional_component('from', 4, useful.GeneralizedTime()),
        _sequence_component('till', 5, useful.GeneralizedTime()),
        _sequence_component('nonce', 7, univ.Integer()),
        _sequence_component('etype', 8,
                            univ.SequenceOf(componentType=univ.Integer())))
Esempio n. 26
0
class OOBCertHash(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.OptionalNamedType(
            'hashAlg',
            rfc2459.AlgorithmIdentifier().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 0))),
        namedtype.OptionalNamedType(
            'certId',
            rfc2511.CertId().subtype(explicitTag=tag.Tag(
                tag.tagClassContext, tag.tagFormatConstructed, 1))),
        namedtype.NamedType('hashVal', univ.BitString()))
Esempio n. 27
0
class ECPrivateKey(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('version', univ.Integer()),
        namedtype.NamedType('privateKey', univ.OctetString()),
        namedtype.NamedType('namedCurve', univ.ObjectIdentifier().subtype(
        explicitTag=tag.Tag(tag.tagClassContext,
            tag.tagFormatSimple, 0))),
        namedtype.NamedType('publicKey', univ.BitString().subtype(
            implicitTag=tag.Tag(tag.tagClassContext,
                tag.tagFormatSimple, 1)))
        )
class KdcReqBody(univ.Sequence):
    tagSet = univ.Sequence.tagSet + tag.Tag(tag.tagClassContext,
                                            tag.tagFormatSimple, 4)
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('kdc-options', _c(0, univ.BitString())),
        namedtype.OptionalNamedType('cname', _c(1, PrincipalName())),
        namedtype.NamedType('realm', _c(2, char.GeneralString())),
        namedtype.OptionalNamedType('sname', _c(3, PrincipalName())),
        namedtype.NamedType('till', _c(5, useful.GeneralizedTime())),
        namedtype.NamedType('nonce', _c(7, univ.Integer())),
        namedtype.NamedType(
            'etype', _c(8, univ.SequenceOf(componentType=univ.Integer()))))
Esempio n. 29
0
	class ECPublicKey(univ.Sequence):
		"""RFC 5480: Elliptic Curve Cryptography Subject Public Key Information

		SubjectPublicKeyInfo  ::=  SEQUENCE  {
			algorithm         AlgorithmIdentifier,
			subjectPublicKey  BIT STRING
		}
		"""
		componentType = namedtype.NamedTypes(
			namedtype.NamedType("algorithm", AlgorithmIdentifier()),
			namedtype.NamedType("subjectPublicKey", univ.BitString()),
		)
Esempio n. 30
0
def convert_from_sshrsa_to_pkcs8(pubkey):
    """Convert a ssh public key to openssl format
       Equivalent to the ssh-keygen's -m option
    """
    # get the second field from the public key file.
    try:
        keydata = base64.b64decode(pubkey.split(None)[1])
    except IndexError:
        msg = _("Unable to find the key")
        raise exception.EncryptionFailure(reason=msg)

    # decode the parts of the key
    parts = []
    while keydata:
        dlen = struct.unpack('>I', keydata[:4])[0]
        data = keydata[4:dlen + 4]
        keydata = keydata[4 + dlen:]
        parts.append(data)

    # Use asn to build the openssl key structure
    #
    #  SEQUENCE(2 elem)
    #    +- SEQUENCE(2 elem)
    #    |    +- OBJECT IDENTIFIER (1.2.840.113549.1.1.1)
    #    |    +- NULL
    #    +- BIT STRING(1 elem)
    #         +- SEQUENCE(2 elem)
    #              +- INTEGER(2048 bit)
    #              +- INTEGER 65537

    # Build the sequence for the bit string
    n_val = eval('0x' +
                 ''.join(['%02X' % struct.unpack('B', x)[0]
                          for x in parts[2]]))
    e_val = eval('0x' +
                 ''.join(['%02X' % struct.unpack('B', x)[0]
                          for x in parts[1]]))
    pkinfo = _to_sequence(univ.Integer(n_val), univ.Integer(e_val))

    # Convert the sequence into a bit string
    pklong = long(der_encoder.encode(pkinfo).encode('hex'), 16)
    pkbitstring = univ.BitString("'00%s'B" % bin(pklong)[2:])

    # Build the key data structure
    oid = _to_sequence(_RSA_OID, univ.Null())
    pkcs1_seq = _to_sequence(oid, pkbitstring)
    pkcs8 = base64.encodestring(der_encoder.encode(pkcs1_seq))

    # Remove the embedded new line and format the key, each line
    # should be 64 characters long
    return ('-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n' %
            re.sub("(.{64})", "\\1\n", pkcs8.replace('\n', ''), re.DOTALL))