• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.inttostring函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中virtualsmartcard.utils.inttostring函数的典型用法代码示例。如果您正苦于以下问题:Python inttostring函数的具体用法?Python inttostring怎么用?Python inttostring使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了inttostring函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: pack

def pack(tlv_data, recalculate_length=False):
    result = b""

    for data in tlv_data:
        tag, length, value = data[:3]
        if tag in (0xff, 0x00):
            result = result + inttostring(tag)
            continue

        if not isinstance(value, bytes):
            value = pack(value, recalculate_length)

        if recalculate_length:
            length = len(value)

        t = b""
        while tag > 0:
            t = inttostring(tag & 0xff) + t
            tag = tag >> 8

        if length < 0x7F:
            l = inttostring(length)
        else:
            l = b""
            while length > 0:
                l = inttostring(length & 0xff) + l
                length = length >> 8
            assert len(l) < 0x7f
            l = inttostring(0x80 | len(l)) + l

        result = result + t
        result = result + l
        result = result + value

    return b"".join(result)
开发者ID:frankmorgner,项目名称:vsmartcard,代码行数:35,代码来源:TLVutils.py


示例2: generate_public_key_pair

    def generate_public_key_pair(self, p1, p2, data):
        """
        In the Cryptoflex card this command only supports RSA keys.

        :param data:
            Contains the public exponent used for key generation
        :param p1:
            The key number. Can be used later to refer to the generated key
        :param p2:
            Used to specify the key length. The mapping is: 0x40 => 256 Bit,
            0x60 => 512 Bit, 0x80 => 1024
        """
        from Crypto.PublicKey import RSA
        from Crypto.Util.randpool import RandomPool

        keynumber = p1  # TODO: Check if key exists

        keylength_dict = {0x40: 256, 0x60: 512, 0x80: 1024}

        if p2 not in keylength_dict:
            raise SwError(SW["ERR_INCORRECTP1P2"])
        else:
            keylength = keylength_dict[p2]

        rnd = RandomPool()
        PublicKey = RSA.generate(keylength, rnd.get_bytes)
        self.dst.key = PublicKey

        e_in = struct.unpack("<i", data)
        if e_in[0] != 65537:
            logging.warning("Warning: Exponents different from 65537 are " +
                            "ignored! The Exponent given is %i" % e_in[0])

        # Encode Public key
        n = PublicKey.__getstate__()['n']
        n_str = inttostring(n)
        n_str = n_str[::-1]
        e = PublicKey.__getstate__()['e']
        e_str = inttostring(e, 4)
        e_str = e_str[::-1]
        pad = 187 * '\x30'  # We don't have CRT components, so we need to pad
        pk_n = TLVutils.bertlv_pack(((0x81, len(n_str), n_str),
                                     (0x01, len(pad), pad),
                                     (0x82, len(e_str), e_str)))
        # Private key
        d = PublicKey.__getstate__()['d']

        # Write result to FID 10 12 EF-PUB-KEY
        df = self.mf.currentDF()
        ef_pub_key = df.select("fid", 0x1012)
        ef_pub_key.writebinary([0], [pk_n])
        data = ef_pub_key.getenc('data')

        # Write private key to FID 00 12 EF-PRI-KEY (not necessary?)
        # How to encode the private key?
        ef_priv_key = df.select("fid", 0x0012)
        ef_priv_key.writebinary([0], [inttostring(d)])
        data = ef_priv_key.getenc('data')
        return PublicKey
开发者ID:frankmorgner,项目名称:vsmartcard,代码行数:59,代码来源:cryptoflex.py


示例3: __init__

    def __init__(self, mf, sam, ins2handler=None, extended_length=False):
        self.mf = mf
        self.SAM = sam

        if not ins2handler:
            self.ins2handler = {
                    0x0c: self.mf.eraseRecord,
                    0x0e: self.mf.eraseBinaryPlain,
                    0x0f: self.mf.eraseBinaryEncapsulated,
                    0x2a: self.SAM.perform_security_operation,
                    0x20: self.SAM.verify,
                    0x22: self.SAM.manage_security_environment,
                    0x24: self.SAM.change_reference_data,
                    0x46: self.SAM.generate_public_key_pair,
                    0x82: self.SAM.external_authenticate,
                    0x84: self.SAM.get_challenge,
                    0x88: self.SAM.internal_authenticate,
                    0xa0: self.mf.searchBinaryPlain,
                    0xa1: self.mf.searchBinaryEncapsulated,
                    0xa4: self.mf.selectFile,
                    0xb0: self.mf.readBinaryPlain,
                    0xb1: self.mf.readBinaryEncapsulated,
                    0xb2: self.mf.readRecordPlain,
                    0xb3: self.mf.readRecordEncapsulated,
                    0xc0: self.getResponse,
                    0xca: self.mf.getDataPlain,
                    0xcb: self.mf.getDataEncapsulated,
                    0xd0: self.mf.writeBinaryPlain,
                    0xd1: self.mf.writeBinaryEncapsulated,
                    0xd2: self.mf.writeRecord,
                    0xd6: self.mf.updateBinaryPlain,
                    0xd7: self.mf.updateBinaryEncapsulated,
                    0xda: self.mf.putDataPlain,
                    0xdb: self.mf.putDataEncapsulated,
                    0xdc: self.mf.updateRecordPlain,
                    0xdd: self.mf.updateRecordEncapsulated,
                    0xe0: self.mf.createFile,
                    0xe2: self.mf.appendRecord,
                    0xe4: self.mf.deleteFile,
                    }
        else:
            self.ins2handler = ins2handler

        if extended_length:
            self.maxle = MAX_EXTENDED_LE
        else:
            self.maxle = MAX_SHORT_LE

        self.lastCommandOffcut = b""
        self.lastCommandSW = SW["NORMAL"]
        el = extended_length  # only needed to keep following line short
        tsft = Iso7816OS.makeThirdSoftwareFunctionTable(extendedLe=el)
        card_capabilities = self.mf.firstSFT + self.mf.secondSFT + tsft
        self.atr = Iso7816OS.makeATR(T=1, directConvention=True, TA1=0x13,
                                     histChars=inttostring(0x80) +
                                     inttostring(0x70 + len(card_capabilities)) +
                                     card_capabilities)
