Exemple #1
0
def test_ecdh_generate_key_random():

    aliceSecretKey = SigningKey.generate(curve=NIST256p)
    alice = ECDH(curve=NIST256p)
    alice.load_private_key(aliceSecretKey)
    alicePublicKey = alice.get_public_key()

    bobSecretKey = SigningKey.generate(curve=NIST256p)
    bob = ECDH(curve=NIST256p)
    bob.load_private_key(bobSecretKey)
    bobPublicKey = bob.get_public_key()

    aliceSecret = derive_shared_secret_from_key(aliceSecretKey, bobPublicKey)
    print("Alice secret: ", aliceSecret.hex())
    bobSecret = derive_shared_secret_from_key(bobSecretKey, alicePublicKey)
    print("Bob secret: ", bobSecret.hex())

    # Header parameters used in ConcatKDF
    alg = "A256GCM"
    apu = "Alice"
    apv = "Bob"
    keydatalen = 32  # 32 bytes or 256 bit output key length

    # After each side generates the shared secret, it is used to independantly derive a shared encryption key
    aliceKey = concat_kdf(aliceSecret, alg, apu, apv, keydatalen)
    print("Alice key: ", aliceKey.hex())

    bobKey = concat_kdf(bobSecret, alg, apu, apv, keydatalen)
    print("Bob key: ", bobKey.hex())

    assert (aliceKey == bobKey
            ), "Both parties should generate the same key from the same secret"
Exemple #2
0
def public_key_encrypt(public_key, data):
    eph = SigningKey.from_string(DEFAULT_KEY, curve=NIST256p, hashfunc=sha256)
    ec = ECDH(curve=NIST256p, private_key=eph, public_key=public_key)
    key = ec.generate_sharedsecret_bytes()

    cipher = AES.new(key, AES.MODE_CTR, nonce=b'\x00')
    encrypted = cipher.encrypt(data)

    return encrypted
Exemple #3
0
 def _ephemeral(self, data: bytes = None) -> Tuple[bytes, bytes]:
     'Generates or extracts ephemeral keys.'
     if data is None:
         self._check_key()
         key = SigningKey.generate(NIST256p, hashfunc=sha384)
         secret = ECDH(NIST256p, key,
                       self._remoteKey).generate_sharedsecret_bytes()
         return key.get_verifying_key().to_string(), secret
     else:
         key, data = data[:EPHEMERAL_KEY_LENGTH], data[
             EPHEMERAL_KEY_LENGTH:]
         key = VerifyingKey.from_string(key, NIST256p, hashfunc=sha384)
         secret = ECDH(NIST256p, self._privateKey,
                       key).generate_sharedsecret_bytes()
         return secret, data
Exemple #4
0
    def __init__(self, loglevel=logging.WARNING):
        logger.setLevel(loglevel)
        logger.debug("In __init__")
        self.initialized_secure_channel = False
        self.sc_privkey = None
        self.sc_pubkey = None
        self.sc_peer_pubkey = None
        self.sc_IV = None
        self.sc_IVcounter = None
        self.shared_key = None
        self.derived_key = None
        self.mac_key = None

        self.ecdh = ECDH(curve=SECP256k1)
        self.ecdh.generate_private_key()
        self.sc_pubkey = self.ecdh.get_public_key()
        self.sc_pubkey_serialized = self.sc_pubkey.to_string(
            encoding='uncompressed')
def DeriveECDHSecret(privateKey, publicKey):
    """Generate a shared secret from keys in byte format."""

    derive = ECDH(curve=NIST256p)
    derive.load_private_key_bytes(unhexlify(privateKey))
    derive.load_received_public_key_bytes(unhexlify(publicKey))

    secret = derive.generate_sharedsecret_bytes()
    return secret
def DeriveECDHSecretFromKey(privateKey, publicKey):
    """Generate a shared secret from keys in ecdsa.Keys format."""

    derive = ECDH(curve=NIST256p)
    derive.load_private_key(privateKey)
    derive.load_received_public_key(publicKey)

    secret = derive.generate_sharedsecret_bytes()
    return secret
