コード例 #1
0
ファイル: test_CMAC.py プロジェクト: Legrandin/pycryptodome
    def runTest(self):

        key = b"0" * 16
        data = b"\x00\x01\x02"

        def get_mv_ro(data):
            return memoryview(data)

        def get_mv_rw(data):
            return memoryview(bytearray(data))

        for get_mv in (get_mv_ro, get_mv_rw):

            # Data and key can be a memoryview (during initialization)
            key_mv = get_mv(key)
            data_mv = get_mv(data)

            h1 = CMAC.new(key, data, ciphermod=AES)
            h2 = CMAC.new(key_mv, data_mv, ciphermod=AES)
            if not data_mv.readonly:
                key_mv[:1] = b'\xFF'
                data_mv[:1] = b'\xFF'
            self.assertEqual(h1.digest(), h2.digest())

            # Data can be a memoryview (during operation)
            data_mv = get_mv(data)

            h1 = CMAC.new(key, ciphermod=AES)
            h2 = CMAC.new(key, ciphermod=AES)
            h1.update(data)
            h2.update(data_mv)
            if not data_mv.readonly:
                data_mv[:1] = b'\xFF'
            self.assertEqual(h1.digest(), h2.digest())
コード例 #2
0
ファイル: test_CMAC.py プロジェクト: Legrandin/pycryptodome
    def runTest(self):

        key = b"0" * 16
        data = b"\x00\x01\x02"

        # Data and key can be a bytearray (during initialization)
        key_ba = bytearray(key)
        data_ba = bytearray(data)

        h1 = CMAC.new(key, data, ciphermod=AES)
        h2 = CMAC.new(key_ba, data_ba, ciphermod=AES)
        key_ba[:1] = b'\xFF'
        data_ba[:1] = b'\xFF'
        self.assertEqual(h1.digest(), h2.digest())

        # Data can be a bytearray (during operation)
        key_ba = bytearray(key)
        data_ba = bytearray(data)

        h1 = CMAC.new(key, ciphermod=AES)
        h2 = CMAC.new(key, ciphermod=AES)
        h1.update(data)
        h2.update(data_ba)
        data_ba[:1] = b'\xFF'
        self.assertEqual(h1.digest(), h2.digest())
コード例 #3
0
ファイル: test_CMAC.py プロジェクト: dongweigogo/pycryptodome
    def runTest(self):

        data_to_mac = get_tag_random("data_to_mac", 128)
        key = get_tag_random("key", 16)
        ref_mac = CMAC.new(key, msg=data_to_mac, ciphermod=AES).digest()

        # Break up in chunks of different length
        # The result must always be the same
        for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:

            chunks = [data_to_mac[i : i + chunk_length] for i in range(0, len(data_to_mac), chunk_length)]

            mac = CMAC.new(key, ciphermod=AES)
            for chunk in chunks:
                mac.update(chunk)
            self.assertEqual(ref_mac, mac.digest())
コード例 #4
0
ファイル: blockalgo.py プロジェクト: Legrandin/pycrypto
    def _start_eax(self, factory, key, *args, **kwargs):

        self.nonce = _getParameter('nonce', 1, args, kwargs)
        if not self.nonce:
            raise TypeError("MODE_EAX requires a nonce")

        # Allowed transitions after initialization
        self._next = [self.update, self.encrypt, self.decrypt,
                      self.digest, self.verify]

        self._mac_len = kwargs.get('mac_len', self.block_size)
        if not (self._mac_len and 4 <= self._mac_len <= self.block_size):
            raise ValueError("Parameter 'mac_len' must not be larger than %d"
                             % self.block_size)

        self._omac = [
                CMAC.new(key, bchr(0) * (self.block_size - 1) + bchr(i),
                         ciphermod=factory)
                for i in xrange(0, 3)
                ]

        # Compute MAC of nonce
        self._omac[0].update(self.nonce)

        self._cipherMAC = self._omac[1]

        # MAC of the nonce is also the initial counter for CTR encryption
        counter_int = bytes_to_long(self._omac[0].digest())
        counter_obj = Crypto.Util.Counter.new(
                        self.block_size * 8,
                        initial_value=counter_int,
                        allow_wraparound=True)
        self._cipher = factory.new(key, MODE_CTR, counter=counter_obj)
コード例 #5
0
ファイル: KDF.py プロジェクト: shubhanus/taiga
    def update(self, item):
        """Pass the next component of the vector.

        The maximum number of components you can pass is equal to the block
        length of the cipher (in bits) minus 1.

        :Parameters:
          item : byte string
            The next component of the vector.
        :Raise TypeError: when the limit on the number of components has been reached.
        :Raise ValueError: when the component is empty
        """

        if not item:
            raise ValueError("A component cannot be empty")

        if self._n_updates==0:
            raise TypeError("Too many components passed to S2V")
        self._n_updates -= 1

        mac = CMAC.new(self._key,
                       msg=self._last_string,
                       ciphermod=self._ciphermod,
                       cipher_params=self._cipher_params)
        self._cache = strxor(self._double(self._cache), mac.digest())
        self._last_string = item
コード例 #6
0
ファイル: test_CMAC.py プロジェクト: Legrandin/pycryptodome
    def test_update_after_digest(self):
        msg = b"rrrrttt"
        key = b"4" * 16

        # Normally, update() cannot be done after digest()
        h = CMAC.new(key, msg[:4], ciphermod=AES)
        dig1 = h.digest()
        self.assertRaises(TypeError, h.update, msg[4:])
        dig2 = CMAC.new(key, msg, ciphermod=AES).digest()

        # With the proper flag, it is allowed
        h2 = CMAC.new(key, msg[:4], ciphermod=AES, update_after_digest=True)
        self.assertEquals(h2.digest(), dig1)
        # ... and the subsequent digest applies to the entire message
        # up to that point
        h2.update(msg[4:])
        self.assertEquals(h2.digest(), dig2)
コード例 #7
0
ファイル: test_CMAC.py プロジェクト: Legrandin/pycryptodome
    def test_internal_caching(self):
        """Verify that internal caching is implemented correctly"""

        data_to_mac = get_tag_random("data_to_mac", 128)
        key = get_tag_random("key", 16)
        ref_mac = CMAC.new(key, msg=data_to_mac, ciphermod=AES).digest()

        # Break up in chunks of different length
        # The result must always be the same
        for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128:

            chunks = [data_to_mac[i:i+chunk_length] for i in
                      range(0, len(data_to_mac), chunk_length)]

            mac = CMAC.new(key, ciphermod=AES)
            for chunk in chunks:
                mac.update(chunk)
            self.assertEqual(ref_mac, mac.digest())
コード例 #8
0
ファイル: kdf.py プロジェクト: webiumsk/WOT-0.9.12-CT
 def derive(self):
     """"Derive a secret from the vector of components.
     
     :Return: a byte string, as long as the block length of the cipher.
     """
     if len(self._last_string) >= 16:
         final = self._last_string[:-16] + strxor(self._last_string[-16:], self._cache)
     else:
         padded = (self._last_string + bchr(128) + bchr(0) * 15)[:16]
         final = strxor(padded, self._double(self._cache))
     mac = CMAC.new(self._key, msg=final, ciphermod=self._ciphermod)
     return mac.digest()
コード例 #9
0
ファイル: test_CMAC.py プロジェクト: Legrandin/pycryptodome
 def test_create_mac(self, tv):
     self._id = "Wycheproof MAC creation Test #" + str(tv.id)
     
     try:
         tag = CMAC.new(tv.key, tv.msg, ciphermod=AES, mac_len=tv.tag_size).digest()
     except ValueError as e:
         if len(tv.key) not in (16, 24, 32) and "key length" in str(e):
             return
         raise e
     if tv.valid:
         self.assertEqual(tag, tv.tag)
         self.warn(tv)