开发者ID:frankmorgner,项目名称:vsmartcard,代码行数:57,代码来源:VirtualSmartcard.py


示例4: tlv_unpack

def tlv_unpack(data):
    ber_class = (data[0] & 0xC0) >> 6
    # 0 = primitive, 0x20 = constructed
    constructed = (data[0] & 0x20) != 0
    tag = data[0]
    data = data[1:]
    if (tag & 0x1F) == 0x1F:
        tag = (tag << 8) | data[0]
        while data[0] & 0x80 == 0x80:
            data = data[1:]
            tag = (tag << 8) | data[0]
        data = data[1:]

    length = data[0]
    if length < 0x80:
        data = data[1:]
    elif length & 0x80 == 0x80:
        length_ = 0
        data = data[1:]
        for i in range(0, length & 0x7F):
            length_ = length_ * 256 + data[0]
            data = data[1:]
        length = length_

    value = b"".join(inttostring(i) for i in data[:length])
    rest = data[length:]

    return ber_class, constructed, tag, length, value, rest
开发者ID:frankmorgner,项目名称:vsmartcard,代码行数:28,代码来源:TLVutils.py


示例5: formatResult

    def formatResult(self, ins, le, data, sw):
        if le == 0 and len(data):
            # cryptoflex does not inpterpret le==0 as maxle
            self.lastCommandSW = sw
            self.lastCommandOffcut = data
            r = R_APDU(inttostring(SW["ERR_WRONGLENGTH"] + min(0xFF, len(data)))).render()
        else:
            if ins == 0xA4 and len(data):
                # get response should be followed by select file
                self.lastCommandSW = sw
                self.lastCommandOffcut = data
                r = R_APDU(inttostring(SW["NORMAL_REST"] + min(0xFF, len(data)))).render()
            else:
                r = Iso7816OS.formatResult(self, Iso7816OS.seekable(ins), le, data, sw, False)

        return r
开发者ID:hsarder,项目名称:vsmartcard,代码行数:16,代码来源:VirtualSmartcard.py


示例6: formatResult

    def formatResult(self, seekable, le, data, sw, sm):
        if seekable:
            # when le = 0 then we want to have 0x9000. here we only have the
            # effective le, which is either MAX_EXTENDED_LE or MAX_SHORT_LE,
            # depending on the APDU. Note that the following distinguisher has
            # one false positive
            if le > len(data) and le != MAX_EXTENDED_LE and le != MAX_SHORT_LE:
                sw = SW["WARN_EOFBEFORENEREAD"]

        if le != None:
            result = data[:le]
        else:
            result = data[:0]
        if sm:
            try:
                sw, result = self.SAM.protect_result(sw, result)
            except SwError as e:
                logging.info(e.message)
                import traceback
                traceback.print_exception(*sys.exc_info())
                sw = e.sw
                result = ""
                answer = self.formatResult(False, 0, result, sw, False)

        return R_APDU(result, inttostring(sw)).render()
开发者ID:Jdi99y515,项目名称:vsmartcard,代码行数:25,代码来源:nPA.py


示例7: __replace_tag

    def __replace_tag(self, tag, data):
        """
        Adjust the config string using a given tag, value combination. If the
        config string already contains a tag, value pair for the given tag,
        replace it. Otherwise append tag, length and value to the config string.
        """
        position = 0
        while position < len(self.__config_string) and \
                self.__config_string[position] != tag:    
            length = stringtoint(self.__config_string[position+1])
            position += length + 3

        if position < len(self.__config_string): #Replace Tag
            length = stringtoint(self.__config_string[position+1])
            self.__config_string = self.__config_string[:position] +\
                                   chr(tag) + inttostring(len(data)) + data +\
                                   self.__config_string[position+2+length:]
        else: #Add new tag
            self.__config_string += chr(tag) + inttostring(len(data)) + data
开发者ID:12019,项目名称:vsmartcard,代码行数:19,代码来源:SEutils.py