Exemple #7
0
def test_ecdh_derive_shared_secret_random():

    # Generate random keys for the two participating users
    aliceSecretKey = SigningKey.generate(curve=NIST256p)
    alice = ECDH(curve=NIST256p)
    alice.load_private_key(aliceSecretKey)
    alicePublicKey = alice.get_public_key()

    bobSecretKey = SigningKey.generate(curve=NIST256p)
    bob = ECDH(curve=NIST256p)
    bob.load_private_key(bobSecretKey)
    bobPublicKey = bob.get_public_key()

    # Each user derives the same shared secret, independantly, using the other's public key which is exchanged
    aliceSecret = derive_shared_secret_from_key(aliceSecretKey, bobPublicKey)
    print("Alice secret: ", aliceSecret.hex())
    bobSecret = derive_shared_secret_from_key(bobSecretKey, alicePublicKey)
    print("Bob secret: ", bobSecret.hex())

    assert aliceSecret == bobSecret, "Both parties should generate the same secret"
Exemple #8
0
    def __init__(self, cookie):
        self.version = '23.9.2'
        self.app_version = '25.2.2'
        self.cookie = cookie
        self.ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36 115Browser/23.9.2'
        self.content_type = 'application/x-www-form-urlencoded'
        self.header = {
            "User-Agent": self.ua,
            "Content-Type": self.content_type,
            "Cookie": self.cookie
        }
        self.remote_pubkey = '0457A29257CD2320E5D6D143322FA4BB8A3CF9D3CC623EF5EDAC62B7678A89C91A83BA800D6129F522D034C895DD2465243ADDC250953BEEBA'
        self.crc_salt = '^j>WD3Kr?J2gLFjD4W2y@'
        self.private_key = RSA.construct((
            0x8C81424BC166F4918756E9F7B22EFAA03479B081E61896872CB7C51C910D7EC1A4CE2871424D5C9149BD5E08A25959A19AD3C981E6512EFDAB2BB8DA3F1E315C294BD117A9FB9D8CE8E633B4962E087C629DC6CA3A149214B4091EF2B0363CB3AE6C7EE702377F055ED3CD93F6C342256A76554BBEA7F203437BBE65F2DA2741,
            0x10001,
            0x3704DAB00D80C25E464FFB785A16D95F688D0A5823811758C16308D5A1DB55FA800D967A9B4AEDE79AA783ADFFDCDB23541C80B8D436901F172B1CCCA190B224DBE777BF18B96DD9A30AACE8780350793A4F90A645A7747EF695622EADBE23A4C6D88F22E87842B43B35486C2D1B5B1FA77DB3528B0910CA84EDB7A46AFDBED1
        ))
        self.publickey = RSA.construct((
            0xD1DEB5A67989D10A5C0B041D11AB47659BC32B3E65A92F9236DD2CC2140A0DA495FA0E7EF875F6FACB4D981F5E5E3BA5E67811DD73B7A4105254222FACC206A74E8911215451AFFCF5EBFDE887BC9ADB675C02A835F75CBE77A603AF820683F439E7CED4289323DF9C9055769E15798B9453E89058B3E2E3F186B07B046A996D,
            0x10001))
        self.g_key_l = '42da13ba78768d37e8ee0491'.decode('hex')
        self.g_key_s = '2923215e'.decode('hex')
        self.g_kts = 'f0e569aebfdcbf5a1a45e8be7da67388de8fe7c445da86949b69920b6ab8f17a38063c95266d2c560070569c363862762f9b5f0ff2fefd2d709c86448f3d142771938ae40ec148aedc347fcffeb27ff6559a46c8eb3777a4e06b72937e51cbf137efad2adeeef9c9396b32a1ba35b1b8beda7873f820d527045a6ffd5e7239cf3b9c2b575cf97c4b7bd21266cc7709a6'.decode(
            'hex')
        self.curve = NIST224p
        self.m115_l_rnd_key = None
        self.m115_s_rnd_key = None
        self.local_private_key = None
        self.aes_key = None
        self.aes_iv = None
        self.local_public_key = None
        self.user_id = None
        self.user_key = None
        self.std_out_handle = None
        self.filecount = 0
        self.cid = 0

        sk = SigningKey.generate(curve=self.curve)
        ecdh = ECDH(curve=self.curve)
        ecdh.load_private_key(sk)
        local_public_key = ecdh.get_public_key()._compressed_encode()

        self.local_public_key = chr(29) + local_public_key
        ecdh.load_received_public_key_bytes(self.remote_pubkey.decode('hex'))
        secret = ecdh.generate_sharedsecret_bytes()
        self.aes_key = secret[0:16]
        self.aes_iv = secret[-16:]

        if self.get_userkey() is False:
            print('Get userkey info failed!')
