blob: 011bd058d41befaca4c1c609216e25dc503edd4e [file] [log] [blame]
Sylvain Munaut76504e02010-12-07 00:24:32 +01001#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4""" pySim: various utilities
5"""
6
7#
8# Copyright (C) 2009-2010 Sylvain Munaut <tnt@246tNt.com>
9#
10# This program is free software: you can redistribute it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation, either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program. If not, see <http://www.gnu.org/licenses/>.
22#
23
24
25def h2b(s):
26 return ''.join([chr((int(x,16)<<4)+int(y,16)) for x,y in zip(s[0::2], s[1::2])])
27
28def b2h(s):
29 return ''.join(['%02x'%ord(x) for x in s])
30
31def h2i(s):
32 return [(int(x,16)<<4)+int(y,16) for x,y in zip(s[0::2], s[1::2])]
33
34def i2h(s):
35 return ''.join(['%02x'%(x) for x in s])
36
37def swap_nibbles(s):
38 return ''.join([x+y for x,y in zip(s[1::2], s[0::2])])
39
40def rpad(s, l, c='f'):
41 return s + c * (l - len(s))
42
43def lpad(s, l, c='f'):
44 return c * (l - len(s)) + s
Alexander Chemeris5e96c3d2013-07-04 17:33:33 +040045
Alexander Chemeris7be92ff2013-07-10 11:18:06 +040046def enc_imsi(imsi):
47 """Converts a string imsi into the value of the EF"""
48 l = (len(imsi) + 1) // 2 # Required bytes
49 oe = len(imsi) & 1 # Odd (1) / Even (0)
50 ei = '%02x' % l + swap_nibbles(lpad('%01x%s' % ((oe<<3)|1, imsi), 16))
51 return ei
52
Alexander Chemeris5e96c3d2013-07-04 17:33:33 +040053def dec_imsi(ef):
54 """Converts an EF value to the imsi string representation"""
55 if len(ef) < 4:
56 return None
57 l = int(ef[0:2]) * 2 # Length of the IMSI string
58 swapped = swap_nibbles(ef[2:])
59 oe = (int(swapped[0])>>3) & 1 # Odd (1) / Even (0)
60 if oe:
61 l = l-1
62 if l+1 > len(swapped):
63 return None
64 imsi = swapped[1:l+2]
65 return imsi
66
67def dec_iccid(ef):
68 return swap_nibbles(ef).strip('f')
Alexander Chemeris7be92ff2013-07-10 11:18:06 +040069
70def enc_iccid(iccid):
71 return swap_nibbles(rpad(iccid, 20))
72
73def enc_plmn(mcc, mnc):
74 """Converts integer MCC/MNC into 6 bytes for EF"""
75 return swap_nibbles(lpad('%d' % mcc, 3) + lpad('%d' % mnc, 3))