Pyscard 实现外部认证功能
1.解决问题:在智能卡开发测试中,需要用到测试工具比如 smarttest 等,利用Python 的pyscard拓展库也不失为一种好的办法,下面通过Python 实现智能卡的外部认证SCP02功能;
*注:其中的send的接口是自己封装的,可以替换成 response,sw1,sw2 = cardservice.connection.transmit(apdu)的形式;
def Scp02(): send([0x00,0xa4,0x04,0x00,0x00]) send([0x00,0xa4,0x04,0x00,0x12]) send([0x80,0x50,0x00,0x00,0x08,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08]) InitializeUpdate = [0x00,0xC0,0x00,0x00,0x1C] InitializeUpdateDate,sw1,sw2 = cardservice.connection.transmit(InitializeUpdate) key='404142434445464748494A4B4C4D4E4F' key = key.decode("hex") iv = '0000000000000000' iv = iv.decode("hex") m=DES3.new(key,DES3.MODE_CBC,iv) num1 = re.sub(r'\s', "", toHexString(InitializeUpdateDate[12:14])) res='0182'+num1+'000000000000000000000000' res1 = res.decode("hex") cipherres = m.encrypt(res1) io=cipherres.encode("hex") iv2 = '0000000000000000' iv2 = iv2.decode("hex") n=DES3.new(cipherres,DES3.MODE_CBC,iv2) num2 = re.sub(r'\s', "", toHexString(InitializeUpdateDate[12:20])) res2 = num2+'01020304050607088000000000000000' resss = res2.decode("hex") cipherres2 = n.encrypt(resss) po = cipherres2.encode("hex") key3='404142434445464748494A4B4C4D4E4F' key3 = key3.decode("hex") iv3 = '0000000000000000' iv3 = iv3.decode("hex") o=DES3.new(key3,DES3.MODE_CBC,iv3) res3='0101'+num1+'000000000000000000000000' res3 = res3.decode("hex") cipherres3 = o.encrypt(res3) iv4 = '0000000000000000' iv4 = iv4.decode("hex") key4 = cipherres3 ert = key4.encode("hex") Mac1key = ert[:16] Mac1key = Mac1key.decode("hex") Mac2key = ert[-16:] Mac2key = Mac2key.decode("hex") Macdata = '8482000010'+po[-16:]+'800000' Macdata1 = Macdata[:16] yxc = Macdata1.decode("hex") Macdata2 = Macdata[-16:] gyf = Macdata2.decode("hex") jui = '0000000000000000' jui = jui.decode("hex") objMac2 = DES.new(Mac1key,DES.MODE_CBC,jui) Macnum2 = objMac2.encrypt(yxc) Macnum2show = Macnum2.encode("hex") objMac3 = DES.new(Mac1key,DES.MODE_CBC,Macnum2) Macnum3 = objMac3.encrypt(gyf) Macnum3show = Macnum3.encode("hex") objMac4 = DES.new(Mac2key,DES.MODE_ECB) Macnum4 = objMac4.decrypt(Macnum3) Macnum4show = Macnum4.encode("hex") objMac5 = DES.new(Mac1key,DES.MODE_ECB) Macnum5 = objMac5.encrypt(Macnum4) Macnum5show = Macnum5.encode("hex") yxczs = '8482000010'+po[-16:]+Macnum5show print len(yxczs) listy = [] jj = 0 for x in range(0,21): niu = '0x'+yxczs[jj:jj+2] liu = eval(niu) listy.append(liu) jj+=2 send(listy)
2. 拓展功能:智能卡的测试可以大量用到Python的pyscard 的库,同时也可以通过py2exe等打包工具发给没有Python环境的测试机进行测试;