コード例 #10
0
ファイル: phy_parser.py プロジェクト: houluy/lora-tester
 def cal_mic(key, typ='normal', **kwargs):
     if typ == 'normal':
         msg = '{MHDR}{FHDR}{FPort}{FRMPayload}'.format(**kwargs)
         msg_bytes = bytearray.fromhex(msg)
         msg_length = '{:0>2x}'.format(len(msg_bytes))
         B0 = DeviceOp._B0(msg_length=msg_length, **kwargs)
         obj_msg = B0 + msg
         obj_msg = bytearray.fromhex(obj_msg)
     else:
         msg = '{MHDR}{AppEUI}{DevEUI}{DevNonce}'.format(**kwargs)
         obj_msg = bytearray.fromhex(msg)
     cobj = CMAC.new(key, ciphermod=AES)
     cobj.update(obj_msg)
     return cobj.hexdigest()[:8]
コード例 #11
0
    def runTest(self):
        key = b"0" * 16
        data = b"\x00\x01\x02"

        # Data and key can be a bytearray (during initialization)
        key_ba = bytearray(key)
        data_ba = bytearray(data)

        h1 = CMAC.new(key, data, ciphermod=AES)
        h2 = CMAC.new(key_ba, data_ba, ciphermod=AES)
        key_ba[:1] = b'\xFF'
        data_ba[:1] = b'\xFF'
        self.assertEqual(h1.digest(), h2.digest())

        # Data can be a bytearray (during operation)
        key_ba = bytearray(key)
        data_ba = bytearray(data)

        h1 = CMAC.new(key, ciphermod=AES)
        h2 = CMAC.new(key, ciphermod=AES)
        h1.update(data)
        h2.update(data_ba)
        data_ba[:1] = b'\xFF'
        self.assertEqual(h1.digest(), h2.digest())
コード例 #12
0
ファイル: scratchpadinfo.py プロジェクト: wirepas/wm-sdk
    def _test_key(cmac, icb, data, auth_key):
        '''Try to authenticate ICB, file headers and file data with a key.'''

        # CMAC.new() only accepts bytes, not bytearray.
        auth_key = bytes(auth_key)

        # Create a CMAC / OMAC1 object.
        cobj = CMAC.new(auth_key, ciphermod=AES)

        # Calculate CMAC / OMAC1 over ICB, file headers and file data.
        cobj.update(icb)
        cobj.update(data)

        # Succeeded?
        return cmac == cobj.digest()
コード例 #13
0
def getPHY_CMAC(key, hexpkt, direction=1):
    """
        Compute MIC with AES CMAC
            In(1): String 128 bits key for CMAC
            In(2): hexstring of the packet
            In(3): Direction (1: network, 0: end device)
            Out: Hexdigest of computed MIC
    """
    lowoff = -4
    if direction == 0:
        lowoff = -6  # skip the CRC
    payload = hexpkt[3:lowoff]
    cobj = CMAC.new(key, ciphermod=AES)
    toret = cobj.update(payload).hexdigest()
    return toret[:8]
コード例 #14
0
def CSEC_GenerateBootMAC(Key, BootMsg, BootSize):
    #96bits"0" + 32bits "bootsize" + BootMsg
    if BootSize % 4 != 0:
        return "Input length error !,Must be 4 bytes aligned !\n"
    Msg = ""
    #Little endian mode to big endian mode
    for i in range(0, len(BootMsg), 8):
        Msg = Msg + BootMsg[i + 6:i +
                            8] + BootMsg[i + 4:i +
                                         6] + BootMsg[i + 2:i +
                                                      4] + BootMsg[i:i + 2]
    tmp = "0" * 24 + "{:0>8x}".format(BootSize * 8) + Msg
    KeyBin = binascii.unhexlify(Key)
    MsgBin = binascii.unhexlify(tmp)
    Cipher = CMAC.new(KeyBin, MsgBin, ciphermod=AES)
    return Cipher.hexdigest().upper()
コード例 #15
0
ファイル: test_CMAC.py プロジェクト: 1dividedby0/ThermaApp
 def test_verify_mac(self, tv):
     self._id = "Wycheproof MAC verification Test #" + str(tv.id)
    
     try:
         mac = CMAC.new(tv.key, tv.msg, ciphermod=AES, mac_len=tv.tag_size)
     except ValueError as e:
         if len(tv.key) not in (16, 24, 32) and "key length" in str(e):
             return
         raise e
     try:
         mac.verify(tv.tag)
     except ValueError:
         assert not tv.valid
     else:
         assert tv.valid
         self.warn(tv)
コード例 #16
0
def calculate_cmac(data_list, auth_key):
    '''Calculate CMAC / OMAC1 tag for data.'''

    # CMAC.new() only accepts bytes, not bytearray.
    auth_key = bytes(auth_key)

    # Create a CMAC / OMAC1 object.
    cobj = CMAC.new(auth_key, ciphermod=AES)

    for data in data_list:
        # OPTIMIZE: Avoid extra conversions between bytearrays and bytes.
        # CMAC object does not accept bytearrays, so convert to bytes.
        cobj.update(bytes(data))

    # Calculate digest and return it as bytearray.
    return bytearray(cobj.digest())
コード例 #17
0
    def derive(self):
        """"Derive a secret from the vector of components.

        :Return: a byte string, as long as the block length of the cipher.
        """

        if len(self._last_string)>=16:
            final = self._last_string[:-16] + strxor(self._last_string[-16:], self._cache)
        else:
            padded = (self._last_string + bchr(0x80)+ bchr(0)*15)[:16]
            final = strxor(padded, self._double(self._cache))
        mac = CMAC.new(self._key,
                       msg=final,
                       ciphermod=self._ciphermod,
                       cipher_params=self._cipher_params)
        return mac.digest()
コード例 #18
0
ファイル: _mode_eax.py プロジェクト: erics8/wwqLyParse
    def __init__(self, factory, key, nonce, mac_len, cipher_params):
        """EAX cipher mode"""

        self.block_size = factory.block_size
        """The block size of the underlying cipher, in bytes."""

        self.nonce = nonce
        """The nonce originally used to create the object."""

        self._mac_len = mac_len
        self._mac_tag = None  # Cache for MAC tag

        # Allowed transitions after initialization
        self._next = [self.update, self.encrypt, self.decrypt,
                      self.digest, self.verify]

        # MAC tag length
        if not (4 <= self._mac_len <= self.block_size):
            raise ValueError("Parameter 'mac_len' must not be larger than %d"
                             % self.block_size)

        # Nonce cannot be empty and must be a byte string
        if len(nonce) == 0:
            raise ValueError("Nonce cannot be empty in EAX mode")
        if not byte_string(nonce):
            raise TypeError("Nonce must be a byte string")

        self._omac = [
                CMAC.new(key,
                         bchr(0) * (self.block_size - 1) + bchr(i),
                         ciphermod=factory,
                         cipher_params=cipher_params)
                for i in range(0, 3)
                ]

        # Compute MAC of nonce
        self._omac[0].update(nonce)
        self._signer = self._omac[1]

        # MAC of the nonce is also the initial counter for CTR encryption
        counter_int = bytes_to_long(self._omac[0].digest())
        self._cipher = factory.new(key,
                                   factory.MODE_CTR,
                                   initial_value=counter_int,
                                   nonce=b(""),
                                   **cipher_params)