示例8: run

    def run(self):
        """
        Main loop of the vpicc. Receives command APDUs via a socket from the
        vpcd, dispatches them to the emulated smartcard and sends the resulting
        respsonse APDU back to the vpcd.
        """
        while True:
            try:
                (size, msg) = self.__recvFromVPICC()
            except socket.error as e:
                if not self.host:
                    logging.info("Waiting for vpcd on port " + str(self.port))
                    (self.sock, address) = self.server_sock.accept()
                    continue
                else:
                    sys.exit()

            if not size:
                logging.warning("Error in communication protocol (missing \
                                size parameter)")
            elif size == VPCD_CTRL_LEN:
                if msg == inttostring(VPCD_CTRL_OFF):
                    logging.info("Power Down")
                    self.os.powerDown()
                elif msg == inttostring(VPCD_CTRL_ON):
                    logging.info("Power Up")
                    self.os.powerUp()
                elif msg == inttostring(VPCD_CTRL_RESET):
                    logging.info("Reset")
                    self.os.reset()
                elif msg == inttostring(VPCD_CTRL_ATR):
                    self.__sendToVPICC(self.os.getATR())
                else:
                    logging.warning("unknown control command")
            else:
                if size != len(msg):
                    logging.warning("Expected %u bytes, but received only %u",
                                    size, len(msg))

                answer = self.os.execute(msg)
                logging.info("Response APDU (%d bytes):\n  %s\n", len(answer),
                             hexdump(answer, indent=2))
                self.__sendToVPICC(answer)
开发者ID:frankmorgner,项目名称:vsmartcard,代码行数:43,代码来源:VirtualSmartcard.py


示例9: formatResult

    def formatResult(self, seekable, le, data, sw, sm):
        if seekable:
            # when le = 0 then we want to have 0x9000. here we only have the
            # effective le, which is either MAX_EXTENDED_LE or MAX_SHORT_LE,
            # depending on the APDU. Note that the following distinguisher has
            # one false positive
            if le > len(data) and le != MAX_EXTENDED_LE and le != MAX_SHORT_LE:
                sw = SW["WARN_EOFBEFORENEREAD"]

        result = data[:le]
        if sm:
            sw, result = self.SAM.protect_result(sw, result)

        return R_APDU(result, inttostring(sw)).render()
开发者ID:Churro,项目名称:vsmartcard,代码行数:14,代码来源:VirtualSmartcard.py


示例10: internal_authenticate

    def internal_authenticate(self, p1, p2, data):
        """
        Authenticate card to terminal. Encrypt the challenge of the terminal
        to prove key posession
        """
        
        if p1 == 0x00: #No information given
            cipher = get_referenced_cipher(self.cipher)   
        else:
            cipher = get_referenced_cipher(p1)

        if cipher == "RSA" or cipher == "DSA":
            crypted_challenge = self.asym_key.sign(data,"")
            crypted_challenge = crypted_challenge[0]
            crypted_challenge = inttostring(crypted_challenge)
        else:
            key = self._get_referenced_key(p1, p2)
            crypted_challenge = vsCrypto.encrypt(cipher, key, data)
        
        return SW["NORMAL"], crypted_challenge
开发者ID:12019,项目名称:vsmartcard,代码行数:20,代码来源:SmartcardSAM.py


示例11: makeThirdSoftwareFunctionTable

 def makeThirdSoftwareFunctionTable(commandChainging=False,
         extendedLe=False, assignLogicalChannel=0, maximumChannels=0):  
     """
     Returns a byte according to the third software function table from the
     historical bytes of the card capabilities.
     """
     tsft = 0
     if commandChainging:
         tsft |= 1 << 7
     if extendedLe:
         tsft |= 1 << 6
     if assignLogicalChannel:
         if not (0<=assignLogicalChannel and assignLogicalChannel<=3):
             raise ValueError
         tsft |= assignLogicalChannel << 3
     if maximumChannels:
         if not (0<=maximumChannels and maximumChannels<=7):
             raise ValueError
         tsft |= maximumChannels
     return inttostring(tsft)
开发者ID:Churro,项目名称:vsmartcard,代码行数:20,代码来源:VirtualSmartcard.py


示例12: protect_response

    def protect_response(self, sw, result):
        """
        This method protects a response APDU using secure messaging mechanisms
        
        :returns: the protected data and the SW bytes
        """

        return_data = ""

        if result != "":
            # Encrypt the data included in the RAPDU
            encrypted = self.encipher(0x82, 0x80, result)
            encrypted = "\x01" + encrypted
            encrypted_tlv = bertlv_pack([(
                                SM_Class["CRYPTOGRAM_PADDING_INDICATOR_ODD"],
                                len(encrypted),
                                encrypted)])
            return_data += encrypted_tlv 

        sw_str = inttostring(sw)
        length = len(sw_str) 
        tag = SM_Class["PLAIN_PROCESSING_STATUS"]
        tlv_sw = bertlv_pack([(tag, length, sw_str)])
        return_data += tlv_sw
        
        if self.cct.algorithm == None:
            raise SwError(SW["CONDITIONSNOTSATISFIED"])
        elif self.cct.algorithm == "CC":
            tag = SM_Class["CHECKSUM"]
            padded = vsCrypto.append_padding(self.cct.blocklength, return_data)
            auth = self.compute_cryptographic_checksum(0x8E, 0x80, padded)
            length = len(auth)
            return_data += bertlv_pack([(tag, length, auth)])
        elif self.cct.algorithm == "SIGNATURE":
            tag = SM_Class["DIGITAL_SIGNATURE"]
            hash = self.hash(0x90, 0x80, return_data)
            auth = self.compute_digital_signature(0x9E, 0x9A, hash)
            length = len(auth)
            return_data += bertlv_pack([(tag, length, auth)])
        
        return sw, return_data
