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:
oepen
2011-12-11 16:56:15 +00:00
parent 899ea104c6
commit 6bf7ca9b3f
8 changed files with 81 additions and 81 deletions

View File

@@ -204,13 +204,13 @@ class CardGenerator(object):
passwd1 = getpass.getpass("Please enter your password:") passwd1 = getpass.getpass("Please enter your password:")
passwd2 = getpass.getpass("Please retype your password:") passwd2 = getpass.getpass("Please retype your password:")
if (passwd1 != passwd2): if (passwd1 != passwd2):
raise ValueError, "Passwords did not match. Will now exit" raise ValueError("Passwords did not match. Will now exit")
else: else:
self.password = passwd1 self.password = passwd1
if self.mf == None or self.sam == None: if self.mf == None or self.sam == None:
raise ValueError, "Card Generator wasn't set up properly" +\ raise ValueError("Card Generator wasn't set up properly" +\
"(missing MF or SAM)." "(missing MF or SAM).")
mf_string = dumps(self.mf) mf_string = dumps(self.mf)
sam_string = dumps(self.sam) sam_string = dumps(self.sam)

View File

@@ -42,17 +42,17 @@ def get_cipher(cipherspec, key, iv = None):
cipherparts = cipherspec.split("-") cipherparts = cipherspec.split("-")
if len(cipherparts) > 2: 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: elif len(cipherparts) == 1:
cipherparts[1] = "ecb" cipherparts[1] = "ecb"
c_class = globals().get(cipherparts[0].upper(), None) c_class = globals().get(cipherparts[0].upper(), None)
if c_class is 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) mode = getattr(c_class, "MODE_" + cipherparts[1].upper(), None)
if mode is 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 cipher = None
if iv is None: if iv is None:
@@ -66,7 +66,7 @@ def get_cipher_keylen(cipherspec):
cipherparts = cipherspec.split("-") cipherparts = cipherspec.split("-")
if len(cipherparts) > 2: 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 = cipherparts[0].upper()
#cipher = globals().get(cipherparts[0].upper(), None) #cipher = globals().get(cipherparts[0].upper(), None)
@@ -78,13 +78,13 @@ def get_cipher_keylen(cipherspec):
elif cipher == "DES3": elif cipher == "DES3":
return 16 return 16
else: else:
raise ValueError, "Unsupported Encryption Algorithm: " + cipher raise ValueError("Unsupported Encryption Algorithm: " + cipher)
def get_cipher_blocklen(cipherspec): def get_cipher_blocklen(cipherspec):
cipherparts = cipherspec.split("-") cipherparts = cipherspec.split("-")
if len(cipherparts) > 2: 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) cipher = globals().get(cipherparts[0].upper(), None)
return cipher.block_size 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"): if algo not in ("HMAC", "MAC", "CC"):
raise ValueError, "Unknown Algorithm %s" % algo raise ValueError("Unknown Algorithm %s" % algo)
if algo == "MAC": if algo == "MAC":
checksum = calculate_MAC(key, data, iv) checksum = calculate_MAC(key, data, iv)
@@ -189,7 +189,7 @@ def hash(hashmethod, data):
def operation_on_string(string1, string2, op): def operation_on_string(string1, string2, op):
if len(string1) != len(string2): 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 = [] result = []
for i in range(len(string1)): for i in range(len(string1)):
result.append(chr(op(ord(string1[i]), ord(string2[i])))) 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] salt = string[7:match.end() - 1]
hmac = string[len(string) - hmac_length:] hmac = string[len(string) - hmac_length:]
else: else:
raise ValueError, "Wrong string format" raise ValueError("Wrong string format")
#Derive key #Derive key
pbk = crypt(password, salt) pbk = crypt(password, salt)
@@ -247,7 +247,7 @@ def read_protected_string(string, password, cipherspec=None):
checksum = crypto_checksum("HMAC", key, crypted) checksum = crypto_checksum("HMAC", key, crypted)
if checksum != hmac: if checksum != hmac:
logging.error("Found HMAC %s expected %s" % (str(hmac), str(checksum))) 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 #Decrypt data
if cipherspec == None: if cipherspec == None:

View File