コード例 #19
0
ファイル: sm.py プロジェクト: PFigs/backend-client
    def _encrypt_packet(self, uid, iv, plain_text):
        enc_key = self.data[uid]["factory_key"][16:32]
        auth_key = self.data[uid]["factory_key"][0:16]

        self.logger.info("  - Encrypt DATA packet")
        # Increment counter
        self.counter += 1
        self.logger.debug("   -  IV: %s",
                          "".join("{:02X}".format(x) + " " for x in iv))
        self.logger.debug("   - Counter : %s", str(self.counter))

        # Authenticate Header + Payload
        to_auth = ProvisioningMessageDATA(self.sm_id[1], self.sm_id[2],
                                          self.counter, plain_text).payload

        # Create a CMAC / OMAC1 object.
        cobj = CMAC.new(auth_key, ciphermod=AES)
        cobj.update(to_auth)

        # MIC is 5 first bytes
        mic = cobj.digest()[0:5]

        # Encrypt payload + mic
        # Generate Initial Counter Block (ICB).
        icb = iv
        ctr_bytes = self.counter + int.from_bytes(
            icb[-2:], byteorder="little", signed=False)
        ctr_bytes = ctr_bytes % 65536
        icb = b"".join([icb[:-2], ctr_bytes.to_bytes(2, byteorder="little")])

        self.logger.debug("   -  ICB: %s",
                          "".join("{:02X}".format(x) + " " for x in icb))

        # Create an AES Counter (CTR) mode cipher using ICB.
        ctr = Counter.new(
            128,
            little_endian=True,
            allow_wraparound=True,
            initial_value=int.from_bytes(icb, byteorder="little",
                                         signed=False),
        )
        cipher = AES.new(enc_key, AES.MODE_CTR, counter=ctr)
        plain_text += mic
        plain_text = bytes(cipher.encrypt(plain_text))

        return plain_text
コード例 #20
0
ファイル: _mode_eax.py プロジェクト: JoanAzpeitia/lp_sg
    def __init__(self, factory, key, nonce, mac_len, cipher_params):
        """EAX cipher mode"""

        self.block_size = factory.block_size
        """The block size of the underlying cipher, in bytes."""

        self.nonce = nonce
        """The nonce originally used to create the object."""

        self._mac_len = mac_len
        self._mac_tag = None  # Cache for MAC tag

        # Allowed transitions after initialization
        self._next = [
            self.update, self.encrypt, self.decrypt, self.digest, self.verify
        ]

        # MAC tag length
        if not (4 <= self._mac_len <= self.block_size):
            raise ValueError("Parameter 'mac_len' must not be larger than %d" %
                             self.block_size)

        # Nonce cannot be empty and must be a byte string
        if len(nonce) == 0:
            raise ValueError("Nonce cannot be empty in EAX mode")
        if not byte_string(nonce):
            raise TypeError("Nonce must be a byte string")

        self._omac = [
            CMAC.new(key,
                     bchr(0) * (self.block_size - 1) + bchr(i),
                     ciphermod=factory,
                     cipher_params=cipher_params) for i in xrange(0, 3)
        ]

        # Compute MAC of nonce
        self._omac[0].update(nonce)
        self._signer = self._omac[1]

        # MAC of the nonce is also the initial counter for CTR encryption
        counter_int = bytes_to_long(self._omac[0].digest())
        self._cipher = factory.new(key,
                                   factory.MODE_CTR,
                                   initial_value=counter_int,
                                   nonce=b(""),
                                   **cipher_params)
コード例 #21
0
ファイル: sept_sign.py プロジェクト: zeroxdevil/Atmosphere
def sign_encrypt_code(code, sig_key, enc_key, iv, desired_mac):
    # Pad with 0x20 of zeroes.
    code += '\x00' * 0x20
    code_len = len(code)
    code_len += 0xFFF
    code_len &= ~0xFFF
    code += '\x00' * (code_len - len(code))

    # Add empty trustzone, warmboot segments.
    code += '\x00' * (0x1FE0 - 0x10)
    pk11_hdr = 'PK11' + pk('<IIIIIII', 0x1000, 0, 0, code_len - 0x20, 0,
                           0x1000, 0)
    pk11 = pk11_hdr + code
    enc_pk11 = AES.new(enc_key, AES.MODE_CBC, iv).encrypt(pk11)
    enc_pk11 = pk('<IIII', len(pk11) + 0x10, 0, 0, 0) + iv + enc_pk11
    enc_pk11 += get_last_block_for_desired_mac(sig_key, enc_pk11, desired_mac)
    enc_pk11 += CMAC.new(sig_key, enc_pk11, AES).digest()
    return enc_pk11
コード例 #22
0
 def _start_eax(self, factory, key, *args, **kwargs):
     self.nonce = _getParameter('nonce', 1, args, kwargs)
     if not self.nonce:
         raise TypeError('MODE_EAX requires a nonce')
     self._next = [self.update,
      self.encrypt,
      self.decrypt,
      self.digest,
      self.verify]
     self._mac_len = kwargs.get('mac_len', self.block_size)
     if not (self._mac_len and 4 <= self._mac_len <= self.block_size):
         raise ValueError("Parameter 'mac_len' must not be larger than %d" % self.block_size)
     self._omac = [ CMAC.new(key, bchr(0) * (self.block_size - 1) + bchr(i), ciphermod=factory) for i in xrange(0, 3) ]
     self._omac[0].update(self.nonce)
     self._cipherMAC = self._omac[1]
     counter_int = bytes_to_long(self._omac[0].digest())
     counter_obj = Crypto.Util.Counter.new(self.block_size * 8, initial_value=counter_int, allow_wraparound=True)
     self._cipher = factory.new(key, MODE_CTR, counter=counter_obj)
コード例 #23
0
    def derive(self):
        """"Derive a secret from the vector of components.

        :Return: a byte string, as long as the block length of the cipher.
        """

        if len(self._last_string) >= 16:
            # xorend
            final = self._last_string[:-16] + strxor(self._last_string[-16:], self._cache)
        else:
            # zero-pad & xor
            padded = (self._last_string + b'\x80' + b'\x00' * 15)[:16]
            final = strxor(padded, self._double(self._cache))
        mac = CMAC.new(self._key,
                       msg=final,
                       ciphermod=self._ciphermod,
                       cipher_params=self._cipher_params)
        return mac.digest()
コード例 #24
0
ファイル: sept_sign.py プロジェクト: xXoof69420Xx/Atmosphere
def sign_encrypt_code(code, sig_key, enc_key, iv, desired_mac, version):
    # Pad with 0x20 of zeroes.
    code = code + bytearray(0x20)
    code_len = len(code)
    code_len += 0xFFF
    code_len &= ~0xFFF
    code = code + bytearray(code_len - len(code))

    # Insert version
    code = code[:8] + pk('<I', version) + code[12:]

    # Add empty trustzone, warmboot segments.
    code = code + bytearray(0x1FE0 - 0x10)
    pk11_hdr = b'PK11' + pk('<IIIIIII', 0x1000, 0, 0, code_len - 0x20, 0, 0x1000, 0)
    pk11 = pk11_hdr + code
    enc_pk11 = AES.new(enc_key, AES.MODE_CBC, iv).encrypt(pk11)
    enc_pk11 = pk('<IIII', len(pk11) + 0x10, 0, 0, 0) + iv + enc_pk11
    enc_pk11 = enc_pk11 + get_last_block_for_desired_mac(sig_key, enc_pk11, desired_mac)
    enc_pk11 = enc_pk11 + CMAC.new(sig_key, enc_pk11, AES).digest()
    return enc_pk11
コード例 #25
0
ファイル: wvclient.py プロジェクト: tarhan/WVClient3
    def getContentKey(self, license_request_data: bytes,
                      license_response_data: bytes):
        licenseMessage = license_protocol_pb2.License()
        requestMessage = license_protocol_pb2.SignedMessage()
        responseMessage = license_protocol_pb2.SignedMessage()
        requestMessage.ParseFromString(license_request_data)
        responseMessage.ParseFromString(license_response_data)

        oaep_key = RSA.importKey(self.private_key)
        cipher = PKCS1_OAEP.new(oaep_key)
        cmac_key = cipher.decrypt(responseMessage.session_key)

        _cipher = CMAC.new(cmac_key, ciphermod=AES)
        _auth_key = b'\x01ENCRYPTION\x00' + requestMessage.msg + b"\x00\x00\x00\x80"
        enc_cmac_key = _cipher.update(_auth_key).digest()

        licenseMessage.ParseFromString(responseMessage.msg)
        for key in licenseMessage.key:
            cryptos = AES.new(enc_cmac_key, AES.MODE_CBC, iv=key.iv[0:16])
            dkey = cryptos.decrypt(key.key[0:16])
            print("KID:", binascii.b2a_hex(key.id), "KEY:",
                  binascii.b2a_hex(dkey))