开发者ID:Jdi99y515,项目名称:vsmartcard,代码行数:41,代码来源:nPA.py


示例13: crypto_checksum

def crypto_checksum(algo, key, data, iv=None, ssc=None):
    """
    Compute various types of cryptographic checksums.
    
    :param algo:
        A string specifying the algorithm to use. Currently supported
        algorithms are \"MAX\" \"HMAC\" and \"CC\" (Meaning a cryptographic
        checksum as used by the ICAO passports)
    :param key:  They key used to computed the cryptographic checksum
    :param data: The data for which to calculate the checksum
    :param iv:
        Optional. An initialization vector. Only used by the \"MAC\" algorithm
    :param ssc:
        Optional. A send sequence counter to be prepended to the data.
        Only used by the \"CC\" algorithm
    
    """
    
    if algo not in ("HMAC", "MAC", "CC"):
        raise ValueError("Unknown Algorithm %s" % algo)
    
    if algo == "MAC":
        checksum = calculate_MAC(key, data, iv)
    elif algo == "HMAC":
        hmac = HMAC.new(key, data)
        checksum = hmac.hexdigest()
        del hmac
    elif algo == "CC":
        if ssc != None:
            data = inttostring(ssc) + data        
        a = cipher(True, "des-cbc", key[:8], data)
        b = cipher(False, "des-ecb", key[8:16], a[-8:])
        c = cipher(True, "des-ecb", key[:8], b)
        checksum = c
    
    return checksum
开发者ID:12019,项目名称:vsmartcard,代码行数:36,代码来源:CryptoUtils.py


示例14: simpletlv_pack

def simpletlv_pack(tlv_data, recalculate_length=False):
    result = b""

    for tag, length, value in tlv_data:
        if tag >= 0xff or tag <= 0x00:
            # invalid
            continue

        if recalculate_length:
            length = len(value)
        if length > 0xffff or length < 0:
            # invalid
            continue

        if length < 0xff:
            result += inttostring(tag) + inttostring(length) + value
        else:
            result += inttostring(tag) + inttostring(0xff) + inttostring(length >> 8) + \
                      inttostring(length & 0xff) + value

    return result
开发者ID:frankmorgner,项目名称:vsmartcard,代码行数:21,代码来源:TLVutils.py


示例15: __generate_ePass

    def __generate_ePass(self):
        """Generate the MF and SAM of an ICAO passport. This method is
        responsible for generating the filesystem and filling it with content.
        Therefore it must interact with the user by prompting for the MRZ and
        optionally for the path to a photo."""
        from PIL import Image
        from virtualsmartcard.cards.ePass import PassportSAM

        # TODO: Sanity checks
        MRZ = raw_input("Please enter the MRZ as one string: ")

        readline.set_completer_delims("")
        readline.parse_and_bind("tab: complete")

        picturepath = raw_input("Please enter the path to an image: ")
        picturepath = picturepath.strip()

        # MRZ1 = "P<UTOERIKSSON<<ANNA<MARIX<<<<<<<<<<<<<<<<<<<"
        # MRZ2 = "L898902C<3UTO6908061F9406236ZE184226B<<<<<14"
        # MRZ = MRZ1 + MRZ2

        try:
            im = Image.open(picturepath)
            pic_width, pic_height = im.size
            fd = open(picturepath, "rb")
            picture = fd.read()
            fd.close()
        except IOError:
            logging.warning("Failed to open file: " + picturepath)
            pic_width = 0
            pic_height = 0
            picture = None

        mf = MF()

        # We need a MF with Application DF \xa0\x00\x00\x02G\x10\x01
        df = DF(parent=mf, fid=4, dfname='\xa0\x00\x00\x02G\x10\x01',
                bertlv_data=[])

        # EF.COM
        COM = pack([(0x5F01, 4, "0107"), (0x5F36, 6, "040000"),
                    (0x5C, 2, "6175")])
        COM = pack(((0x60, len(COM), COM),))
        df.append(TransparentStructureEF(parent=df, fid=0x011E,
                  filedescriptor=0, data=COM))

        # EF.DG1
        DG1 = pack([(0x5F1F, len(MRZ), MRZ)])
        DG1 = pack([(0x61, len(DG1), DG1)])
        df.append(TransparentStructureEF(parent=df, fid=0x0101,
                  filedescriptor=0, data=DG1))

        # EF.DG2
        if picture is not None:
            IIB = "\x00\x01" + inttostring(pic_width, 2) +\
                    inttostring(pic_height, 2) + 6 * "\x00"
            length = 32 + len(picture)  # 32 is the length of IIB + FIB
            FIB = inttostring(length, 4) + 16 * "\x00"
            FRH = "FAC" + "\x00" + "010" + "\x00" +\
                  inttostring(14 + length, 4) + inttostring(1, 2)
            picture = FRH + FIB + IIB + picture
            DG2 = pack([(0xA1, 8, "\x87\x02\x01\x01\x88\x02\x05\x01"),
                       (0x5F2E, len(picture), picture)])
            DG2 = pack([(0x02, 1, "\x01"), (0x7F60, len(DG2), DG2)])
            DG2 = pack([(0x7F61, len(DG2), DG2)])
        else:
            DG2 = ""
        df.append(TransparentStructureEF(parent=df, fid=0x0102,
                  filedescriptor=0, data=DG2))

        # EF.SOD
        df.append(TransparentStructureEF(parent=df, fid=0x010D,
                  filedescriptor=0, data=""))

        mf.append(df)

        self.mf = mf
        self.sam = PassportSAM(self.mf)