@@ -45,7 +45,7 @@ class ControlReferenceTemplate:
if tag not in (CRT_TEMPLATE["AT"], CRT_TEMPLATE["HT"], if tag not in (CRT_TEMPLATE["AT"], CRT_TEMPLATE["HT"],
CRT_TEMPLATE["KAT"], CRT_TEMPLATE["CCT"], CRT_TEMPLATE["KAT"], CRT_TEMPLATE["CCT"],
CRT_TEMPLATE["DST"], CRT_TEMPLATE["CT"]): CRT_TEMPLATE["DST"], CRT_TEMPLATE["CT"]):
raise ValueError, "Unknown control reference tag." raise ValueError("Unknown control reference tag.")
else: else:
self.type = tag self.type = tag

View File

@@ -249,11 +249,11 @@ class File(object):
self.SAM = SAM self.SAM = SAM
if simpletlv_data: if simpletlv_data:
if not isinstance(simpletlv_data, list): 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) self.setdec('simpletlv_data', simpletlv_data)
if bertlv_data: if bertlv_data:
if not isinstance(bertlv_data, list): 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) self.setdec('bertlv_data', bertlv_data)
def decrypt(self, path, data): def decrypt(self, path, data):
@@ -1474,7 +1474,7 @@ class RecordStructureEF(EF):
See EF for more. See EF for more.
""" """
if not isinstance(records, list): 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, EF.__init__(self, parent, fid, filedescriptor, lifecycle,
simpletlv_data, bertlv_data, simpletlv_data, bertlv_data,
datacoding, shortfid) datacoding, shortfid)

View File

@@ -74,8 +74,8 @@ class SAM(object):
self.cardSecret = urandom(keylen) self.cardSecret = urandom(keylen)
else: else:
if len(cardSecret) != keylen: if len(cardSecret) != keylen:
raise ValueError, "cardSecret has the wrong key length for: " +\ raise ValueError("cardSecret has the wrong key length for: " +\
get_referenced_cipher(self.cipher) get_referenced_cipher(self.cipher))
else: else:
self.cardSecret = cardSecret self.cardSecret = cardSecret
@@ -357,25 +357,25 @@ if __name__ == "__main__":
MyCard = SAM("1234", "1234567890") MyCard = SAM("1234", "1234567890")
try: try:
print MyCard.verify(0x00, 0x00, "5678") print(MyCard.verify(0x00, 0x00, "5678"))
except SwError, e: except SwError as e:
print e.message print(e.message)
print "Counter = " + str(MyCard.counter) print("Counter = " + str(MyCard.counter))
print MyCard.verify(0x00, 0x00, "1234") print(MyCard.verify(0x00, 0x00, "1234"))
print "Counter = " + str(MyCard.counter) print("Counter = " + str(MyCard.counter))
sw, challenge = MyCard.get_challenge(0x00, 0x00, "") sw, challenge = MyCard.get_challenge(0x00, 0x00, "")
print "Before encryption: " + challenge print("Before encryption: " + challenge)
padded = vsCrypto.append_padding("DES3-ECB", challenge) padded = vsCrypto.append_padding("DES3-ECB", challenge)
sw, result_data = MyCard.internal_authenticate(0x00, 0x00, padded) sw, result_data = MyCard.internal_authenticate(0x00, 0x00, padded)
print "Internal Authenticate status code: %x" % sw print("Internal Authenticate status code: %x" % sw)
try: try:
sw, res = MyCard.external_authenticate(0x00, 0x00, result_data) sw, res = MyCard.external_authenticate(0x00, 0x00, result_data)
except SwError, e: except SwError as e:
print e.message print(e.message)
sw = e.sw sw = e.sw
print "Decryption Status code: %x" % sw print("Decryption Status code: %x" % sw)
#SE = Security_Environment(None) #SE = Security_Environment(None)
#testvektor = "foobar" #testvektor = "foobar"

View File