コード例 #26
0
def encrypt_btl(data: bytes, *args, **kwargs) -> bytes:
    assert (isinstance(data, bytes))

    assert (len(data) == 0x1bfd0)
    stream: io.BytesIO = io.BytesIO(data)

    decrypted: bytes = stream.read(0x1bfd0)

    seed: bytes = get_random_bytes(0x10)

    context: tuple = struct.unpack_from('<IIII', seed)
    random: Random = Random(*context)

    key: bytes = crypto.create_key(random, keytables.btl, 0x10)
    aes: _mode_cbc.CbcMode = AES.new(key, AES.MODE_CBC, get_random_bytes(0x10))
    encrypted: bytes = aes.encrypt(decrypted)

    key: bytes = crypto.create_key(random, keytables.btl, 0x10)
    mac: CMAC.CMAC = CMAC.new(key, ciphermod=AES)
    mac.update(decrypted)

    return encrypted + aes.iv + seed + mac.digest()
コード例 #27
0
ファイル: protocolkdf.py プロジェクト: kusaku/wot_scripts
 def update(self, item):
     """Pass the next component of the vector.
     
     The maximum number of components you can pass is equal to the block
     length of the cipher (in bits) minus 1.
     
     :Parameters:
       item : byte string
         The next component of the vector.
     :Raise TypeError: when the limit on the number of components has been reached.
     :Raise ValueError: when the component is empty
     """
     if not item:
         raise ValueError('A component cannot be empty')
     if self._n_updates == 0:
         raise TypeError('Too many components passed to S2V')
     self._n_updates -= 1
     mac = CMAC.new(self._key,
                    msg=self._last_string,
                    ciphermod=self._ciphermod)
     self._cache = strxor(self._double(self._cache), mac.digest())
     self._last_string = item
コード例 #28
0
ファイル: KDF.py プロジェクト: 37976120/37976120.github.io
    def update(self, item):
        """Pass the next component of the vector.

        The maximum number of components you can pass is equal to the block
        length of the cipher (in bits) minus 1.

        :Parameters:
          item : byte string
            The next component of the vector.
        :Raise TypeError: when the limit on the number of components has been reached.
        """

        if self._n_updates == 0:
            raise TypeError("Too many components passed to S2V")
        self._n_updates -= 1

        mac = CMAC.new(self._key,
                       msg=self._last_string,
                       ciphermod=self._ciphermod,
                       cipher_params=self._cipher_params)
        self._cache = strxor(self._double(self._cache), mac.digest())
        self._last_string = _copy_bytes(None, None, item)
コード例 #29
0
ファイル: main.py プロジェクト: jnbarnesUdel/Applied-Crypto
def EtM(ptxt, key1, key2, nonce):
    counter = 0
    temp2 = 0
    NonceCount = nonce ^ counter
    ctxt = 0
    E = SimonCipher(key1, key_size=256, block_size=128)
    mac = CMAC.new(key=key2.encode(), ciphermod=AES)  #Mac block
    block = breakup(ptxt, 16)

    for i in range(len(block)):
        NonceCount = nonce ^ counter
        counter = counter + 1
        temp = E.encrypt(NonceCount)
        for a in block[
                i]:  #shift temp2 by 1 byte each time and or it with a new byte
            temp2 = (temp2 << 8) | ord(a)
        ctxt = (ctxt << 128) | (temp ^ temp2)  # accumulate onto the ctxt
        temp2 = 0
    T = mac.update(str(ctxt).encode()).hexdigest()
    print("CTXT: ")
    print(hex(ctxt))
    print("T: ")
    print(T)
コード例 #30
0
 def cal_mic(key, typ='normal', **kwargs):
     if typ == 'normal':
         # pdb.set_trace()
         msg = '{MHDR}{FHDR}{FPort}{FRMPayload}'.format(**kwargs)
         print(msg)
         print(len(msg))
         msg_bytes = bytearray.fromhex(msg)
         msg_length = '{:0>2x}'.format(len(msg_bytes) % 0xFF)
         B0 = DeviceOp._B0(msg_length=msg_length, **kwargs)
         obj_msg = B0 + msg
         print(obj_msg)
         print(len(obj_msg))
         obj_msg = bytearray.fromhex(obj_msg)
     elif typ == 'join':
         msg = '{MHDR}{AppEUI}{DevEUI}{DevNonce}'.format(**kwargs)
         obj_msg = bytearray.fromhex(msg)
     else:
         msg = '{MHDR}{AppNonce}{NetID}{DevAddr}\
             {DLSettings}{RxDelay}{CFList}'.format(**kwargs)
         obj_msg = bytearray.fromhex(msg)
     cobj = CMAC.new(key, ciphermod=AES)
     cobj.update(obj_msg)
     return cobj.hexdigest()[:8]
コード例 #31
0
def decrypt_bcd(data: bytes, *args, **kwargs) -> bytes:
    assert (isinstance(data, bytes))

    assert (len(data) == 0x5c000)
    stream: io.BytesIO = io.BytesIO(data)

    header: io.BytesIO = io.BytesIO(stream.read(0x10))
    encrypted: bytes = stream.read(0x5bfc0)
    footer: io.BytesIO = io.BytesIO(stream.read(0x30))

    header.seek(header.tell() + 0x4)
    filetype: int = struct.unpack('<H', header.read(0x2))[0]
    header.seek(header.tell() + 0x2)
    crc32: int = struct.unpack('<I', header.read(0x4))[0]
    magic: str = header.read(0x4).decode('utf-8')
    assert (filetype == 0x10 and magic == 'SCDL')

    iv: bytes = footer.read(0x10)
    seed: bytes = footer.read(0x10)
    cmac: bytes = footer.read(0x10)

    context: tuple = struct.unpack_from('<IIII', footer.getvalue(), 0x10)
    random: Random = Random(*context)

    key: bytes = crypto.create_key(random, keytables.bcd, 0x10)
    aes: _mode_cbc.CbcMode = AES.new(key, AES.MODE_CBC, iv)
    decrypted: bytes = aes.decrypt(encrypted)

    assert (zlib.crc32(decrypted) == crc32)

    key: bytes = crypto.create_key(random, keytables.bcd, 0x10)
    mac: CMAC.CMAC = CMAC.new(key, ciphermod=AES)
    mac.update(decrypted)
    mac.verify(cmac)

    return decrypted
コード例 #32
0
 def _common(self, raw: bytes):
     return CMAC.new(self._secret, msg=raw, ciphermod=self._mod)
