#!/usr/bin/env python3

# (C) 2023 by Harald Welte <laforge@osmocom.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import unittest
import logging
import base64
from osmocom.utils import b2h, h2b

from pySim.esim.bsp import *
import pySim.esim.rsp as rsp
from pySim.esim import ActivationCode

from cryptography.hazmat.primitives.asymmetric import ec

class TestActivationCode(unittest.TestCase):
    def test_de_encode(self):
        STRS = ['1$SMDP.GSMA.COM$04386-AGYFT-A74Y8-3F815',
                '1$SMDP.GSMA.COM$04386-AGYFT-A74Y8-3F815$$1',
                '1$SMDP.GSMA.COM$04386-AGYFT-A74Y8-3F815$1.3.6.1.4.1.31746$1',
                '1$SMDP.GSMA.COM$04386-AGYFT-A74Y8-3F815$1.3.6.1.4.1.31746',
                '1$SMDP.GSMA.COM$$1.3.6.1.4.1.31746']
        for s in STRS:
            ac = ActivationCode.from_string(s)
            self.assertEqual(s, ac.to_string())


class TestECKA(unittest.TestCase):
    def test_mode51(self):
        curve = ec.SECP256R1()
        euicc_otpk_der = h2b('0400f7b8d71403f21d84b00cd9e561178d737d3f4d065e62fee279271298dd4f074794ab791b9939d4461296efe388aa26731064263af988b7d2c4d77da44801b5')
        smdp_otpk_der = h2b('04a27e2bdbd94dcf67d4c9ae5cb149d9d0f093be7a16dc41ec9db0318e4db72d09234a7d7631979a5d150eec40afe17ce41673df9d2f2e4246d60051c74eba7964')
        smdp_otsk_bytes = h2b('fb68a38ccedb69e15cbe03c256228998ac398587e5dc7117f948145c839d61a4')
        expected_shared_secret = h2b('c9a993dd4879a8f7161f2085410edd4f9652f1df37be097ba96ba2ca6be528fe')

        euicc_otpk = ec.EllipticCurvePublicKey.from_encoded_point(curve, bytes(euicc_otpk_der))
        smdp_otpk = ec.EllipticCurvePublicKey.from_encoded_point(curve, bytes(smdp_otpk_der))
        smdp_otsk = ec.derive_private_key(int.from_bytes(smdp_otsk_bytes, 'big'), curve)

        shared_secret = smdp_otsk.exchange(ec.ECDH(), euicc_otpk)

        self.assertEqual(shared_secret, expected_shared_secret)


class TestBSPdecode(unittest.TestCase):
    bpp_b64 = "[encoded data, 17240 characters]"



if __name__ == "__main__":
	unittest.main()