开发者ID:aslucky,项目名称:vsmartcard,代码行数:78,代码来源:CardGenerator.py


示例16: __generate_nPA

    def __generate_nPA(self):
        from virtualsmartcard.cards.nPA import nPA_SAM
        mappings = [
            (b'\x04\x00\x7f\x00\x07\x02\x02\x04', range(1, 5), range(1, 5),
             "PACE"),
            (b'\x04\x00\x7f\x00\x07\x02\x02\x02', range(1, 3), range(1, 6),
             "TA"),
            (b'\x04\x00\x7f\x00\x07\x02\x02\x02', [1], [6], "TA"),
            (b'\x04\x00\x7f\x00\x07\x02\x02\x03', range(1, 3), range(1, 5),
             "CA"),
            (b'\x04\x00\x7f\x00\x07\x02\x02\x05', range(1, 3), range(1, 6),
             "RI"),
        ]
        for oid_base, x_list, y_list, algo in mappings:
            for oid in [oid_base + inttostring(x) + inttostring(y)
                    for x in x_list for y in y_list]:
                ALGO_MAPPING[oid] = algo
        ALGO_MAPPING[b"\x04\x00\x7f\x00\x07\x03\x01\x04\x03"] = "CommunityID"
        ALGO_MAPPING[b"\x04\x00\x7f\x00\x07\x03\x01\x04\x02"] = "DateOfExpiry"
        ALGO_MAPPING[b"\x04\x00\x7f\x00\x07\x03\x01\x04\x01"] = "DateOfBirth"

        self.mf = MF()

        card_access = b"\x31\x81\xb3\x30\x0d\x06\x08\x04\x00\x7f\x00\x07\x02"\
                      b"\x02\x02\x02\x01\x02\x30\x12\x06\x0a\x04\x00\x7f\x00"\
                      b"\x07\x02\x02\x03\x02\x02\x02\x01\x02\x02\x01\x41\x30"\
                      b"\x12\x06\x0a\x04\x00\x7f\x00\x07\x02\x02\x03\x02\x02"\
                      b"\x02\x01\x02\x02\x01\x45\x30\x12\x06\x0a\x04\x00\x7f"\
                      b"\x00\x07\x02\x02\x04\x02\x02\x02\x01\x02\x02\x01\x0d"\
                      b"\x30\x1c\x06\x09\x04\x00\x7f\x00\x07\x02\x02\x03\x02"\
                      b"\x30\x0c\x06\x07\x04\x00\x7f\x00\x07\x01\x02\x02\x01"\
                      b"\x0d\x02\x01\x41\x30\x1c\x06\x09\x04\x00\x7f\x00\x07"\
                      b"\x02\x02\x03\x02\x30\x0c\x06\x07\x04\x00\x7f\x00\x07"\
                      b"\x01\x02\x02\x01\x0d\x02\x01\x45\x30\x2a\x06\x08\x04"\
                      b"\x00\x7f\x00\x07\x02\x02\x06\x16\x1e\x68\x74\x74\x70"\
                      b"\x3a\x2f\x2f\x62\x73\x69\x2e\x62\x75\x6e\x64\x2e\x64"\
                      b"\x65\x2f\x63\x69\x66\x2f\x6e\x70\x61\x2e\x78\x6d\x6c"
        self.mf.append(TransparentStructureEF(parent=self.mf, fid=0x011c,
                       shortfid=0x1c, data=card_access))
        card_security = b"\x30\x82\x05\xA0\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01"\
                        b"\x07\x02\xA0\x82\x05\x91\x30\x82\x05\x8D\x02\x01\x03"\
                        b"\x31\x0F\x30\x0D\x06\x09\x60\x86\x48\x01\x65\x03\x04"\
                        b"\x02\x01\x05\x00\x30\x82\x01\x48\x06\x08\x04\x00\x7F"\
                        b"\x00\x07\x03\x02\x01\xA0\x82\x01\x3A\x04\x82\x01\x36"\
                        b"\x31\x82\x01\x32\x30\x0D\x06\x08\x04\x00\x7F\x00\x07"\
                        b"\x02\x02\x02\x02\x01\x02\x30\x12\x06\x0A\x04\x00\x7F"\
                        b"\x00\x07\x02\x02\x03\x02\x02\x02\x01\x02\x02\x01\x41"\
                        b"\x30\x12\x06\x0A\x04\x00\x7F\x00\x07\x02\x02\x04\x02"\
                        b"\x02\x02\x01\x02\x02\x01\x0D\x30\x17\x06\x0A\x04\x00"\
                        b"\x7F\x00\x07\x02\x02\x05\x02\x03\x30\x09\x02\x01\x01"\
                        b"\x02\x01\x43\x01\x01\xFF\x30\x17\x06\x0A\x04\x00\x7F"\
                        b"\x00\x07\x02\x02\x05\x02\x03\x30\x09\x02\x01\x01\x02"\
                        b"\x01\x44\x01\x01\x00\x30\x19\x06\x09\x04\x00\x7F\x00"\
                        b"\x07\x02\x02\x05\x02\x30\x0C\x06\x07\x04\x00\x7F\x00"\
                        b"\x07\x01\x02\x02\x01\x0D\x30\x1C\x06\x09\x04\x00\x7F"\
                        b"\x00\x07\x02\x02\x03\x02\x30\x0C\x06\x07\x04\x00\x7F"\
                        b"\x00\x07\x01\x02\x02\x01\x0D\x02\x01\x41\x30\x2A\x06"\
                        b"\x08\x04\x00\x7F\x00\x07\x02\x02\x06\x16\x1E\x68\x74"\
                        b"\x74\x70\x3A\x2F\x2F\x62\x73\x69\x2E\x62\x75\x6E\x64"\
                        b"\x2E\x64\x65\x2F\x63\x69\x66\x2F\x6E\x70\x61\x2E\x78"\
                        b"\x6D\x6C\x30\x62\x06\x09\x04\x00\x7F\x00\x07\x02\x02"\
                        b"\x01\x02\x30\x52\x30\x0C\x06\x07\x04\x00\x7F\x00\x07"\
                        b"\x01\x02\x02\x01\x0D\x03\x42\x00\x04\x92\x5D\xB4\xE1"\
                        b"\x7A\xDE\x58\x20\x9F\x96\xFA\xA0\x7F\x1F\x8A\x22\x3F"\
                        b"\x82\x3F\x96\xCC\x5D\x78\xCB\xEF\x5D\x17\x42\x20\x88"\
                        b"\xFD\xD5\x8E\x56\xBC\x42\x50\xDE\x33\x46\xB3\xC8\x32"\
                        b"\xCA\xE4\x86\x35\xFB\x6C\x43\x78\x9D\xE8\xB3\x10\x2F"\
                        b"\x43\x93\xB4\x18\xE2\x4A\x13\xD9\x02\x01\x41\xA0\x82"\
                        b"\x03\x1C\x30\x82\x03\x18\x30\x82\x02\xBC\xA0\x03\x02"\
                        b"\x01\x02\x02\x02\x01\x5C\x30\x0C\x06\x08\x2A\x86\x48"\
                        b"\xCE\x3D\x04\x03\x02\x05\x00\x30\x4F\x31\x0B\x30\x09"\
                        b"\x06\x03\x55\x04\x06\x13\x02\x44\x45\x31\x0D\x30\x0B"\
                        b"\x06\x03\x55\x04\x0A\x0C\x04\x62\x75\x6E\x64\x31\x0C"\
                        b"\x30\x0A\x06\x03\x55\x04\x0B\x0C\x03\x62\x73\x69\x31"\
                        b"\x0C\x30\x0A\x06\x03\x55\x04\x05\x13\x03\x30\x31\x33"\
                        b"\x31\x15\x30\x13\x06\x03\x55\x04\x03\x0C\x0C\x63\x73"\
                        b"\x63\x61\x2D\x67\x65\x72\x6D\x61\x6E\x79\x30\x1E\x17"\
                        b"\x0D\x31\x30\x31\x30\x30\x35\x31\x31\x30\x37\x35\x32"\
                        b"\x5A\x17\x0D\x32\x31\x30\x34\x30\x35\x30\x38\x33\x39"\
                        b"\x34\x37\x5A\x30\x47\x31\x0B\x30\x09\x06\x03\x55\x04"\
                        b"\x06\x13\x02\x44\x45\x31\x1D\x30\x1B\x06\x03\x55\x04"\
                        b"\x0A\x0C\x14\x42\x75\x6E\x64\x65\x73\x64\x72\x75\x63"\
                        b"\x6B\x65\x72\x65\x69\x20\x47\x6D\x62\x48\x31\x0C\x30"\
                        b"\x0A\x06\x03\x55\x04\x05\x13\x03\x30\x37\x34\x31\x0B"\
                        b"\x30\x09\x06\x03\x55\x04\x03\x0C\x02\x44\x53\x30\x82"\
                        b"\x01\x13\x30\x81\xD4\x06\x07\x2A\x86\x48\xCE\x3D\x02"\
                        b"\x01\x30\x81\xC8\x02\x01\x01\x30\x28\x06\x07\x2A\x86"\
                        b"\x48\xCE\x3D\x01\x01\x02\x1D\x00\xD7\xC1\x34\xAA\x26"\
                        b"\x43\x66\x86\x2A\x18\x30\x25\x75\xD1\xD7\x87\xB0\x9F"\
                        b"\x07\x57\x97\xDA\x89\xF5\x7E\xC8\xC0\xFF\x30\x3C\x04"\
                        b"\x1C\x68\xA5\xE6\x2C\xA9\xCE\x6C\x1C\x29\x98\x03\xA6"\
                        b"\xC1\x53\x0B\x51\x4E\x18\x2A\xD8\xB0\x04\x2A\x59\xCA"\
                        b"\xD2\x9F\x43\x04\x1C\x25\x80\xF6\x3C\xCF\xE4\x41\x38"\
                        b"\x87\x07\x13\xB1\xA9\x23\x69\xE3\x3E\x21\x35\xD2\x66"\
                        b"\xDB\xB3\x72\x38\x6C\x40\x0B\x04\x39\x04\x0D\x90\x29"\
                        b"\xAD\x2C\x7E\x5C\xF4\x34\x08\x23\xB2\xA8\x7D\xC6\x8C"\
                        b"\x9E\x4C\xE3\x17\x4C\x1E\x6E\xFD\xEE\x12\xC0\x7D\x58"\
                        b"\xAA\x56\xF7\x72\xC0\x72\x6F\x24\xC6\xB8\x9E\x4E\xCD"\
                        b"\xAC\x24\x35\x4B\x9E\x99\xCA\xA3\xF6\xD3\x76\x14\x02"\
                        b"\xCD\x02\x1D\x00\xD7\xC1\x34\xAA\x26\x43\x66\x86\x2A"\