コード例 #33
0
def main(argc, argv):
        with open(sys.argv[1], 'rb') as f:
            data = f.read()
            data1 = data[0x2A0:0x2B0]
            data2 = data[0x2B0:0x2C0]
            data3 = data[0x2C0:0x2D0]
            data4 = data[0x2D0:0x2E0]
            data5 = data[0x2E0:0x300]
            data6 = data[0x300:0x320]
            data7 = data[0x320:0x340]
            data8 = data[0x340:0x360]
            eid1 = data[0x10:0x290]
            hash = data[0x290:0x2A0]
            cmac1= CMAC.new(uhx(EID1KEYS[0]), ciphermod=AES)
            cmac1.update(eid1)
            print(hx(hash))
            print(cmac1.hexdigest())
            sexy = aes_decrypt_cbc(uhx(EID1KEYS[0]), uhx(ZEROS128[0]), eid1)
            keyseed = sexy[:0x10]
            pck1 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), keyseed)
            pck2 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck1)
            pck3 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck2)
            pck4 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck3)
            pck5 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck4)
            pck6 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck5)
            pck7 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck6)
            pck8 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck7)
            pck9 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck8)
            pck10 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck9)
            pck11 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck10)
            pck12 = aes_encrypt_cbc(uhx(INITKEYS[0]), uhx(ZEROS128[0]), pck11)
            data1_stage1 = aes_decrypt_ecb(pck1,data1)
            data2_stage1 = aes_decrypt_ecb(pck2,data2)
            data3_stage1 = aes_decrypt_ecb(pck3,data3)
            data4_stage1 = aes_decrypt_ecb(pck4,data4)
            
            hash1 = data5[0x10:]
            body1 = data5[:0x10]
            cmac1= CMAC.new(pck1, ciphermod=AES)
            cmac1.update(body1)
            print(hx(hash1))
            print(cmac1.hexdigest())
            
            hash2 = data6[0x10:]
            body2 = data6[:0x10]
            cmac1= CMAC.new(pck1, ciphermod=AES)
            cmac1.update(body2)
            print(hx(hash2))
            print(cmac1.hexdigest())
            
            hash3 = data7[0x10:]
            body3 = data7[:0x10]
            cmac1= CMAC.new(pck1, ciphermod=AES)
            cmac1.update(body3)
            print(hx(hash3))
            print(cmac1.hexdigest())
            
            hash4 = data8[0x10:]
            body4 = data8[:0x10]
            cmac1= CMAC.new(pck1, ciphermod=AES)
            cmac1.update(body4)
            print(hx(hash4))
            print(cmac1.hexdigest())
            
            data5_stage1 = aes_decrypt_ecb(pck1,body1)
            data6_stage1 = aes_decrypt_ecb(pck1,body2)
            data7_stage1 = aes_decrypt_ecb(pck1,body3)
            data8_stage1 = aes_decrypt_ecb(pck1,body4)
            
            
            
            with open(sys.argv[1] + '.eid1.dec.bin', 'wb') as g:
                g.write(sexy)
                
            with open(sys.argv[1] + '.init.dec.bin', 'wb') as g:
                g.write(data1_stage1+data2_stage1+data3_stage1+data4_stage1+data5_stage1+data6_stage1+data7_stage1+data8_stage1)
コード例 #34
0
    cipher = DES.new(key, DES.MODE_ECB)
    mess = []
    for i in range(len(list_mess)):
        tmp = cipher.encrypt(convert_number(i))
        tmp = xor(tmp, list_mess[i])
        mess.append(tmp)
    result = ""
    for i in range(len(mess)):
        result += mess[i].decode('utf-8')
    return result


key = "the key!"
mode = 0
secret = b'eightkey'
cobj = CMAC.new(secret, ciphermod=DES)
mac = ""
other_mac = ""
#  Do 10 requests, waiting each time for a response
for request in range(3):
    print("Sending request : ", request)
    socket.send(b"send next~")
    if (request == 0):
        mode = socket.recv()
        print(mode)
        mode = mode.decode('utf-8')
    elif (request == 1):
        mac = socket.recv()
    else:
        encrypted_message = socket.recv()
        cobj.update(encrypted_message)
コード例 #35
0
 def verify(s, buf):
     content, mac = buf[:-0x10], buf[-0x10:]
     CMAC.new(s.cmac_key, ciphermod=AES, msg=content).verify(mac)
     return content
コード例 #36
0
    def calcmic_app(self, mhdr, fhdr, fport, frmpld, direction, fcnt=0):
        """
        Calculate the MIC field for uplink and downlink application data
        Args:
            mhdr, fhdr, fport, frmpld: Necessary fields to compute
            direction: int object, 0 for uplink and 1 for downlink
            fcnt: Necessary only for downlink data
        Returns:
            A 4-byte length bytes object of MIC field

        Downlink MIC B0:
        ------------------------------------------------------------------------------
        | 0x49 | ConfFCnt | 0x0000 | dir | DevAddr | AF(NF)CntDown | 0x00 | len(msg) |
        ------------------------------------------------------------------------------
        Downlink key: SNwkSIntKey

        Uplink MIC B0:
        ----------------------------------------------------------------
        | 0x49 | 0x00000000 | dir | DevAddr | FCntUp | 0x00 | len(msg) |
        ----------------------------------------------------------------
        B0 key: FNwkSIntKey

        B1:
        ----------------------------------------------------------------------------
        | 0x49 | ConfFCnt | TxDr | TxCh | dir | DevAddr | FCntUp | 0x00 | len(msg) |
        ----------------------------------------------------------------------------
        B1 key: SNwkSIntKey
        """
        msg = b''.join([
            mhdr,
            fhdr,
            fport.to_bytes(1, 'big'),
            frmpld,
        ])
        msglen = len(msg)
        B_f = '<cHBBB4sIBB'
        if direction == 0:
            fcnt = self.fcntup
            key = self.fnwksintkey
        else:
            key = self.snwksintkey
        conffcnt = fcnt if (self.ack and direction == 1) else 0
        B0_elements = [
            b'\x49', conffcnt, 0, 0, direction, self.devaddr[::-1], fcnt, 0,
            msglen
        ]
        B0 = struct.pack(
            B_f,
            *B0_elements,
        )
        fmsg = B0 + msg
        fcmacobj = CMAC.new(key, ciphermod=AES)
        fcmac = fcmacobj.update(fmsg)
        if direction == 0:
            B1_elements = B0_elements[:]
            conffcnt = fcnt if self.ack else 0
            B1_elements[1:4] = [conffcnt, self.txdr, self.txch]
            B1 = struct.pack(
                B_f,
                *B1_elements,
            )
            smsg = B1 + msg
            #print('msg: \nB0: {} \nB1: {}'.format(fmsg.hex(), smsg.hex()))
            scmacobj = CMAC.new(self.snwksintkey, ciphermod=AES)
            scmac = scmacobj.update(smsg)
            return scmac.digest()[:MIC_LEN // 2] + fcmac.digest()[:MIC_LEN //
                                                                  2]
        else:
            return fcmac.digest()[:MIC_LEN]
コード例 #37
0
    def calcmic_join(self, key, macpld, optneg=0):
        """
        Calculate the MIC field for join-related data (join request, accept and rejoin)
        Args:
            key: Key used to CMAC
            macpld: MACPayload of join related messages
            optneg: Flag of LoRaWAN version (and the type of accept message)
        Returns:
            A 4-byte length bytes object of MIC field

        Join request MIC fields:
        --------------------------------------
        | MHDR | JoinEUI | DevEUI | DevNonce |
        --------------------------------------
        |1 byte| 8 bytes |8 bytes |  2 bytes |
        --------------------------------------
        Key: NwkKey

        Rejoin 0 & 2 MIC fields:
        --------------------------------------------------
        | MHDR | Rejoin Type | NetID | DevEUI | RJcount0 |
        --------------------------------------------------
        |1 byte|    1 byte   |3 bytes|8 bytes |  2 bytes |
        --------------------------------------------------
        Key: SNwkSIntKey

        Rejoin 1 MIC fields:
        ----------------------------------------------------
        | MHDR | Rejoin Type | JoinEUI | DevEUI | RJcount1 |
        ----------------------------------------------------
        |1 byte|    1 byte   | 8 bytes |8 bytes | 2 bytes  |
        ----------------------------------------------------
        Key: JSIntKey

        Join accept MIC fields (OptNeg = 0, LoRaWAN 1.0):
        ----------------------------------------------------------------------
        | MHDR | JoinNonce | NetID | DevAddr | DLSettings | RxDelay | CFList |
        ----------------------------------------------------------------------
        |1 byte|  3 bytes  |3 bytes| 4 bytes |   1 byte   |  1 byte | 0 ~ 15 |
        ----------------------------------------------------------------------
        Key: NwkKey

        The MACPayload can be directly used of upper messages.

        Join accept MIC fields (OptNeg = 1, LoRaWAN 1.1):
        -------------------------------------------------------------
        | JoinReqType | JoinEUI | DevNonce | MHDR | JoinNonce | NetID ...
        -------------------------------------------------------------
        |   1 byte    | 8 bytes | 2 bytes  |1 byte|  2 bytes  | Same above
        -------------------------------------------------------------
        Key: JSIntKey
        """
        #joinreq_fields = ['mhdr', 'joineui', 'deveui', 'devnonce']
        #rejoin0_fields = rejoin2_fields = ['mhdr', 'joinreqtyp', 'homenetid', 'deveui', 'rjcount0']
        #rejoin1_fields = ['mhdr', 'joinreqtyp', 'joineui', 'deveui', 'rjcount1']
        #joinacpt0_fields = ['mhdr', 'joinnonce', 'homenetid', 'devaddr', 'dlsettings', 'rxdelay', 'cflist']
        #joinacpt1_fields = ['joinreqtyp', 'joineui', 'devnonce', *joinacpt0_fields]
        #joinacpt_basic_f = 's3s3s4sss{}s'
        #mic_f = {
        #    'joinreq': self.joinmic_fields('<s8s8s2s', joinreq_fields),
        #    'rejoin0': self.joinmic_fields('>ss3s8sH', rejoin0_fields),
        #    'rejoin1': self.joinmic_fields('>ss8s8sH', rejoin1_fields),
        #    'rejoin2': self.joinmic_fields('>ss3s8sH', rejoin2_fields),
        #    'joinacpt0': self.joinmic_fields('>' + joinacpt_basic_f, joinacpt0_fields),
        #    'joinacpt1': self.joinmic_fields('<s8s2s' + joinacpt_basic_f, joinacpt1_fields),
        #}
        #joinmic_field = mic_f[typ]
        #def form_fields(name):
        #    try:
        #        return getattr(self, name)
        #    except AttributeError:
        #        return mhdr
        #f = joinmic_field.struct_f
        #if typ.startswith('joinacpt'):
        #    f = f.format(len(self.cflist))
        #print(list(map(form_fields, joinmic_field.field_name)))
        #msg = struct.pack(
        #    f,
        #    *map(form_fields, joinmic_field.field_name)
        #)
        if optneg:
            acptopt_f = '<s8s2s'
            macpld = struct.pack(
                acptopt_f,
                self.joinreqtyp,
                self.joineui[::-1],
                self.devnonce[::-1],
            ) + macpld
        cobj = CMAC.new(key, ciphermod=AES)
        cobj.update(macpld)
        return cobj.digest()[:MIC_LEN]