@@ -271,7 +271,7 @@ class Iso7816OS(SmartcardOS):
try: try:
c = C_APDU(msg) c = C_APDU(msg)
except ValueError, e: except ValueError as e:
logging.warning(str(e)) logging.warning(str(e))
return self.formatResult(False, 0, "", SW["ERR_INCORRECTPARAMETERS"], False) 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) answer = self.formatResult(Iso7816OS.seekable(c.ins), c.effective_Le, result, sw, True)
else: else:
answer = self.formatResult(Iso7816OS.seekable(c.ins), c.effective_Le, result, sw, False) answer = self.formatResult(Iso7816OS.seekable(c.ins), c.effective_Le, result, sw, False)
except SwError, e: except SwError as e:
logging.info(e.message) logging.info(e.message)
#traceback.print_exception(*sys.exc_info()) #traceback.print_exception(*sys.exc_info())
sw = e.sw sw = e.sw
@@ -353,14 +353,14 @@ class CryptoflexOS(Iso7816OS):
try: try:
c = C_APDU(msg) c = C_APDU(msg)
except ValueError, e: except ValueError as e:
logging.debug("Failed to parse APDU %s", msg) logging.debug("Failed to parse APDU %s", msg)
return self.formatResult(False, 0, 0, "", SW["ERR_INCORRECTPARAMETERS"]) return self.formatResult(False, 0, 0, "", SW["ERR_INCORRECTPARAMETERS"])
try: try:
sw, result = self.ins2handler.get(c.ins, notImplemented)(c.p1, c.p2, c.data) sw, result = self.ins2handler.get(c.ins, notImplemented)(c.p1, c.p2, c.data)
#print type(result) #print type(result)
except SwError, e: except SwError as e:
logging.info(e.message) logging.info(e.message)
#traceback.print_exception(*sys.exc_info()) #traceback.print_exception(*sys.exc_info())
sw = e.sw sw = e.sw
@@ -415,7 +415,7 @@ class RelayOS(SmartcardOS):
self.reader = readers[readernum] self.reader = readers[readernum]
try: try:
self.session = smartcard.Session(self.reader) 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) logging.error("Error connecting to card: %s", e.message)
sys.exit() sys.exit()
@@ -429,7 +429,7 @@ class RelayOS(SmartcardOS):
""" """
try: try:
self.session.close() self.session.close()
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException as e:
logging.warning("Error disconnecting from card: %s", e.message) logging.warning("Error disconnecting from card: %s", e.message)
def getATR(self): def getATR(self):
@@ -437,13 +437,13 @@ class RelayOS(SmartcardOS):
# In this case we must try to reconnect (and then get the ATR). # In this case we must try to reconnect (and then get the ATR).
try: try:
atr = self.session.getATR() atr = self.session.getATR()
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException as e:
try: try:
# Try to reconnect to the card # Try to reconnect to the card
self.session.close() self.session.close()
self.session = smartcard.Session(self.reader) self.session = smartcard.Session(self.reader)
atr = self.session.getATR() atr = self.session.getATR()
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException as e:
logging.error("Error getting ATR: %s", e.message) logging.error("Error getting ATR: %s", e.message)
sys.exit() sys.exit()
@@ -456,10 +456,10 @@ class RelayOS(SmartcardOS):
# must try to reconnect (and power the card). # must try to reconnect (and power the card).
try: try:
self.session.getATR() self.session.getATR()
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException as e:
try: try:
self.session = smartcard.Session(self.reader) 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) logging.error("Error connecting to card: %s", e.message)
sys.exit() sys.exit()
@@ -468,7 +468,7 @@ class RelayOS(SmartcardOS):
# disconnect, which should implicitly power down the card. # disconnect, which should implicitly power down the card.
try: try:
self.session.close() self.session.close()
except smartcard.Exceptions.CardConnectionException, e: except smartcard.Exceptions.CardConnectionException as e:
logging.error("Error disconnecting from card: %s", str(e)) logging.error("Error disconnecting from card: %s", str(e))
sys.exit() sys.exit()
@@ -478,7 +478,7 @@ class RelayOS(SmartcardOS):
try: try:
rapdu, sw1, sw2 = self.session.sendCommandAPDU(apdu) 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)) logging.error("Error transmitting APDU: %s", str(e))
sys.exit() sys.exit()
@@ -574,7 +574,7 @@ class VirtualICC(object):
try: try:
self.sock = self.connectToPort(host, port) self.sock = self.connectToPort(host, port)
self.sock.settimeout(None) self.sock.settimeout(None)
except socket.error, e: except socket.error as e:
logging.error("Failed to open socket: %s", str(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?", logging.error("Is pcscd running at %s? Is vpcd loaded? Is a firewall blocking port %u?",
host, port) host, port)

View File

@@ -29,7 +29,7 @@ class nPA_AT_CRT(ControlReferenceTemplate):
def parse_SE_config(self, config): def parse_SE_config(self, config):
try: try:
ControlReferenceTemplate.parse_SE_config(self, config) ControlReferenceTemplate.parse_SE_config(self, config)
except SwError, e: except SwError as e:
structure = unpack(config) structure = unpack(config)
for tlv in structure: for tlv in structure:
tag, length, value = tlv tag, length, value = tlv

