Partial conversion to python 3
git-svn-id: https://vsmartcard.svn.sourceforge.net/svnroot/vsmartcard@667 96b47cad-a561-4643-ad3b-153ac7d7599c
This commit is contained in:
@@ -204,13 +204,13 @@ class CardGenerator(object):
|
||||
passwd1 = getpass.getpass("Please enter your password:")
|
||||
passwd2 = getpass.getpass("Please retype your password:")
|
||||
if (passwd1 != passwd2):
|
||||
raise ValueError, "Passwords did not match. Will now exit"
|
||||
raise ValueError("Passwords did not match. Will now exit")
|
||||
else:
|
||||
self.password = passwd1
|
||||
|
||||
if self.mf == None or self.sam == None:
|
||||
raise ValueError, "Card Generator wasn't set up properly" +\
|
||||
"(missing MF or SAM)."
|
||||
raise ValueError("Card Generator wasn't set up properly" +\
|
||||
"(missing MF or SAM).")
|
||||
|
||||
mf_string = dumps(self.mf)
|
||||
sam_string = dumps(self.sam)
|
||||
|
||||
@@ -42,17 +42,17 @@ def get_cipher(cipherspec, key, iv = None):
|
||||
cipherparts = cipherspec.split("-")
|
||||
|
||||
if len(cipherparts) > 2:
|
||||
raise ValueError, 'cipherspec must be of the form "cipher-mode" or "cipher"'
|
||||
raise ValueError('cipherspec must be of the form "cipher-mode" or "cipher"')
|
||||
elif len(cipherparts) == 1:
|
||||
cipherparts[1] = "ecb"
|
||||
|
||||
c_class = globals().get(cipherparts[0].upper(), None)
|
||||
if c_class is None:
|
||||
raise ValueError, "Cipher '%s' not known, must be one of %s" % (cipherparts[0], ", ".join([e.lower() for e in dir() if e.isupper()]))
|
||||
raise ValueError("Cipher '%s' not known, must be one of %s" % (cipherparts[0], ", ".join([e.lower() for e in dir() if e.isupper()])))
|
||||
|
||||
mode = getattr(c_class, "MODE_" + cipherparts[1].upper(), None)
|
||||
if mode is None:
|
||||
raise ValueError, "Mode '%s' not known, must be one of %s" % (cipherparts[1], ", ".join([e.split("_")[1].lower() for e in dir(c_class) if e.startswith("MODE_")]))
|
||||
raise ValueError("Mode '%s' not known, must be one of %s" % (cipherparts[1], ", ".join([e.split("_")[1].lower() for e in dir(c_class) if e.startswith("MODE_")])))
|
||||
|
||||
cipher = None
|
||||
if iv is None:
|
||||
@@ -66,7 +66,7 @@ def get_cipher_keylen(cipherspec):
|
||||
cipherparts = cipherspec.split("-")
|
||||
|
||||
if len(cipherparts) > 2:
|
||||
raise ValueError, 'cipherspec must be of the form "cipher-mode" or "cipher"'
|
||||
raise ValueError('cipherspec must be of the form "cipher-mode" or "cipher"')
|
||||
|
||||
cipher = cipherparts[0].upper()
|
||||
#cipher = globals().get(cipherparts[0].upper(), None)
|
||||
@@ -78,13 +78,13 @@ def get_cipher_keylen(cipherspec):
|
||||
elif cipher == "DES3":
|
||||
return 16
|
||||
else:
|
||||
raise ValueError, "Unsupported Encryption Algorithm: " + cipher
|
||||
raise ValueError("Unsupported Encryption Algorithm: " + cipher)
|
||||
|
||||
def get_cipher_blocklen(cipherspec):
|
||||
cipherparts = cipherspec.split("-")
|
||||
|
||||
if len(cipherparts) > 2:
|
||||
raise ValueError, 'cipherspec must be of the form "cipher-mode" or "cipher"'
|
||||
raise ValueError('cipherspec must be of the form "cipher-mode" or "cipher"')
|
||||
|
||||
cipher = globals().get(cipherparts[0].upper(), None)
|
||||
return cipher.block_size
|
||||
@@ -137,7 +137,7 @@ def crypto_checksum(algo, key, data, iv=None, ssc=None):
|
||||
"""
|
||||
|
||||
if algo not in ("HMAC", "MAC", "CC"):
|
||||
raise ValueError, "Unknown Algorithm %s" % algo
|
||||
raise ValueError("Unknown Algorithm %s" % algo)
|
||||
|
||||
if algo == "MAC":
|
||||
checksum = calculate_MAC(key, data, iv)
|
||||
@@ -189,7 +189,7 @@ def hash(hashmethod, data):
|
||||
|
||||
def operation_on_string(string1, string2, op):
|
||||
if len(string1) != len(string2):
|
||||
raise ValueError, "string1 and string2 must be of equal length"
|
||||
raise ValueError("string1 and string2 must be of equal length")
|
||||
result = []
|
||||
for i in range(len(string1)):
|
||||
result.append(chr(op(ord(string1[i]), ord(string2[i]))))
|
||||
@@ -236,7 +236,7 @@ def read_protected_string(string, password, cipherspec=None):
|
||||
salt = string[7:match.end() - 1]
|
||||
hmac = string[len(string) - hmac_length:]
|
||||
else:
|
||||
raise ValueError, "Wrong string format"
|
||||
raise ValueError("Wrong string format")
|
||||
|
||||
#Derive key
|
||||
pbk = crypt(password, salt)
|
||||
@@ -247,7 +247,7 @@ def read_protected_string(string, password, cipherspec=None):
|
||||
checksum = crypto_checksum("HMAC", key, crypted)
|
||||
if checksum != hmac:
|
||||
logging.error("Found HMAC %s expected %s" % (str(hmac), str(checksum)))
|
||||
raise ValueError, "Failed to authenticate data. Wrong password?"
|
||||
raise ValueError("Failed to authenticate data. Wrong password?")
|
||||
|
||||
#Decrypt data
|
||||
if cipherspec == None:
|
||||
|
||||
@@ -45,7 +45,7 @@ class ControlReferenceTemplate:
|
||||
if tag not in (CRT_TEMPLATE["AT"], CRT_TEMPLATE["HT"],
|
||||
CRT_TEMPLATE["KAT"], CRT_TEMPLATE["CCT"],
|
||||
CRT_TEMPLATE["DST"], CRT_TEMPLATE["CT"]):
|
||||
raise ValueError, "Unknown control reference tag."
|
||||
raise ValueError("Unknown control reference tag.")
|
||||
else:
|
||||
self.type = tag
|
||||
|
||||
|
||||
@@ -249,11 +249,11 @@ class File(object):
|
||||
self.SAM = SAM
|
||||
if simpletlv_data:
|
||||
if not isinstance(simpletlv_data, list):
|
||||
raise ValueError, "must be a list of (tag, length, value)-tuples"
|
||||
raise TypeError("must be a list of (tag, length, value)-tuples")
|
||||
self.setdec('simpletlv_data', simpletlv_data)
|
||||
if bertlv_data:
|
||||
if not isinstance(bertlv_data, list):
|
||||
raise ValueError, "must be a list of (tag, length, value)-tuples"
|
||||
raise TypeError("must be a list of (tag, length, value)-tuples")
|
||||
self.setdec('bertlv_data', bertlv_data)
|
||||
|
||||
def decrypt(self, path, data):
|
||||
@@ -1474,7 +1474,7 @@ class RecordStructureEF(EF):
|
||||
See EF for more.
|
||||
"""
|
||||
if not isinstance(records, list):
|
||||
raise TypeError, "must be a list of Records"
|
||||
raise TypeError("must be a list of Records")
|
||||
EF.__init__(self, parent, fid, filedescriptor, lifecycle,
|
||||
simpletlv_data, bertlv_data,
|
||||
datacoding, shortfid)
|
||||
|
||||
@@ -74,8 +74,8 @@ class SAM(object):
|
||||
self.cardSecret = urandom(keylen)
|
||||
else:
|
||||
if len(cardSecret) != keylen:
|
||||
raise ValueError, "cardSecret has the wrong key length for: " +\
|
||||
get_referenced_cipher(self.cipher)
|
||||
raise ValueError("cardSecret has the wrong key length for: " +\
|
||||
get_referenced_cipher(self.cipher))
|
||||
else:
|
||||
self.cardSecret = cardSecret
|
||||
|
||||
@@ -357,25 +357,25 @@ if __name__ == "__main__":
|
||||
|
||||
MyCard = SAM("1234", "1234567890")
|
||||
try:
|
||||
print MyCard.verify(0x00, 0x00, "5678")
|
||||
except SwError, e:
|
||||
print e.message
|
||||
print(MyCard.verify(0x00, 0x00, "5678"))
|
||||
except SwError as e:
|
||||
print(e.message)
|
||||
|
||||
print "Counter = " + str(MyCard.counter)
|
||||
print MyCard.verify(0x00, 0x00, "1234")
|
||||
print "Counter = " + str(MyCard.counter)
|
||||
print("Counter = " + str(MyCard.counter))
|
||||
print(MyCard.verify(0x00, 0x00, "1234"))
|
||||
print("Counter = " + str(MyCard.counter))
|
||||
sw, challenge = MyCard.get_challenge(0x00, 0x00, "")
|
||||
print "Before encryption: " + challenge
|
||||
print("Before encryption: " + challenge)
|
||||
padded = vsCrypto.append_padding("DES3-ECB", challenge)
|
||||
sw, result_data = MyCard.internal_authenticate(0x00, 0x00, padded)
|
||||
print "Internal Authenticate status code: %x" % sw
|
||||
print("Internal Authenticate status code: %x" % sw)
|
||||
|
||||
try:
|
||||
sw, res = MyCard.external_authenticate(0x00, 0x00, result_data)
|
||||
except SwError, e:
|
||||
print e.message
|
||||
except SwError as e:
|
||||
print(e.message)
|
||||
sw = e.sw
|
||||
print "Decryption Status code: %x" % sw
|
||||
print("Decryption Status code: %x" % sw)
|
||||
|
||||
#SE = Security_Environment(None)
|
||||
#testvektor = "foobar"
|
||||
|
||||
@@ -271,7 +271,7 @@ class Iso7816OS(SmartcardOS):
|
||||
|
||||
try:
|
||||
c = C_APDU(msg)
|
||||
except ValueError, e:
|
||||
except ValueError as e:
|
||||
logging.warning(str(e))
|
||||
return self.formatResult(False, 0, "", SW["ERR_INCORRECTPARAMETERS"], False)
|
||||
|
||||
@@ -332,7 +332,7 @@ class Iso7816OS(SmartcardOS):
|
||||
answer = self.formatResult(Iso7816OS.seekable(c.ins), c.effective_Le, result, sw, True)
|
||||
else:
|
||||
answer = self.formatResult(Iso7816OS.seekable(c.ins), c.effective_Le, result, sw, False)
|
||||
except SwError, e:
|
||||
except SwError as e:
|
||||
logging.info(e.message)
|
||||
#traceback.print_exception(*sys.exc_info())
|
||||
sw = e.sw
|
||||
@@ -353,14 +353,14 @@ class CryptoflexOS(Iso7816OS):
|
||||
|
||||
try:
|
||||
c = C_APDU(msg)
|
||||
except ValueError, e:
|
||||
except ValueError as e:
|
||||
logging.debug("Failed to parse APDU %s", msg)
|
||||
return self.formatResult(False, 0, 0, "", SW["ERR_INCORRECTPARAMETERS"])
|
||||
|
||||
try:
|
||||
sw, result = self.ins2handler.get(c.ins, notImplemented)(c.p1, c.p2, c.data)
|
||||
#print type(result)
|
||||
except SwError, e:
|
||||
except SwError as e:
|
||||
logging.info(e.message)
|
||||
#traceback.print_exception(*sys.exc_info())
|
||||
sw = e.sw
|
||||
@@ -415,7 +415,7 @@ class RelayOS(SmartcardOS):
|
||||
self.reader = readers[readernum]
|
||||
try:
|
||||
self.session = smartcard.Session(self.reader)
|
||||
except smartcard.Exceptions.CardConnectionException, e:
|
||||
except smartcard.Exceptions.CardConnectionException as e:
|
||||
logging.error("Error connecting to card: %s", e.message)
|
||||
sys.exit()
|
||||
|
||||
@@ -429,7 +429,7 @@ class RelayOS(SmartcardOS):
|
||||
"""
|
||||
try:
|
||||
self.session.close()
|
||||
except smartcard.Exceptions.CardConnectionException, e:
|
||||
except smartcard.Exceptions.CardConnectionException as e:
|
||||
logging.warning("Error disconnecting from card: %s", e.message)
|
||||
|
||||
def getATR(self):
|
||||
@@ -437,13 +437,13 @@ class RelayOS(SmartcardOS):
|
||||
# In this case we must try to reconnect (and then get the ATR).
|
||||
try:
|
||||
atr = self.session.getATR()
|
||||
except smartcard.Exceptions.CardConnectionException, e:
|
||||
except smartcard.Exceptions.CardConnectionException as e:
|
||||
try:
|
||||
# Try to reconnect to the card
|
||||
self.session.close()
|
||||
self.session = smartcard.Session(self.reader)
|
||||
atr = self.session.getATR()
|
||||
except smartcard.Exceptions.CardConnectionException, e:
|
||||
except smartcard.Exceptions.CardConnectionException as e:
|
||||
logging.error("Error getting ATR: %s", e.message)
|
||||
sys.exit()
|
||||
|
||||
@@ -456,10 +456,10 @@ class RelayOS(SmartcardOS):
|
||||
# must try to reconnect (and power the card).
|
||||
try:
|
||||
self.session.getATR()
|
||||
except smartcard.Exceptions.CardConnectionException, e:
|
||||
except smartcard.Exceptions.CardConnectionException as e:
|
||||
try:
|
||||
self.session = smartcard.Session(self.reader)
|
||||
except smartcard.Exceptions.CardConnectionException, e:
|
||||
except smartcard.Exceptions.CardConnectionException as e:
|
||||
logging.error("Error connecting to card: %s", e.message)
|
||||
sys.exit()
|
||||
|
||||
@@ -468,7 +468,7 @@ class RelayOS(SmartcardOS):
|
||||
# disconnect, which should implicitly power down the card.
|
||||
try:
|
||||
self.session.close()
|
||||
except smartcard.Exceptions.CardConnectionException, e:
|
||||
except smartcard.Exceptions.CardConnectionException as e:
|
||||
logging.error("Error disconnecting from card: %s", str(e))
|
||||
sys.exit()
|
||||
|
||||
@@ -478,7 +478,7 @@ class RelayOS(SmartcardOS):
|
||||
|
||||
try:
|
||||
rapdu, sw1, sw2 = self.session.sendCommandAPDU(apdu)
|
||||
except smartcard.Exceptions.CardConnectionException, e:
|
||||
except smartcard.Exceptions.CardConnectionException as e:
|
||||
logging.error("Error transmitting APDU: %s", str(e))
|
||||
sys.exit()
|
||||
|
||||
@@ -574,7 +574,7 @@ class VirtualICC(object):
|
||||
try:
|
||||
self.sock = self.connectToPort(host, port)
|
||||
self.sock.settimeout(None)
|
||||
except socket.error, e:
|
||||
except socket.error as e:
|
||||
logging.error("Failed to open socket: %s", str(e))
|
||||
logging.error("Is pcscd running at %s? Is vpcd loaded? Is a firewall blocking port %u?",
|
||||
host, port)
|
||||
|
||||
@@ -29,7 +29,7 @@ class nPA_AT_CRT(ControlReferenceTemplate):
|
||||
def parse_SE_config(self, config):
|
||||
try:
|
||||
ControlReferenceTemplate.parse_SE_config(self, config)
|
||||
except SwError, e:
|
||||
except SwError as e:
|
||||
structure = unpack(config)
|
||||
for tlv in structure:
|
||||
tag, length, value = tlv
|
||||
|
||||
@@ -45,7 +45,7 @@ def inttostring(i, length=None):
|
||||
if length:
|
||||
l = len(str)
|
||||
if l > length:
|
||||
raise ValueError, "i too big for the specified stringlength"
|
||||
raise ValueError("i too big for the specified stringlength")
|
||||
else:
|
||||
str = chr(0)*(length-l) + str
|
||||
|
||||
@@ -122,10 +122,10 @@ def parse_status(data):
|
||||
lifecycle = ord(segment[1+lgth])
|
||||
privileges = ord(segment[1+lgth+1])
|
||||
|
||||
print "aid length: %i (%x)" % (lgth, lgth)
|
||||
print "aid: %s" % hexdump(aid, indent = 18, short=True)
|
||||
print "life cycle state: %x (%s)" % (lifecycle, LIFE_CYCLES.get(lifecycle, "unknown or invalid state"))
|
||||
print "privileges: %x (%s)\n" % (privileges, parse_privileges(privileges))
|
||||
print("aid length: %i (%x)" % (lgth, lgth))
|
||||
print("aid: %s" % hexdump(aid, indent = 18, short=True))
|
||||
print("life cycle state: %x (%s)" % (lifecycle, LIFE_CYCLES.get(lifecycle, "unknown or invalid state")))
|
||||
print("privileges: %x (%s)\n" % (privileges, parse_privileges(privileges)))
|
||||
|
||||
pos = 0
|
||||
while pos < len(data):
|
||||
@@ -185,7 +185,7 @@ class APDU(object):
|
||||
if t == str:
|
||||
initbuff[index] = ord(value)
|
||||
elif t != int:
|
||||
raise TypeError, "APDU must consist of ints or one-byte strings, not %s (index %s)" % (t, index)
|
||||
raise TypeError("APDU must consist of ints or one-byte strings, not %s (index %s)" % (t, index))
|
||||
|
||||
self.parse( initbuff )
|
||||
|
||||
@@ -201,7 +201,7 @@ class APDU(object):
|
||||
elif isinstance(value, list):
|
||||
self._data = "".join([chr(int(e)) for e in value])
|
||||
else:
|
||||
raise ValueError, "'data' attribute can only be a str or a list of int, not %s" % type(value)
|
||||
raise ValueError("'data' attribute can only be a str or a list of int, not %s" % type(value))
|
||||
self.Lc = len(value)
|
||||
def _deldata(self):
|
||||
del self._data; self.data = ""
|
||||
@@ -216,7 +216,7 @@ class APDU(object):
|
||||
elif isinstance(value, str):
|
||||
setattr(self, "_"+name, ord(value))
|
||||
else:
|
||||
raise ValueError, "'%s' attribute can only be a byte, that is: int or str, not %s" % (name, type(value))
|
||||
raise ValueError("'%s' attribute can only be a byte, that is: int or str, not %s" % (name, type(value)))
|
||||
|
||||
def _format_parts(self, fields):
|
||||
"utility function to be used in __str__ and __repr__"
|
||||
@@ -271,7 +271,7 @@ class C_APDU(APDU):
|
||||
self.Le = (apdu[-2]<<8) + apdu[-1]
|
||||
self.data = apdu[7:-3]
|
||||
else:
|
||||
raise ValueError, "Invalid Lc value. Is %s, should be %s or %s" % (self.Lc,
|
||||
raise ValueError("Invalid Lc value. Is %s, should be %s or %s" % (self.Lc,)
|
||||
7 + self.Lc, 7 + self.Lc + 3)
|
||||
else: # short apdu
|
||||
if len(apdu) == 5: # case 2 short apdu
|
||||
@@ -285,8 +285,8 @@ class C_APDU(APDU):
|
||||
self.data = apdu[5:-1]
|
||||
self.Le = apdu[-1]
|
||||
else:
|
||||
raise ValueError, "Invalid Lc value. Is %s, should be %s or %s" % (self.Lc,
|
||||
5 + self.Lc, 5 + self.Lc + 1)
|
||||
raise ValueError("Invalid Lc value. Is %s, should be %s or %s" % (self.Lc,
|
||||
5 + self.Lc, 5 + self.Lc + 1))
|
||||
|
||||
CLA = _make_byte_property("CLA"); cla = CLA
|
||||
INS = _make_byte_property("INS"); ins = INS
|
||||
@@ -355,7 +355,7 @@ class R_APDU(APDU):
|
||||
def _getsw(self): return chr(self.SW1) + chr(self.SW2)
|
||||
def _setsw(self, value):
|
||||
if len(value) != 2:
|
||||
raise ValueError, "SW must be exactly two bytes"
|
||||
raise ValueError("SW must be exactly two bytes")
|
||||
self.SW1 = value[0]
|
||||
self.SW2 = value[1]
|
||||
|
||||
@@ -385,39 +385,39 @@ if __name__ == "__main__":
|
||||
c = C_APDU((1, 2, 3), cla = 0x23, data = "hallo") # case 3
|
||||
d = C_APDU(1, 2, 3, 4, 2, 4, 6, 0) # case 4
|
||||
|
||||
print
|
||||
print a
|
||||
print b
|
||||
print c
|
||||
print d
|
||||
print
|
||||
print repr(a)
|
||||
print repr(b)
|
||||
print repr(c)
|
||||
print repr(d)
|
||||
print()
|
||||
print(a)
|
||||
print(b)
|
||||
print(c)
|
||||
print(d)
|
||||
print()
|
||||
print(repr(a))
|
||||
print(repr(b))
|
||||
print(repr(c))
|
||||
print(repr(d))
|
||||
|
||||
print
|
||||
print()
|
||||
for i in a, b, c, d:
|
||||
print hexdump(i.render())
|
||||
print(hexdump(i.render()))
|
||||
|
||||
print
|
||||
print()
|
||||
e = R_APDU(0x90, 0)
|
||||
f = R_APDU("foo\x67\x00")
|
||||
|
||||
print
|
||||
print e
|
||||
print f
|
||||
print
|
||||
print repr(e)
|
||||
print repr(f)
|
||||
print()
|
||||
print(e)
|
||||
print(f)
|
||||
print()
|
||||
print(repr(e))
|
||||
print(repr(f))
|
||||
|
||||
print
|
||||
print()
|
||||
for i in e, f:
|
||||
print hexdump(i.render())
|
||||
print(hexdump(i.render()))
|
||||
|
||||
g = C_APDU(0x00, 0xb0, 0x9c, 0x00, 0x00, 0x00, 0x00) #case 2 extended length
|
||||
|
||||
print
|
||||
print g
|
||||
print repr(g)
|
||||
print hexdump(g.render())
|
||||
print()
|
||||
print(g)
|
||||
print(repr(g))
|
||||
print(hexdump(g.render()))
|
||||
|
||||
Reference in New Issue
Block a user