コード例 #38
0
 def __init__(self, key):
     self.cmac = CMAC.new(key, ciphermod=AES)
コード例 #39
0
ファイル: core.py プロジェクト: dgoltzsche/keymanager
    def run(self):
        curve = registry.get_curve('secp256r1')
        data = self._socket.recv(4)
        if int.from_bytes(bytes(data), byteorder='little', signed=False) != 0:
            print("ERROR")  #TODO
        data = self._socket.recv(ctypes.sizeof(sgx_ra_msg1_t))
        msg1 = sgx_ra_msg1_t.from_buffer_copy(data)
        remote_public_x_buffer = bytes(msg1.g_a)[:PUBLIC_KEY_X_SIZE]
        remote_public_y_buffer = bytes(msg1.g_a)[PUBLIC_KEY_X_SIZE:]
        private_key_point = randbelow(curve.field.n)
        public_key_point = private_key_point * curve.g
        remote_public_key_x = int.from_bytes(remote_public_x_buffer,
                                             byteorder='little',
                                             signed=False)
        remote_public_key_y = int.from_bytes(remote_public_y_buffer,
                                             byteorder='little',
                                             signed=False)

        def compute_shared_secret(private_key_point, remote_public_key_x,
                                  remote_public_key_y):
            """ Calc Diffiehellman key and compute secret
            """
            remote_public_key_point = ec2.Point(curve, remote_public_key_x,
                                                remote_public_key_y)
            shared_point = private_key_point * remote_public_key_point
            shared_secret = shared_point.x.to_bytes(PUBLIC_KEY_X_SIZE,
                                                    byteorder="little")
            return shared_secret

        shared_secret = compute_shared_secret(private_key_point,
                                              remote_public_key_x,
                                              remote_public_key_y)
        kdk = CMAC.new(bytes([0] * 16), ciphermod=AES)
        kdk.update(shared_secret)
        smk = CMAC.new(kdk.digest(), ciphermod=AES)
        smk.update(b'\x01SMK\x00\x80\x00')
        public_key_x_buffer = public_key_point.x.to_bytes(PUBLIC_KEY_X_SIZE,
                                                          byteorder="little")
        public_key_y_buffer = public_key_point.y.to_bytes(PUBLIC_KEY_Y_SIZE,
                                                          byteorder="little")
        private_key = ec.derive_private_key(private_value=1111,
                                            curve=ec.SECP256R1(),
                                            backend=default_backend())
        signature_algorithm = ec.ECDSA(hashes.SHA256())
        data = public_key_x_buffer + public_key_y_buffer + bytes(msg1.g_a)
        signature = private_key.sign(data, signature_algorithm)
        r, s = decode_dss_signature(signature)
        r = r.to_bytes(32, byteorder="little")
        s = s.to_bytes(32, byteorder="little")
        msg = public_key_x_buffer + public_key_y_buffer + spid + (1).to_bytes(
            2, byteorder='little') + (1).to_bytes(2,
                                                  byteorder='little') + r + s
        mac = CMAC.new(smk.digest(), ciphermod=AES)
        mac.update(msg)
        msg = msg + mac.digest() + (0).to_bytes(4, byteorder='little')
        self._socket.send(msg)
        data = self._socket.recv(4096)
        quote_size = int(len(data) - 336)  #size of msg3
        msg3 = sgx_ra_msg3_t_factory(quote_size).from_buffer_copy(data)
        if bytes(msg1.g_a) != bytes(msg3.g_a):
            pass  #TODO error
        """mac = CMAC.new(smk.digest(), ciphermod=AES)
        mac.update(bytes(msg3.g_a))
        print(mac.digest()) #TODO
        print(bytes(msg3.mac)) #TODO"""
        quote = sgx_quote_t_factory(len(bytes(msg3.quote))).from_buffer_copy(
            bytes(msg3.quote))
        b64quote = b64encode(bytes(msg3.quote)).decode('utf8')
        mk = CMAC.new(kdk.digest(), ciphermod=AES)
        mk.update(b'\x01MK\x00\x80\x00')
        sk = CMAC.new(kdk.digest(), ciphermod=AES)
        sk.update(b'\x01SK\x00\x80\x00')  #shared secret for com
        shared_secret = sk.digest()

        def request_ias(quote):
            """ Request the Intel Attestation Service to verify to quote
            """
            data = {'isvEnclaveQuote': quote}
            print(data)
            cert = (self._cert, self._key)
            headers = {'Content-Type': 'application/json'}
            r = requests.post(IAS_QUOTE_URL,
                              cert=cert,
                              json=data,
                              headers=headers)
            if r.status_code != 200:
                self._socket.close()
                return False, None
            return (True, json.loads(r.text))

        if not self._sim:
            status, attestation_result = request_ias(b64quote)
            if not status:
                self._socket.close()
                return
            if attestation_result['isvEnclaveQuoteStatus'] != 'OK':
                print("Warning. isvEnclaveQuoteStatus is not ok.")
                if attestation_result[
                        'isvEnclaveQuoteStatus'] != 'GROUP_OUT_OF_DATE':  #only for lazy deploy
                    self._socket.close()
                    return

        def is_valid_mrenclave(report_body):
            """ Verify mrenclave to ensure that the right runtime is loaded in enclave
            """
            raw = b64decode(report_body)[
                112:112 + 32]  #mrenclave starts at 112 (size 32)
            m = sha256()
            m.update(raw)
            mrenclave_hash = m.hexdigest()
            result = db_client["faasm"]["config"].find_one(
                {'mrenclave': mrenclave_hash})
            if not result:
                return True  #TODO WARNING only for test
            return True

        if not self._sim:
            if not is_valid_mrenclave(
                    attestation_result['isvEnclaveQuoteBody']):
                self._socket.close()
                return
        payload = sgx_wamr_msg_pkey_mkey_t_factory(0, 0, MASTER_SECRET)
        cipher, nonce, mac = encrypt_aes_gcm_128(payload, shared_secret)
        res = sgx_wamr_msg_t_factory(0, mac, nonce, len(cipher), cipher)
        self._socket.send(res)
        print("Attestation was successful.")
        while True:
            data = self._socket.recv(ctypes.sizeof(sgx_wamr_msg_t))
            if len(data) == 0:
                break
            msg = sgx_wamr_msg_t.from_buffer_copy(data)
            nonce = b64encode(bytes(msg.nonce))
            if db_client["faasm"]["nonces"].find_one({"value": nonce}):
                res_payload = build_error_buffer('Replay protection.\0')
                cipher, nonce, mac = encrypt_aes_gcm_128(
                    res_payload, shared_secret)
                res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                             len(cipher), cipher)
            else:
                encrypted_payload_data = self._socket.recv(msg.payload_len)
                payload_data = decrypt_aes_gcm_128(encrypted_payload_data,
                                                   bytes(msg.nonce),
                                                   bytes(msg.mac),
                                                   shared_secret)
                db_client["faasm"]["nonces"].insert_one({"value": nonce})
                if payload_data[0] < 2:  #call
                    payload = sgx_wamr_msg_hash_sid_t.from_buffer_copy(
                        payload_data)
                    session_id = bytes(payload.session_id).decode()
                    function_hash_digest = hexlify(
                        bytes(payload.opcode_enc_hash)).decode('ascii')
                    nonce = b64encode(bytes(payload.nonce))
                    if db_client["faasm"]["nonces"].find_one({"value": nonce}):
                        res_payload = build_error_buffer(
                            bytes(msg.nonce), 'Replay protection.\0')
                        cipher, nonce, mac = encrypt_aes_gcm_128(
                            res_payload, shared_secret)
                        res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                     len(cipher), cipher)
                    else:
                        db_client["faasm"]["nonces"].insert_one(
                            {"value": nonce})
                        result = db_client["faasm"]["session"].find_one({
                            "sid":
                            session_id,
                            "hash":
                            function_hash_digest
                        })
                        if result:
                            payload_key = result['key'].encode()
                            res_payload = sgx_wamr_payload_key_factory(
                                bytes(msg.nonce), 0, 0, payload_key)
                            cipher, nonce, mac = encrypt_aes_gcm_128(
                                res_payload, shared_secret)
                            res = sgx_wamr_msg_t_factory(
                                msg.msg_id, mac, nonce, len(cipher), cipher)
                        else:
                            res_payload = build_error_buffer(
                                bytes(msg.nonce),
                                'Function and sid doesnt match.\0')
                            cipher, nonce, mac = encrypt_aes_gcm_128(
                                res_payload, shared_secret)
                            res = sgx_wamr_msg_t_factory(
                                msg.msg_id, mac, nonce, len(cipher), cipher)
                elif payload_data[0] < 3:  #load
                    payload = sgx_wamr_msg_hash_fct_t_factory(
                        msg.payload_len).from_buffer_copy(payload_data)
                    function_name = bytes(payload.fct_name).decode()
                    function_hash_digest = hexlify(
                        bytes(payload.opcode_enc_hash)).decode('ascii')
                    result = db_client["faasm"]["function"].find_one({
                        "name":
                        function_name,
                        "hash":
                        function_hash_digest
                    })
                    if result:
                        op_key = result['key'].encode()
                        policy = result['ccp'].encode()
                        res_payload = sgx_wamr_okey_policy_t_factory(
                            bytes(msg.nonce), 0, 0, op_key, policy)
                        cipher, nonce, mac = encrypt_aes_gcm_128(
                            res_payload, shared_secret)
                        res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                     len(cipher), cipher)
                    else:
                        res_payload = build_error_buffer(
                            bytes(msg.nonce),
                            'Hash and function doesnt match.\0')
                        cipher, nonce, mac = encrypt_aes_gcm_128(
                            res_payload, shared_secret)
                        res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                     len(cipher), cipher)
                elif payload_data[0] < 6:  #state write
                    payload = sgx_wamr_msg_state_write_t_factory(
                        msg.payload_len).from_buffer_copy(payload_data)
                    buffer_nonce_digest = hexlify(bytes(
                        payload.buffer_nonce)).decode('ascii')
                    namespace, key = bytes(
                        payload.data[:payload.name_length]).decode().split(':')
                    total_execution_stack = bytes(
                        payload.data[payload.name_length:]).decode()
                    state_secret = get_random_bytes(AES_KEY_SIZE)
                    filter = {'namespace': namespace, 'key': key}
                    update = {
                        '$set': {
                            'secret': hexlify(state_secret).decode('ascii'),
                            'buffer_nonce': buffer_nonce_digest,
                            'stack': total_execution_stack
                        }
                    }
                    state_pendings[namespace + ':' + key] = {
                        'filter': filter,
                        'update': update
                    }
                    res_payload = sgx_wamr_payload_key_factory(
                        bytes(msg.nonce), 0, 2, state_secret)
                    cipher, nonce, mac = encrypt_aes_gcm_128(
                        res_payload, shared_secret)
                    res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                 len(cipher), cipher)
                elif payload_data[0] < 8:  #state read
                    payload = sgx_wamr_msg_state_read_t_factory(
                        msg.payload_len).from_buffer_copy(payload_data)
                    namespace, key = bytes(payload.key).decode().split(':')
                    result = db_client["faasm"]["state"].find_one({
                        "namespace": namespace,
                        "key": key
                    })
                    if result:
                        buffer_nonce = unhexlify(result['buffer_nonce'])
                        state_secret = unhexlify(result["secret"])
                        stack = result['stack'].encode()
                        res_payload = sgx_wamr_state_read_res_factory(
                            bytes(msg.nonce), 0, 2, state_secret, buffer_nonce,
                            stack)
                        cipher, nonce, mac = encrypt_aes_gcm_128(
                            res_payload, shared_secret)
                        res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                     len(cipher), cipher)
                    else:
                        res_payload = build_error_buffer(
                            bytes(msg.nonce), 'State is not registered.\0')
                        cipher, nonce, mac = encrypt_aes_gcm_128(
                            res_payload, shared_secret)
                        res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                     len(cipher), cipher)
                elif payload_data[0] < 10:  #request check
                    payload = sgx_wamr_msg_nonce_offer_t.from_buffer_copy(
                        payload_data)
                    nonce = b64encode(bytes(payload.nonce))
                    if db_client["faasm"]["nonces"].find_one({"value": nonce}):
                        res_payload = build_error_buffer(
                            bytes(msg.nonce), 'Replay protection.\0')
                        cipher, nonce, mac = encrypt_aes_gcm_128(
                            res_payload, shared_secret)
                        res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                     len(cipher), cipher)
                    else:
                        db_client["faasm"]["nonces"].insert_one(
                            {"value": nonce})
                        res_payload = sgx_wamr_ack_t_factory(
                            bytes(msg.nonce), 0, 0)
                        cipher, nonce, mac = encrypt_aes_gcm_128(
                            res_payload, shared_secret)
                        res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                     len(cipher), cipher)
                elif payload_data[0] < 12:  #state write reply
                    payload = sgx_wamr_msg_state_read_t_factory(
                        msg.payload_len).from_buffer_copy(payload_data)
                    namespace, key = bytes(payload.key).decode().split(':')
                    if namespace + ':' + key not in state_pendings:
                        res_payload = build_error_buffer(
                            bytes(msg.nonce), 'State is not registered.\0')
                        cipher, nonce, mac = encrypt_aes_gcm_128(
                            res_payload, shared_secret)
                        res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                     len(cipher), cipher)
                    else:
                        tmp = state_pendings[namespace + ':' + key]
                        result = db_client["faasm"]["state"].update_one(
                            tmp['filter'], tmp['update'], upsert=True)
                        if result:
                            del state_pendings[namespace + ':' + key]
                            res_payload = sgx_wamr_ack_t_factory(
                                bytes(msg.nonce), 0, 0)
                            cipher, nonce, mac = encrypt_aes_gcm_128(
                                res_payload, shared_secret)
                            res = sgx_wamr_msg_t_factory(
                                msg.msg_id, mac, nonce, len(cipher), cipher)
                        else:
                            res_payload = build_error_buffer(
                                bytes(msg.nonce), 'DB Error.\0')
                            cipher, nonce, mac = encrypt_aes_gcm_128(
                                res_payload, shared_secret)
                            res = sgx_wamr_msg_t_factory(
                                msg.msg_id, mac, nonce, len(cipher), cipher)
                else:
                    print("Error, received unknown message!")
                    res_payload = build_error_buffer(
                        bytes(msg.nonce),
                        'Error, received unknown message!.\0')
                    cipher, nonce, mac = encrypt_aes_gcm_128(
                        res_payload, shared_secret)
                    res = sgx_wamr_msg_t_factory(msg.msg_id, mac, nonce,
                                                 len(cipher), cipher)
                self._socket.send(res)
        self._socket.close()
