本文整理汇总了Python中virtualsmartcard.utils.inttostring函数的典型用法代码示例。如果您正苦于以下问题:Python inttostring函数的具体用法?Python inttostring怎么用?Python inttostring使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了inttostring函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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)
示例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
示例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
示例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()
示例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
示例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)
示例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()
示例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
示例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)
示例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
示例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
示例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
示例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)