SimlockInsKey.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/env python
  2. from struct import pack, unpack
  3. import subprocess,os,sys,struct,array
  4. from Crypto.PublicKey import RSA
  5. from Crypto.Util.number import long_to_bytes
  6. #cpath=os.getcwd()
  7. #cpath="/home/hesheng.lv/projects/8850/Bin/InsertSimlocKey/"
  8. KeyType='RSA2048'
  9. MagicNum='SIMLOCK_MAGIC_S'
  10. KeyUpDir = "/SimlocKeys/"
  11. KeyIDTable = [0x1011, 0x1012, 0x1013, 0x1014, 0x1015]
  12. KeysDirs = ["authstartkey", "authendkey", "simlockey", "imeikey", "reskey"]
  13. def GetKeyFiles(fdir):
  14. kf = ""
  15. fls=os.listdir(fdir)
  16. j = 0
  17. for i in fls:
  18. if os.path.splitext(i)[1] == ".pem":
  19. #print "Find key: " + i
  20. if kf == "":
  21. kf = i
  22. j = j + 1
  23. if j > 1:
  24. kf = ""
  25. return j, kf
  26. def get_head_offset(tos_img,tos_len):
  27. secpos = tos_img.find(MagicNum)
  28. if secpos < 0:
  29. print ("there is no head!!!")
  30. return 0
  31. else:
  32. print ("Find magic num: " + MagicNum)
  33. return secpos
  34. def InsertKey(kpath,kid,img):
  35. f = open(kpath, 'rb')
  36. if f < 0:
  37. print ("Can\'t find key: \""+kpath+"\"")
  38. return 0
  39. else:
  40. k = RSA.importKey(f.read())
  41. f.close
  42. Mlen = (k.publickey().size()+7)/8
  43. Nlen = len(long_to_bytes(k.publickey().n))
  44. Elen = len(long_to_bytes(k.publickey().e))
  45. img.write('%s' % struct.pack("<I", kid))
  46. img.write('%s' % struct.pack("<I", Mlen))
  47. img.write(KeyType)
  48. img.seek(1,1)
  49. img.write('%s' % struct.pack("<I", Nlen))
  50. for x in array.array("B", long_to_bytes(k.publickey().n)):
  51. data_n = struct.pack("<B",x)
  52. img.write(data_n)
  53. img.seek(512-Nlen, 1)
  54. img.write('%s' % struct.pack("<I", Elen))
  55. for x in array.array("B", long_to_bytes(k.publickey().e)):
  56. data_e = struct.pack("<B",x)
  57. img.write(data_e)
  58. img.seek(512-Elen, 1)
  59. #print ("Insert key["+hex(kid)+"]:\""+os.path.basename(kpath)+"\" success")
  60. return 1
  61. def main():
  62. filename = sys.argv[1]
  63. cpath = sys.argv[2]
  64. #print(sys.argv)
  65. if os.path.exists(filename):
  66. f1 = open(filename,'rb+')
  67. bindata = f1.read()
  68. bin_len = len(bindata)
  69. offset = get_head_offset(bindata,bin_len)
  70. if offset == 0:
  71. print ("Can\'t find head magic num")
  72. else:
  73. print ("Magic Offset is " + bytes(offset))
  74. f1.seek(offset+16,0)
  75. for n in range(0,5):
  76. knum, kfile = GetKeyFiles(cpath+KeyUpDir+KeysDirs[n])
  77. if knum == 1:
  78. InsertKey(cpath+KeyUpDir+KeysDirs[n]+"/"+kfile, KeyIDTable[n], f1)
  79. print ("Insert simlock key success")
  80. f1.close
  81. else:
  82. print ("Cp bin is not accessible!!!")
  83. if __name__ == "__main__":
  84. main()