コード例 #40
0
ファイル: crypto.py プロジェクト: matheuswhite/bluebees
 def aes_cmac(self, key: bytes, text: bytes):
     cobj = CMAC.new(key=key, ciphermod=AES)
     cobj.update(text)
     return cobj.digest()
コード例 #41
0
ファイル: SNVS.py プロジェクト: requeijaum/sherwood
def main(argc, argv):
    with open(sys.argv[1], 'rb') as f:
        data = f.read()
        snvs = data[0x560:0x2560]  #0x2560

        eid1 = data[0x10:0x290]
        hash = data[0x290:0x2A0]
        cmac1 = CMAC.new(uhx(EID1KEYS[0]), ciphermod=AES)
        cmac1.update(eid1)
        print(hx(hash))
        print(cmac1.hexdigest())
        sexy = aes_decrypt_cbc(uhx(EID1KEYS[0]), uhx(ZEROS128[0]), eid1)
        keyseed = sexy[0x150:0x160]

        keygen = aes_encrypt_cbc(uhx(EID1KEYS[2]), uhx(ZEROS128[0]), keyseed)
        keygen2 = aes_encrypt_cbc(uhx(EID1KEYS[2]), uhx(ZEROS128[0]), keygen)
        keygen3 = aes_encrypt_cbc(uhx(EID1KEYS[2]), uhx(ZEROS128[0]), keygen2)
        keygen4 = aes_encrypt_cbc(uhx(EID1KEYS[2]), uhx(ZEROS128[0]), keygen3)
        keygen5 = aes_encrypt_cbc(uhx(EID1KEYS[2]), uhx(ZEROS128[0]), keygen4)
        keygen6 = aes_encrypt_cbc(uhx(EID1KEYS[2]), uhx(ZEROS128[0]), keygen5)
        keygen7 = aes_encrypt_cbc(uhx(EID1KEYS[2]), uhx(ZEROS128[0]), keygen6)
        keygen8 = aes_encrypt_cbc(uhx(EID1KEYS[2]), uhx(ZEROS128[0]), keygen7)

        f.close()

        snvs_dec = snvs

        xor1 = [chr(ord(a) ^ ord(b)) for (a, b) in zip(snvs_dec, uhx(XOR))]

        with open(sys.argv[1] + '.snvs.dec.bin', 'wb') as m:
            m.write("".join(xor1))

        with open(sys.argv[1] + '.snvs.enc.bin', 'wb') as g:

            for x in range(0, 0x400, 0x10):
                enc = aes_encrypt_cbc(keygen, uhx(ZEROS128[0]),
                                      "".join(xor1)[x:0x10 + x])
                g.write(enc)

            for x in range(0x400, 0x800, 0x10):
                enc = aes_encrypt_cbc(keygen2, uhx(ZEROS128[0]),
                                      "".join(xor1)[x:0x10 + x])
                g.write(enc)

            for x in range(0x800, 0xC00, 0x10):
                enc = aes_encrypt_cbc(keygen3, uhx(ZEROS128[0]),
                                      "".join(xor1)[x:0x10 + x])
                g.write(enc)

            for x in range(0xC00, 0x1000, 0x10):
                enc = aes_encrypt_cbc(keygen4, uhx(ZEROS128[0]),
                                      "".join(xor1)[x:0x10 + x])
                g.write(enc)

            for x in range(0x1000, 0x1400, 0x10):
                enc = aes_encrypt_cbc(keygen5, uhx(ZEROS128[0]),
                                      "".join(xor1)[x:0x10 + x])
                g.write(enc)

            for x in range(0x1400, 0x1800, 0x10):
                enc = aes_encrypt_cbc(keygen6, uhx(ZEROS128[0]),
                                      "".join(xor1)[x:0x10 + x])
                g.write(enc)

            for x in range(0x1800, 0x1C00, 0x10):
                enc = aes_encrypt_cbc(keygen7, uhx(ZEROS128[0]),
                                      "".join(xor1)[x:0x10 + x])
                g.write(enc)

            for x in range(0x1C00, 0x2000, 0x10):
                enc = aes_encrypt_cbc(keygen8, uhx(ZEROS128[0]),
                                      "".join(xor1)[x:0x10 + x])
                g.write(enc)

    with open(sys.argv[1] + '.eid1.dec.bin', 'wb') as g:
        g.write(sexy)