#.........这里部分代码省略.........
开发者ID:frankmorgner,项目名称:vsmartcard,代码行数:101,代码来源:CardGenerator.py


示例17: generate_public_key_pair

    def generate_public_key_pair(self, p1, p2, data):
        """
        The GENERATE PUBLIC-KEY PAIR command either initiates the generation
        and storing of a key pair, i.e., a public key and a private key, in the
        card, or accesses a key pair previously generated in the card.

        :param p1: should be 0x00 (generate new key)
        :param p2: '00' (no information provided) or reference of the key to
                   be generated
        :param data: One or more CRTs associated to the key generation if
                     P1-P2 different from '0000'
        """

        from Crypto.PublicKey import RSA, DSA
        from Crypto.Util.randpool import RandomPool
        rnd = RandomPool()

        cipher = self.ct.algorithm

        c_class = locals().get(cipher, None)
        if c_class is None:
            raise SwError(SW["ERR_CONDITIONNOTSATISFIED"])

        if p1 & 0x01 == 0x00:  # Generate key
            PublicKey = c_class.generate(self.dst.keylength, rnd.get_bytes)
            self.dst.key = PublicKey
        else:
            pass  # Read key

        # Encode keys
        if cipher == "RSA":
            # Public key
            n = inttostring(PublicKey.__getstate__()['n'])
            e = inttostring(PublicKey.__getstate__()['e'])
            pk = ((0x81, len(n), n), (0x82, len(e), e))
            result = bertlv_pack(pk)
            # Private key
            d = PublicKey.__getstate__()['d']
        elif cipher == "DSA":
            # DSAParams
            p = inttostring(PublicKey.__getstate__()['p'])
            q = inttostring(PublicKey.__getstate__()['q'])
            g = inttostring(PublicKey.__getstate__()['g'])
            # Public key
            y = inttostring(PublicKey.__getstate__()['y'])
            pk = ((0x81, len(p), p), (0x82, len(q), q), (0x83, len(g), g),
                  (0x84, len(y), y))
            # Private key
            x = inttostring(PublicKey.__getstate__()['x'])
        # Add more algorithms here
        # elif cipher = "ECDSA":
        else:
            raise SwError(SW["ERR_CONDITIONNOTSATISFIED"])

        result = bertlv_pack([[0x7F49, len(pk), pk]])
        # TODO: Internally store key pair

        if p1 & 0x02 == 0x02:
            # We do not support extended header lists yet
            raise SwError["ERR_NOTSUPPORTED"]
        else:
            return SW["NORMAL"], result