View File

@@ -45,7 +45,7 @@ def inttostring(i, length=None):
if length: if length:
l = len(str) l = len(str)
if l > length: if l > length:
raise ValueError, "i too big for the specified stringlength" raise ValueError("i too big for the specified stringlength")
else: else:
str = chr(0)*(length-l) + str str = chr(0)*(length-l) + str
@@ -122,10 +122,10 @@ def parse_status(data):
lifecycle = ord(segment[1+lgth]) lifecycle = ord(segment[1+lgth])
privileges = ord(segment[1+lgth+1]) privileges = ord(segment[1+lgth+1])
print "aid length: %i (%x)" % (lgth, lgth) print("aid length: %i (%x)" % (lgth, lgth))
print "aid: %s" % hexdump(aid, indent = 18, short=True) 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("life cycle state: %x (%s)" % (lifecycle, LIFE_CYCLES.get(lifecycle, "unknown or invalid state")))
print "privileges: %x (%s)\n" % (privileges, parse_privileges(privileges)) print("privileges: %x (%s)\n" % (privileges, parse_privileges(privileges)))
pos = 0 pos = 0
while pos < len(data): while pos < len(data):
@@ -185,7 +185,7 @@ class APDU(object):
if t == str: if t == str:
initbuff[index] = ord(value) initbuff[index] = ord(value)
elif t != int: 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 ) self.parse( initbuff )
@@ -201,7 +201,7 @@ class APDU(object):
elif isinstance(value, list): elif isinstance(value, list):
self._data = "".join([chr(int(e)) for e in value]) self._data = "".join([chr(int(e)) for e in value])
else: 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) self.Lc = len(value)
def _deldata(self): def _deldata(self):
del self._data; self.data = "" del self._data; self.data = ""
@@ -216,7 +216,7 @@ class APDU(object):
elif isinstance(value, str): elif isinstance(value, str):
setattr(self, "_"+name, ord(value)) setattr(self, "_"+name, ord(value))
else: 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): def _format_parts(self, fields):
"utility function to be used in __str__ and __repr__" "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.Le = (apdu[-2]<<8) + apdu[-1]
self.data = apdu[7:-3] self.data = apdu[7:-3]
else: 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) 7 + self.Lc, 7 + self.Lc + 3)
else: # short apdu else: # short apdu
if len(apdu) == 5: # case 2 short apdu if len(apdu) == 5: # case 2 short apdu
@@ -285,8 +285,8 @@ class C_APDU(APDU):
self.data = apdu[5:-1] self.data = apdu[5:-1]
self.Le = apdu[-1] self.Le = apdu[-1]
else: 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,
5 + self.Lc, 5 + self.Lc + 1) 5 + self.Lc, 5 + self.Lc + 1))
CLA = _make_byte_property("CLA"); cla = CLA CLA = _make_byte_property("CLA"); cla = CLA
INS = _make_byte_property("INS"); ins = INS 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 _getsw(self): return chr(self.SW1) + chr(self.SW2)
def _setsw(self, value): def _setsw(self, value):
if len(value) != 2: 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.SW1 = value[0]
self.SW2 = value[1] self.SW2 = value[1]
@@ -385,39 +385,39 @@ if __name__ == "__main__":
c = C_APDU((1, 2, 3), cla = 0x23, data = "hallo") # case 3 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 d = C_APDU(1, 2, 3, 4, 2, 4, 6, 0) # case 4
print print()
print a print(a)
print b print(b)
print c print(c)
print d print(d)
print print()
print repr(a) print(repr(a))
print repr(b) print(repr(b))
print repr(c) print(repr(c))
print repr(d) print(repr(d))
print print()
for i in a, b, c, d: for i in a, b, c, d:
print hexdump(i.render()) print(hexdump(i.render()))
print print()
e = R_APDU(0x90, 0) e = R_APDU(0x90, 0)
f = R_APDU("foo\x67\x00") f = R_APDU("foo\x67\x00")
print print()
print e print(e)
print f print(f)
print print()
print repr(e) print(repr(e))
print repr(f) print(repr(f))
print print()
for i in e, f: 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 g = C_APDU(0x00, 0xb0, 0x9c, 0x00, 0x00, 0x00, 0x00) #case 2 extended length
print print()
print g print(g)
print repr(g) print(repr(g))
print hexdump(g.render()) print(hexdump(g.render()))