コード例 #42
0
class EaxMode(object):
    """*EAX* mode.

    This is an Authenticated Encryption with Associated Data
    (`AEAD`_) mode. It provides both confidentiality and authenticity.

    The header of the message may be left in the clear, if needed,
    and it will still be subject to authentication.

    The decryption step tells the receiver if the message comes
    from a source that really knowns the secret key.
    Additionally, decryption detects if any part of the message -
    including the header - has been modified or corrupted.

    This mode requires a *nonce*.

    This mode is only available for ciphers that operate on 64 or
    128 bits blocks.

    There are no official standards defining EAX.
    The implementation is based on `a proposal`__ that
    was presented to NIST.

    .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
    .. __: http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/eax/eax-spec.pdf
    """
    def __init__(self, factory, **kwargs):
        """Create a new block cipher, configured in EAX mode.

        :Parameters:
          factory : module
            A symmetric cipher module from `Crypto.Cipher`
            (like `Crypto.Cipher.AES`).

        :Keywords:
          key : byte string
            The secret key to use in the symmetric cipher.

          nonce : byte string
            A mandatory value that must never be reused for any other encryption.
            There are no restrictions on its length,
            but it is recommended to use at least 16 bytes.

            The nonce shall never repeat for two
            different messages encrypted with the same key,
            but it does not need to be random.

          mac_len : integer
            Length of the MAC, in bytes. It must be no
            larger than the cipher block bytes (which is the default).
        """

        self.block_size = factory.block_size

        try:
            key = kwargs.pop("key")
            nonce = kwargs.pop("nonce")
        except KeyError, e:
            raise TypeError("Missing parameter: " + str(e))
        self._mac_len = kwargs.pop("mac_len", self.block_size)

        self._mac_tag = None  # Cache for MAC tag

        # Allowed transitions after initialization
        self._next = [
            self.update, self.encrypt, self.decrypt, self.digest, self.verify
        ]

        # MAC tag length
        if not (4 <= self._mac_len <= self.block_size):
            raise ValueError("Parameter 'mac_len' must not be larger than %d" %
                             self.block_size)

        self._omac = [
            CMAC.new(key,
                     bchr(0) * (self.block_size - 1) + bchr(i),
                     ciphermod=factory,
                     cipher_params=kwargs) for i in xrange(0, 3)
        ]

        # Compute MAC of nonce
        self._omac[0].update(nonce)
        self._signer = self._omac[1]

        # MAC of the nonce is also the initial counter for CTR encryption
        counter_int = bytes_to_long(self._omac[0].digest())
        counter_obj = Counter.new(self.block_size * 8,
                                  initial_value=counter_int)
        self._cipher = factory.new(key,
                                   factory.MODE_CTR,
                                   counter=counter_obj,
                                   **kwargs)