Exemple #9
0
def DecryptMessage(privateKey_hex, encrypted_hex):
    if privateKey_hex[:2] == '0x':
        privateKey_hex = privateKey_hex[2:]
    if encrypted_hex[:2] == '0x':
        encrypted_hex = encrypted_hex[2:]

    # get the components
    encrypted = bytearray.fromhex(encrypted_hex)
    iv = encrypted[:16]
    ephemPubKeyEncoded = encrypted[17:81]
    mac = encrypted[81:113]
    ciphertext = encrypted[113:]

    # recover the temporary public key
    ephemPubKey = VerifyingKey.from_string(ephemPubKeyEncoded, curve=SECP256k1)

    # load the private key
    priv_key = SigningKey.from_secret_exponent(int(privateKey_hex, 16),
                                               curve=SECP256k1)
    ecdh = ECDH(curve=SECP256k1, private_key=priv_key)

    # ECDH => get the shared secret
    ecdh.load_received_public_key(ephemPubKey)
    px = ecdh.generate_sharedsecret_bytes()

    # compute the encription and MAC keys
    hash_px = SHA512.new(data=px).digest()
    encryptionKey = hash_px[:32]
    macKey = hash_px[32:]

    # check the MAC
    dataToMac = iv + bytearray([4]) + ephemPubKeyEncoded + ciphertext
    computed_mac = hmac.new(macKey, dataToMac, 'sha256').digest()
    if computed_mac != mac:
        raise ValueError("MAC missmatch")

    #decipher the text
    plaintext = AES256CbcDecrypt(ciphertext.hex(), encryptionKey, iv)
    return plaintext.decode("utf-8")
Exemple #10
0
    def __init__(self, cookie):
        self.version = '23.9.0'
        self.app_version = '25.2.2'
        self.cookie = cookie
        self.ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36 115Browser/23.9.0'
        self.content_type = 'application/x-www-form-urlencoded'
        self.header = {
            "User-Agent": self.ua,
            "Content-Type": self.content_type,
            "Cookie": self.cookie
        }
        self.remote_pubkey = '0457A29257CD2320E5D6D143322FA4BB8A3CF9D3CC623EF5EDAC62B7678A89C91A83BA800D6129F522D034C895DD2465243ADDC250953BEEBA'
        self.crc_salt = '^j>WD3Kr?J2gLFjD4W2y@'
        self.private_key = RSA.construct((
            0x8C81424BC166F4918756E9F7B22EFAA03479B081E61896872CB7C51C910D7EC1A4CE2871424D5C9149BD5E08A25959A19AD3C981E6512EFDAB2BB8DA3F1E315C294BD117A9FB9D8CE8E633B4962E087C629DC6CA3A149214B4091EF2B0363CB3AE6C7EE702377F055ED3CD93F6C342256A76554BBEA7F203437BBE65F2DA2741,
            0x10001,
            0x3704DAB00D80C25E464FFB785A16D95F688D0A5823811758C16308D5A1DB55FA800D967A9B4AEDE79AA783ADFFDCDB23541C80B8D436901F172B1CCCA190B224DBE777BF18B96DD9A30AACE8780350793A4F90A645A7747EF695622EADBE23A4C6D88F22E87842B43B35486C2D1B5B1FA77DB3528B0910CA84EDB7A46AFDBED1
        ))
        self.publickey = RSA.construct((
            0xD1DEB5A67989D10A5C0B041D11AB47659BC32B3E65A92F9236DD2CC2140A0DA495FA0E7EF875F6FACB4D981F5E5E3BA5E67811DD73B7A4105254222FACC206A74E8911215451AFFCF5EBFDE887BC9ADB675C02A835F75CBE77A603AF820683F439E7CED4289323DF9C9055769E15798B9453E89058B3E2E3F186B07B046A996D,
            0x10001))
        self.g_key_l = '\x42\xda\x13\xba\x78\x76\x8d\x37\xe8\xee\x04\x91'
        self.g_key_s = '\x29\x23\x21\x5e'
        self.g_kts = '\xf0\xe5\x69\xae\xbf\xdc\xbf\x5a\x1a\x45\xe8\xbe\x7d\xa6\x73\x88\xde\x8f\xe7\xc4\x45\xda\x86\x94\x9b\x69\x92\x0b\x6a\xb8\xf1\x7a\x38\x06\x3c\x95\x26\x6d\x2c\x56\x00\x70\x56\x9c\x36\x38\x62\x76\x2f\x9b\x5f\x0f\xf2\xfe\xfd\x2d\x70\x9c\x86\x44\x8f\x3d\x14\x27\x71\x93\x8a\xe4\x0e\xc1\x48\xae\xdc\x34\x7f\xcf\xfe\xb2\x7f\xf6\x55\x9a\x46\xc8\xeb\x37\x77\xa4\xe0\x6b\x72\x93\x7e\x51\xcb\xf1\x37\xef\xad\x2a\xde\xee\xf9\xc9\x39\x6b\x32\xa1\xba\x35\xb1\xb8\xbe\xda\x78\x73\xf8\x20\xd5\x27\x04\x5a\x6f\xfd\x5e\x72\x39\xcf\x3b\x9c\x2b\x57\x5c\xf9\x7c\x4b\x7b\xd2\x12\x66\xcc\x77\x09\xa6'
        self.m115_rnd_key = None
        self.curve = NIST224p
        self.local_private_key = None
        self.aes_key = None
        self.aes_iv = None
        self.local_public_key = None
        self.user_id = None
        self.user_key = None
        self.std_out_handle = None
        self.filecount = 0
        self.cid = 0

        sk = SigningKey.generate(curve=self.curve)
        ecdh = ECDH(curve=self.curve)
        ecdh.load_private_key(sk)
        local_public_key = ecdh.get_public_key()._compressed_encode()

        self.local_public_key = chr(29) + local_public_key
        ecdh.load_received_public_key_bytes(self.remote_pubkey.decode('hex'))
        secret = ecdh.generate_sharedsecret_bytes()
        self.aes_key = secret[0:16]
        self.aes_iv = secret[-16:]

        if self.get_userkey() is False:
            print('Get userkey info failed!')
Exemple #11
0
 def ephemeral(self, ephemeral=None):
     'Create or decapsulate a ephemeral key.'
     if not self._remoteKey:
         raise MissingRemoteKey
     if not ephemeral: # request to generate one
         eph_key = ECPrivateKey()
         ecdh = ECDH(NIST256p, eph_key._key, self._remoteKey._key)
         return eph_key.publicKey().exportString(), ecdh.generate_sharedsecret_bytes()
     else: # decapsulate key
         eph_key = ECPublicKey(VerifyingKey.from_string(ephemeral, NIST256p))
         ecdh = ECDH(NIST256p, self._privateKey._key, eph_key._key)
         return ecdh.generate_sharedsecret_bytes()
Exemple #12
0
def EncryptMessage(publicKey_hex, plainText_string):
    if publicKey_hex[:2] == '0x':
        publicKey_hex = publicKey_hex[2:]
    publicKey_bin = bytearray.fromhex(publicKey_hex)

    # Generate the temporary key
    ecdh = ECDH(curve=SECP256k1)
    ecdh.generate_private_key()

    ephemPubKeyEncoded = bytearray.fromhex(
        ecdh.get_public_key().to_string().hex())

    # Load the public key
    publicKey = VerifyingKey.from_string(publicKey_bin, curve=SECP256k1)

    # ECDH => get the shared secret
    ecdh.load_received_public_key(publicKey)

    px = ecdh.generate_sharedsecret_bytes()

    # compute the encription and MAC keys
    hash_px = SHA512.new(data=px).digest()
    encryptionKey = hash_px[:32]
    macKey = hash_px[32:]

    # cipher the plain text
    iv = Random.get_random_bytes(16)
    plaintext = plainText_string.encode(encoding='utf_8')
    ciphertext = AES256CbcEncrypt(plaintext, encryptionKey, iv)

    # compute the MAC
    dataToMac = iv + bytearray([4]) + ephemPubKeyEncoded + ciphertext
    mac = hmac.new(macKey, dataToMac, 'sha256').digest()

    #build the output
    serializedCiphertext = iv + bytearray(
        [4]) + ephemPubKeyEncoded + mac + ciphertext
    return serializedCiphertext.hex()
Exemple #13
0
    def __init__(self, cookie):
        self.version = '23.9.1'
        self.app_version = '25.2.2'
        self.cookie = cookie
        self.ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36 115Browser/23.9.1'
        self.content_type = 'application/x-www-form-urlencoded'
        self.header = {
            "User-Agent": self.ua,
            "Content-Type": self.content_type,
            "Cookie": self.cookie
        }
        self.remote_pubkey = '0457A29257CD2320E5D6D143322FA4BB8A3CF9D3CC623EF5EDAC62B7678A89C91A83BA800D6129F522D034C895DD2465243ADDC250953BEEBA'
        self.crc_salt = '^j>WD3Kr?J2gLFjD4W2y@'
        self.curve = NIST224p
        self.local_private_key = None
        self.aes_key = None
        self.aes_iv = None
        self.local_public_key = None
        self.user_id = None
        self.user_key = None
        self.std_out_handle = None
        self.filecount = 0
        self.cid = 0

        sk = SigningKey.generate(curve=self.curve)
        ecdh = ECDH(curve=self.curve)
        ecdh.load_private_key(sk)
        local_public_key = ecdh.get_public_key()._compressed_encode()

        self.local_public_key = chr(29) + local_public_key
        ecdh.load_received_public_key_bytes(self.remote_pubkey.decode('hex'))
        secret = ecdh.generate_sharedsecret_bytes()
        self.aes_key = secret[0:16]
        self.aes_iv = secret[-16:]

        if self.get_userkey() is False:
            print('Get userkey info failed!')
Exemple #14
0
class BLECDH:
    def __init__(self, curve=NIST256p):
        self.ecdh = ECDH(curve)
        self.local_public_key = None
        self.sharedsecret = ''

    def create_public_key(self):
        self.ecdh.generate_private_key()
        self.local_public_key = self.ecdh.get_public_key()
        ret = binascii.hexlify(
            self.local_public_key.to_string()).decode('utf-8')
        bflb_utils.printf('local public key:')
        bflb_utils.printf(ret)
        return ret

    def create_shared_key(self, peer_pk):
        self.ecdh.load_received_public_key_bytes(binascii.unhexlify(peer_pk))
        self.sharedsecret = self.ecdh.generate_sharedsecret_bytes()
        ret = binascii.hexlify(self.sharedsecret).decode('utf-8')
        bflb_utils.printf('secret key:')
        bflb_utils.printf(ret)
        return ret
Exemple #15
0
 def secret(self) -> bytes:
     'Gets the shared secret.'
     self._check_key()
     return ECDH(NIST256p, self._privateKey,
                 self._remoteKey).generate_sharedsecret_bytes()
Exemple #16
0
from ecdsa import ECDH, NIST256p

ecdh = ECDH(curve=NIST256p)
ecdh.generate_private_key()
local_public_key = ecdh.get_public_key()
#send `local_public_key` to remote party and receive `remote_public_key` from remote party
with open("remote_public_key.pem") as e:
    remote_public_key = e.read()
ecdh.load_received_public_key_pem(remote_public_key)
secret = ecdh.generate_sharedsecret_bytes()
Exemple #17
0
 def secret(self):
     'Gets the shared secret.'
     if not self._remoteKey:
         raise MissingRemoteKey
     ecdh = ECDH(NIST256p, self._privateKey._key, self._remoteKey._key)
     return ecdh.generate_sharedsecret_bytes()
Exemple #18
0
from ecdsa import SigningKey, VerifyingKey, ECDH, SECP256k1

private_key_author = "3a412d173259377650f6e760441163838cdc1286c93f5080b37add3b653d03a4"
public_key_project = "04bcabfebae83aa1ed933e517d0aa313edbc7ad95c9eef253782070bb4759937bf6b97d0dbf37ff3cbf389db8de0eb41d6346c6ad5afc40c651a1fbf7e62da03f9"

private_key_author_hex = bytes.fromhex(private_key_author)
public_key_project_hex = bytes.fromhex(public_key_project)

private_key = SigningKey.from_string(private_key_author_hex, curve=SECP256k1)
public_key = VerifyingKey.from_string(public_key_project_hex, curve=SECP256k1)

ecdh = ECDH(curve=SECP256k1, private_key=private_key, public_key=public_key)
secret = ecdh.generate_sharedsecret_bytes().hex()

print(secret)

# cf7c0ddd238f76c9dc3ff97629c8f23852215d18c67eccb0bf2ba40d271df345
Exemple #19
0
print(f"ECDSA Public key:\n\t" + x.decode("utf-8") + "." + y.decode("utf-8") +
      "\n\t" + data['pub'])

# 3. Check Verification method
x, y = data["pub"].split('.')
vpub = base64.b64decode(base64urldecode(x)) + base64.b64decode(
    base64urldecode(y))
vpub = VerifyingKey.from_string(vpub, curve=NIST256p, hashfunc=sha256)

integrity = sha256(signed['m'].encode('utf-8'))

print(
    f'Verify signature: {vpub.verify(base64.b64decode(signed["s"]), integrity.digest(), hashfunc=sha256)}'
)

# ECDH
epriv = base64urldecode(data["epriv"])
epriv = base64.b64decode(epriv)

# 1. Decode k
ecdh = ECDH(curve=NIST256p)
k = ecdh.load_private_key_bytes(epriv)

# 2. Generate public key
epub = k.to_string()
ex, ey = epub[:32], epub[32:]
ex = base64urlencode(base64.b64encode(ex))
ey = base64urlencode(base64.b64encode(ey))
print(f"ECDSA Public key:\n\t" + ex.decode("utf-8") + "." +
      ey.decode("utf-8") + "\n\t" + data['epub'])
Exemple #20
0
 def __init__(self, curve=NIST256p):
     self.ecdh = ECDH(curve)
     self.local_public_key = None
     self.sharedsecret = ''
Exemple #21
0
class SecureChannel:
    def __init__(self, loglevel=logging.WARNING):
        logger.setLevel(loglevel)
        logger.debug("In __init__")
        self.initialized_secure_channel = False
        self.sc_privkey = None
        self.sc_pubkey = None
        self.sc_peer_pubkey = None
        self.sc_IV = None
        self.sc_IVcounter = None
        self.shared_key = None
        self.derived_key = None
        self.mac_key = None

        self.ecdh = ECDH(curve=SECP256k1)
        self.ecdh.generate_private_key()
        self.sc_pubkey = self.ecdh.get_public_key()
        self.sc_pubkey_serialized = self.sc_pubkey.to_string(
            encoding='uncompressed')

    def initiate_secure_channel(self, peer_pubkey_bytes):
        logger.debug("In initiate_secure_channel()")

        self.sc_IVcounter = 1

        #using ecdsa
        self.sc_peer_pubkey = VerifyingKey.from_string(peer_pubkey_bytes,
                                                       curve=SECP256k1)
        self.ecdh.load_received_public_key(self.sc_peer_pubkey)
        self.shared_key = self.ecdh.generate_sharedsecret_bytes()

        #logger.debug("Shared key:"+ self.shared_key.hex()) #debug

        mac = hmac.new(self.shared_key, "sc_key".encode('utf-8'), sha1)
        self.derived_key = mac.digest()[:16]
        mac = hmac.new(self.shared_key, "sc_mac".encode('utf-8'), sha1)
        self.mac_key = mac.digest()

        # alternative derivation
        # tmp_key= sha256(self.shared_key).digest()
        # self.derived_key = tmp_key[:16]
        # tmp_key= sha256(tmp_key).digest()
        # self.mac_key= tmp_key[:20]

        # logger.debug("Derived_key key:"+ self.derived_key.hex()) #debug
        # logger.debug("Mac_key key:"+ self.mac_key.hex()) #debug

        self.initialized_secure_channel = True

    def encrypt_secure_channel(self, data_bytes):
        logger.debug("In encrypt_secure_channel()")
        if not self.initialized_secure_channel:
            raise UninitializedSecureChannelError(
                'Secure channel is not initialized')

        ## for encryption, the data is padded with PKCS#7 (done by PADDING_DEFAULT)
        # blocksize= 16
        # size=len(apdu)
        # padsize= blocksize - (size%blocksize)
        # apdu= apdu+ [padsize]*padsize

        key = self.derived_key
        iv = urandom(12) + (self.sc_IVcounter).to_bytes(4, byteorder='big')

        aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv)
        aes = pyaes.Encrypter(aes_cbc, padding=pyaes.PADDING_DEFAULT)
        ciphertext = aes.feed(data_bytes) + aes.feed()

        self.sc_IVcounter += 2

        data_to_mac = iv + len(ciphertext).to_bytes(
            2, byteorder='big') + ciphertext
        mac = hmac.new(self.mac_key, data_to_mac, sha1).digest()

        return (iv, ciphertext, mac)

    def decrypt_secure_channel(self, iv, ciphertext):
        logger.debug("In decrypt_secure_channel()")
        if not self.initialized_secure_channel:
            raise UninitializedSecureChannelError(
                'Secure channel is not initialized')

        key = self.derived_key

        aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv)
        aes = pyaes.Decrypter(aes_cbc, padding=pyaes.PADDING_DEFAULT)
        decrypted = aes.feed(ciphertext) + aes.feed()

        # #remove padding (already done with PADDING_DEFAULT)
        # #logger.debug(f'Plaintext with padding: {toHexString(plaintext)}')
        # plaintext= list(plaintext)
        # pad= plaintext[-1]
        # plaintext=plaintext[0:-pad]
        # #logger.debug(f'Plaintext without padding: {toHexString(plaintext)}')

        return list(decrypted)