开发者ID:frankmorgner,项目名称:vsmartcard,代码行数:62,代码来源:SEutils.py


示例18: parse_SM_CAPDU

    def parse_SM_CAPDU(self, CAPDU, authenticate_header):
        """
        This methods parses a data field including Secure Messaging objects.
        SM_header indicates whether or not the header of the message shall be 
        authenticated. It returns an unprotected command APDU
        
        :param CAPDU: The protected CAPDU to be parsed
        :param authenticate_header: Whether or not the header should be
            included in authentication mechanisms 
        :returns: Unprotected command APDU
        """
            
        structure = unpack(CAPDU.data)
        return_data = ["",]
        
        cla = None
        ins = None
        p1 = None
        p2 = None
        le = None
        
        if authenticate_header:
            to_authenticate = inttostring(CAPDU.cla) + inttostring(CAPDU.ins)+\
                              inttostring(CAPDU.p1) + inttostring(CAPDU.p2)
            to_authenticate = vsCrypto.append_padding(self.cct.blocklength, to_authenticate)
        else:
            to_authenticate = ""

        for tlv in structure:
            tag, length, value = tlv
            
            if tag % 2 == 1: #Include object in checksum calculation
                to_authenticate += bertlv_pack([[tag, length, value]])
            
            #SM data objects for encapsulating plain values
            if tag in (SM_Class["PLAIN_VALUE_NO_TLV"],
                       SM_Class["PLAIN_VALUE_NO_TLV_ODD"]):
                return_data.append(value) #FIXME: Need TLV coding?
            #Encapsulated SM objects. Parse them
            #FIXME: Need to pack value into a dummy CAPDU
            elif tag in (SM_Class["PLAIN_VALUE_TLV_INCULDING_SM"],
                         SM_Class["PLAIN_VALUE_TLV_INCULDING_SM_ODD"]):
                return_data.append(self.parse_SM_CAPDU(value, authenticate_header)) 
            #Encapsulated plaintext BER-TLV objects
            elif tag in (SM_Class["PLAIN_VALUE_TLV_NO_SM"],
                         SM_Class["PLAIN_VALUE_TLV_NO_SM_ODD"]):
                return_data.append(value)
            elif tag in (SM_Class["Ne"], SM_Class["Ne_ODD"]):
                le = value
            elif tag == SM_Class["PLAIN_COMMAND_HEADER"]:
                if len(value) != 8:
                    raise SwError(SW["ERR_SECMESSOBJECTSINCORRECT"])
                else:
                    cla = value[:2]
                    ins = value[2:4]
                    p1 = value[4:6]
                    p2 = value[6:8]

            #SM data objects for confidentiality
            if tag in (SM_Class["CRYPTOGRAM_PLAIN_TLV_INCLUDING_SM"],
                       SM_Class["CRYPTOGRAM_PLAIN_TLV_INCLUDING_SM_ODD"]):
                #The cryptogram includes SM objects. 
                #We decrypt them and parse the objects.
                plain = self.decipher(tag, 0x80, value)
                #TODO: Need Le = length
                return_data.append(self.parse_SM_CAPDU(plain, authenticate_header))
            elif tag in (SM_Class["CRYPTOGRAM_PLAIN_TLV_NO_SM"],
                         SM_Class["CRYPTOGRAM_PLAIN_TLV_NO_SM_ODD"]):
                #The cryptogram includes BER-TLV encoded plaintext. 
                #We decrypt them and return the objects.
                plain = self.decipher(tag, 0x80, value)
                return_data.append(plain)
            elif tag in (SM_Class["CRYPTOGRAM_PADDING_INDICATOR"],
                         SM_Class["CRYPTOGRAM_PADDING_INDICATOR_ODD"]):
                #The first byte of the data field indicates the padding to use:
                """
                Value        Meaning
                '00'     No further indication
                '01'     Padding as specified in 6.2.3.1
                '02'     No padding
                '1X'     One to four secret keys for enciphering information,
                         not keys ('X' is a bitmap with any value from '0' to 'F')
                '11'     indicates the first key (e.g., an "even" control word
                         in a pay TV system)
                '12'     indicates the second key (e.g., an "odd" control word
                         in a pay TV system)
                '13'     indicates the first key followed by the second key
                         (e.g., a pair of control words in a pay TV system)
                '2X'     Secret key for enciphering keys, not information
                         ('X' is a reference with any value from '0' to 'F')
                         (e.g., in a pay TV system, either an operational key
                         for enciphering control words, or a management key for
                         enciphering operational keys)
                '3X'     Private key of an asymmetric key pair ('X' is a
                         reference with any value from '0' to 'F')
                '4X'     Password ('X' is a reference with any value from '0' to
                         'F')
            '80' to '8E' Proprietary
                """
                padding_indicator = stringtoint(value[0])
#.........这里部分代码省略.........
开发者ID:12019,项目名称:vsmartcard,代码行数:101,代码来源:SEutils.py


示例19: selectFile

    def selectFile(self, p1, p2, data):
        """
        Function for instruction 0xa4. Takes the parameter bytes 'p1', 'p2' as
        integers and 'data' as binary string. Returns the status bytes as two
        byte long integer and the response data as binary string.
        """
        P2_FCI = 0
        P2_FCP = 1 << 2
        P2_FMD = 2 << 2
        P2_NONE = 3 << 2
        file = self._selectFile(p1, p2, data)

        if isinstance(file, EF):
            # File size (body only)
            size = inttostring(min(0xffff, len(file.getenc('data'))), 2)
            extra = bytes(0)  # RFU
            if (isinstance(file, RecordStructureEF) and
                    file.hasFixedRecordSize() and not file.isCyclic()):
                # Length of records
                extra += bytes(0) + bytes(min(file.records, 0xff))
       

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python config.init_config函数代码示例发布时间:2022-05-26
下一篇:
Python virtualsmartcard.CryptoUtils类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap