Exemplo n.º 1
0
    def encrypt_ige(plain_text, key, iv):
        """Encrypts the given text in 16-bytes blocks by using the
           given key and 32-bytes initialization vector
        """

        # Add random padding iff it's not evenly divisible by 16 already
        if len(plain_text) % 16 != 0:
            padding_count = 16 - len(plain_text) % 16
            plain_text += os.urandom(padding_count)

        iv1 = iv[:len(iv) // 2]
        iv2 = iv[len(iv) // 2:]

        aes = pyaes.AES(key)

        cipher_text = []
        blocks_count = len(plain_text) // 16

        for block_index in range(blocks_count):
            plain_text_block = list(plain_text[block_index *
                                               16:block_index * 16 + 16])
            for i in range(16):
                plain_text_block[i] ^= iv1[i]

            cipher_text_block = aes.encrypt(plain_text_block)

            for i in range(16):
                cipher_text_block[i] ^= iv2[i]

            iv1 = cipher_text_block
            iv2 = plain_text[block_index * 16:block_index * 16 + 16]

            cipher_text.extend(cipher_text_block)

        return bytes(cipher_text)
Exemplo n.º 2
0
        def ctr(cls, data: bytes, key: bytes, iv: bytearray,
                state: bytearray) -> bytes:
            cipher = pyaes.AES(key)

            out = bytearray(data)
            chunk = cipher.encrypt(iv)

            for i in range(0, len(data), 16):
                for j in range(0, min(len(data) - i, 16)):
                    out[i + j] ^= chunk[state[0]]

                    state[0] += 1

                    if state[0] >= 16:
                        state[0] = 0

                    if state[0] == 0:
                        for k in range(15, -1, -1):
                            try:
                                iv[k] += 1
                                break
                            except ValueError:
                                iv[k] = 0

                        chunk = cipher.encrypt(iv)

            return out
Exemplo n.º 3
0
    def decrypt_ige(cipher_text, key, iv):
        """Decrypts the given text in 16-bytes blocks by using the
           given key and 32-bytes initialization vector
        """
        iv1 = iv[:len(iv) // 2]
        iv2 = iv[len(iv) // 2:]

        aes = pyaes.AES(key)

        plain_text = []
        blocks_count = len(cipher_text) // 16

        cipher_text_block = [0] * 16
        for block_index in range(blocks_count):
            for i in range(16):
                cipher_text_block[i] = \
                    cipher_text[block_index * 16 + i] ^ iv2[i]

            plain_text_block = aes.decrypt(cipher_text_block)

            for i in range(16):
                plain_text_block[i] ^= iv1[i]

            iv1 = cipher_text[block_index * 16:block_index * 16 + 16]
            iv2 = plain_text_block

            plain_text.extend(plain_text_block)

        return bytes(plain_text)
Exemplo n.º 4
0
def ctr_decrypt(iv, key, msg):
    aes = pyaes.AES(key)
    ctr = 0
    out = bytearray()
    for chunk in blockify(msg):
        iv_ctr = iv[:8] + bytearray(struct.pack("Q", ctr))
        out.extend(xor(msg, aes.decrypt(iv_ctr)))
        ctr += 1
    return out
Exemplo n.º 5
0
def cbs_decrypt(iv, key, msg):
    aes = pyaes.AES(key)
    out = bytearray()
    xor_factor = iv
    for chunk in blockify(msg):
        plaintext = xor(xor_factor, aes.decrypt(chunk))
        out.extend(plaintext)
        xor_factor = chunk
    return out
Exemplo n.º 6
0
def cbs_encrypt(iv, key, msg):
    aes = pyaes.AES(key)
    xor_factor = iv
    out = bytearray()
    for chunk in blockify(msg):
        ciphertext = aes.encrypt(xor(xor_factor, chunk))
        out.extend(ciphertext)
        xor_factor = ciphertext
    return out
Exemplo n.º 7
0
 def __init__(self, key: bytes, iv: bytes):
     if len(key) != 32:
         raise ValueError(
             "AES key length must be 32 bytes, got %d bytes: %s" %
             (len(key), short_hex(key)))
     if len(iv) != 32:
         raise ValueError(
             "AES init vector length must be 32 bytes, got %d bytes: %s" %
             (len(iv), short_hex(key)))
     self.iv1, self.iv2 = iv[:16], iv[16:]
     self.aes = pyaes.AES(key)
     self.plain_buffer = b''
Exemplo n.º 8
0
    def encryptResponse(self, request, decrypted, response):
        randomSalt = bytearray(os.urandom(16))
        result = hashlib.sha256(bytes(randomSalt)).digest()

        SaltC = bytearray(request['message']['salt'])
        XorSalts = bytearray(pyaes.AES(self.key, v6=self.v6).decrypt(SaltC))
        randomStuff = bytearray(16)
        for i in range(0, 16):
            randomStuff[i] = (XorSalts[i] ^ randomSalt[i]) & 0xff

        message = self.DecryptedResponse.Message()
        message['response'] = response
        message['keys'] = bytes(randomStuff)
        message['hash'] = result
        message['xorSalts'] = bytes(XorSalts)
        message['hwid'] = self.config['hwid']

        # SaltS
        SaltS = bytearray(os.urandom(16))

        d = pyaes.AESModeOfOperationCBC(self.key, SaltS,
                                        v6=True).decrypt(SaltS)

        # DSaltS
        DSaltS = bytearray(d)

        # HMacMsg
        HMacMsg = bytearray(16)
        for i in range(0, 16):
            HMacMsg[i] = (SaltS[i] ^ DSaltS[i]) & 0xff
        HMacMsg.extend(message.__bytes__())

        # HMacKey
        requestTime = decrypted['requestTime']
        HMacKey = self.getMACKey(requestTime)
        if hasattr(hashlib.sha256(), 'digest_size'):
            HMac = hmac.new(HMacKey, bytes(HMacMsg), hashlib.sha256)
        else:  # micropython defaultly use uhashlib, which has no digest_size
            HMac = hmac.new(HMacKey, bytes(HMacMsg), hashlib._sha256.sha256)
        digest = HMac.digest()

        responsedata = self.DecryptedResponse()
        responsedata['message'] = message
        responsedata['hmac'] = digest[16:]

        encrypter = pyaes.Encrypter(
            pyaes.AESModeOfOperationCBC(self.key, SaltS, v6=True))
        crypted = encrypter.feed(responsedata.__bytes__()) + encrypter.feed()

        return bytes(SaltS), bytes(bytearray(crypted))
Exemplo n.º 9
0
def ofb(plaintext, key, iv, block_size=8, decrypting=False):
    blocks = block_feeder(plaintext, block_size)
    ciphertext = ''
    aes = pyaes.AES(key)
    for block in blocks:
        encrypted_iv = bytes(aes.encrypt(iv))
        right_side_enc_iv_bytes = encrypted_iv[:block_size]
        cipher_block = (''.join(
            [chr(ord(a) ^ int(b)) for a, b in zip(block, iv)]))
        ciphertext += cipher_block
        iv = iv[block_size:] + right_side_enc_iv_bytes
    if decrypting:
        ciphertext = unpad(ciphertext, block_size)
    return ciphertext
Exemplo n.º 10
0
def authenticate_lcg(alpha_numbers, key, serial_number, batch_number):
    hashids = Hashids(min_length=16, salt=key)
    hashidEncoded = hashids.decode(alpha_numbers)
    if hashidEncoded == ():
        print 'unauthentic'
        return 0
    else:
        final = str(hashidEncoded).strip('(L,)')
        if len(final) != 16:
            print 'unauthentic'
            return 0
        # final = str(hashidEncoded)[1:16]

        if int(serial_number) <= 9:
            final = final[15:] + final[:15]
            print final

        key_32 = key.zfill(32)
        aes = pyaes.AES(key_32)

        str_random = final[6:]
        plaintext_bytes = [ord(i) for i in str_random.zfill(16)]
        ciphertext = aes.encrypt(plaintext_bytes)
        print ciphertext
        a = 0
        sec_a = ""
        sec = ""
        ba_num = ""
        ser_num = ""

        a = sum(ciphertext)
        sec_aes = str(a).zfill(4)
        for i in xrange(2, len(sec_aes)):
            sec_a = sec_a + sec_aes[i]
        for i in xrange(4, len(final) - 10):
            sec = sec + final[i]
        for i in xrange(2, len(final) - 12):
            ba_num = ba_num + final[i]

        for i in xrange(0, len(final) - 14):
            ser_num = ser_num + final[i]
        if (sec_a == sec) and (ba_num == batch_number) and (ser_num
                                                            == serial_number):
            print 'authentic'
        else:
            print 'unauthentic'
Exemplo n.º 11
0
    def ige(data: bytes, key: bytes, iv: bytes, encrypt: bool) -> bytes:
        cipher = pyaes.AES(key)

        iv_1 = iv[:16]
        iv_2 = iv[16:]

        data = [data[i: i + 16] for i in range(0, len(data), 16)]

        if encrypt:
            for i, chunk in enumerate(data):
                iv_1 = data[i] = xor(cipher.encrypt(xor(chunk, iv_1)), iv_2)
                iv_2 = chunk
        else:
            for i, chunk in enumerate(data):
                iv_2 = data[i] = xor(cipher.decrypt(xor(chunk, iv_2)), iv_1)
                iv_1 = chunk

        return b"".join(data)
Exemplo n.º 12
0
	def encryptResponse(self, request, decrypted, response):
		randomSalt = bytearray(os.urandom(16))
		result = hashlib.sha256(bytes(randomSalt)).digest()

		iv = bytearray(request['message']['salt'])

		XorSalts = pyaes.AES(self.key, v6=self.v6).decrypt(iv)
		randomStuff = bytearray(16)
		for i in range(0,16):
			randomStuff[i] = (bytearray(XorSalts)[i] ^ randomSalt[i]) & 0xff

		responsedata = self.DecryptedResponse()
		responsedata['response'] = response
		responsedata['keys'] = bytes(randomStuff)
		responsedata['hash'] = result

		encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(self.key, iv, v6=self.v6))
		crypted = encrypter.feed(responsedata.__bytes__()) + encrypter.feed()

		return bytes(iv), crypted
Exemplo n.º 13
0
    def encrypt_ige(plain_text, key, iv):
        """
        Encrypts the given text in 16-bytes blocks by using the
        given key and 32-bytes initialization vector.
        """
        padding = len(plain_text) % 16
        if padding:
            plain_text += os.urandom(16 - padding)

        if tgcrypto:
            return tgcrypto.ige256_encrypt(plain_text, key, iv)
        if cryptg:
            return cryptg.encrypt_ige(plain_text, key, iv)
        if libssl.encrypt_ige:
            return libssl.encrypt_ige(plain_text, key, iv)

        iv1 = iv[:len(iv) // 2]
        iv2 = iv[len(iv) // 2:]

        aes = pyaes.AES(key)

        cipher_text = []
        blocks_count = len(plain_text) // 16

        for block_index in range(blocks_count):
            plain_text_block = list(plain_text[block_index *
                                               16:block_index * 16 + 16])
            for i in range(16):
                plain_text_block[i] ^= iv1[i]

            cipher_text_block = aes.encrypt(plain_text_block)

            for i in range(16):
                cipher_text_block[i] ^= iv2[i]

            iv1 = cipher_text_block
            iv2 = plain_text[block_index * 16:block_index * 16 + 16]

            cipher_text.extend(cipher_text_block)

        return bytes(cipher_text)
Exemplo n.º 14
0
def cbc_decrypt(cyphertext, key, iv):
    blocks = block_feeder(cyphertext)
    plaintext = ''
    aes = pyaes.AES(key)
    last_cypher = blocks[0]
    for i in range(len(blocks)):
        block = blocks[i]
        block_bytes = [ord(c) for c in block]
        decrypted_block = aes.decrypt(block_bytes)
        decrypted_block = ''.join([chr(i) for i in decrypted_block])
        if i == 0:
            unxored_block = (''.join(
                [chr(ord(a) ^ int(b)) for a, b in zip(decrypted_block, iv)]))
        else:
            unxored_block = (''.join([
                chr(ord(a) ^ ord(b))
                for a, b in zip(decrypted_block, last_cypher)
            ]))
            last_cypher = blocks[i]
        plaintext += unxored_block
    return unpad(plaintext)
Exemplo n.º 15
0
def generateHash(message):
    """
	The KMS v4 hash is a variant of CMAC-AES-128. There are two key differences:
	* The 'AES' used is modified in particular ways:
	  * The basic algorithm is Rjindael with a conceptual 160bit key and 128bit blocks.
	    This isn't part of the AES standard, but it works the way you'd expect.
	    Accordingly, the algorithm uses 11 rounds and a 192 byte expanded key.
	* The trailing block is not XORed with a generated subkey, as defined in CMAC.
	  This is probably because the subkey generation algorithm is only defined for
	  situations where block and key size are the same.
	"""
    aes = pyaes.AES(key, rounds=11)

    messageSize = len(message)
    lastBlock = bytearray(16)
    hashBuffer = bytearray(16)

    # MessageSize / Blocksize
    j = messageSize >> 4

    # Remainding bytes
    k = messageSize & 0xf

    # Hash
    for i in range(0, j):
        xorBuffer(message, i << 4, hashBuffer, 16)
        hashBuffer = bytearray(aes.encrypt(hashBuffer))

    # Bit Padding
    ii = 0
    for i in range(j << 4, k + (j << 4)):
        lastBlock[ii] = message[i]
        ii += 1
    lastBlock[k] = 0x80

    xorBuffer(lastBlock, 0, hashBuffer, 16)
    hashBuffer = bytearray(aes.encrypt(hashBuffer))

    return bytes(hashBuffer)
Exemplo n.º 16
0
def aes_crypto(plaintext: str = None):
    """AES 加密"""
    # 16 byte block of plain text
    if not plaintext:
        plaintext = "Hello World!!!!!"
    plaintext_bytes = [ord(c) for c in plaintext]

    # key_value = os.urandom(32)
    key_value = b'\x18\x7f\xbb\xd7/\xcb\xe56~me<>\xefM>Zg\xc7\xd0\xaf|\xf3\xc7\xd5,D\tB&N\x9c'
    aes = pyaes.AES(key_value)

    print(plaintext_bytes)
    # Encrypt!
    ciphertext = aes.encrypt(plaintext_bytes)
    print(ciphertext)
    # Decrypt!
    decrypted = aes.decrypt(ciphertext)
    print(decrypted)

    result = ''
    for i in decrypted:
        result += chr(i)
    print(result)
Exemplo n.º 17
0
def main():
    numbers = raw_input("Please enter number of random numbers: > ").strip()
    numbers = int(numbers)
    product_id = raw_input("Please enter the product id: > ").strip()
    serial_number = raw_input("Please enter serial_number: > ").strip()
    batch_number = raw_input("Please enter batch_number: > ").strip()

    if int(serial_number) <= 9:
        serial = str(serial_number).zfill(2)
    else:
        serial = serial_number

    if int(batch_number) <= 9:
        batch = str(batch_number).zfill(2)
    else:
        batch = batch_number

    digit_length = raw_input(
        "Please enter number of digits in the alphanumeric number: > ").strip(
        )
    key = str(serial) + str(batch) + str(digit_length) + str(product_id)
    key_32 = key.zfill(32)
    aes = pyaes.AES(key_32)
    generate_lcg(numbers, aes, key, serial, batch)
Exemplo n.º 18
0
def cbc_encrypt(plaintext, key, iv):
    # Separate the text into blocks
    blocks = block_feeder(plaintext)

    # Where the cipher tet will be held for return
    cipher_text = ''
    aes = pyaes.AES(key)

    # Variable to retain the last encrypted block for later xoring
    last_cipher = None

    for i in range(len(blocks)):
        # If we're dealing with the first block, xor with iv, else xor with last encrypted block
        if i == 0:
            xored_block = (''.join(
                [chr(ord(a) ^ int(b)) for a, b in zip(blocks[0], iv)]))
        else:
            xored_block = (''.join([
                chr(ord(a) ^ int(b)) for a, b in zip(blocks[i], last_cipher)
            ]))
        block_bytes = [ord(c) for c in xored_block]
        last_cipher = (aes.encrypt(block_bytes))
        cipher_text += ''.join([chr(i) for i in last_cipher])
    return (cipher_text)
Exemplo n.º 19
0
def raw_encrypt(key, plaintext):
    assert len(plaintext) == 16

    aes = pyaes.AES(key)
    return aes.encrypt(plaintext)
Exemplo n.º 20
0
    PORT=int(sys.argv[1])

print("[+] Server Running ")
print("[+] Allowing All Incoming Connections ")
print("[+] PORT "+str(PORT))
print("[+] Waiting For Connection...")

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print('[+] Connected by ', addr)

key = str(input('[+] AES Pre-Shared-Key for the Connection : '))
hashed = hashlib.sha256(key.encode()).digest()
aes = pyaes.AES(hashed)

def verify_and_display(recv_dict):
    timestamp = recv_dict['timestamp']
    recv_hash = recv_dict['hash']
    message   = recv_dict['message']
    mess_hash = hashlib.sha256(str(message).encode('utf-8')).hexdigest()
    SET_LEN = 80
    if (mess_hash == recv_hash):
        tag = str('☑')
    else:
        tag = str('☒')
    spaces = SET_LEN - len(str(message)) - len('Received : ') - 1
    if spaces > 0 :
        space = ' '*spaces
        sentence = 'Received : ' + str(message) + space + tag + '  ' + timestamp
Exemplo n.º 21
0
except socket.error as e:
    print(str(e))
s.listen(1)

(connection, address) = s.accept()
data = connection.recv(100).decode("utf-8")
operation_mode = data
connection.close()

# Second connection, receive key from key_manager and decrypt it
(connection, address) = s.accept()
data = connection.recv(100).decode("utf-8")
connection.close()

# Decrypt the key
aes = pyaes.AES(crypto_functions.Kprime)
block_bytes = [ord(c) for c in data]
communication_key = aes.decrypt(block_bytes)

# Start using the key
communication_key = bytes(communication_key)
aes = pyaes.AES(communication_key)

# Start communicating securely with A
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((node_A_host, node_A_port))
# Send start message
s.send(bytes('Start', 'utf-8'))
crypto_text = ''
while True:
    data = s.recv(1024).decode('utf-8')
Exemplo n.º 22
0
class AES:
    """
    Class that servers as an interface to encrypt and decrypt
    text through the AES IGE mode.
    """

    @staticmethod
    def decrypt_ige(cipher_text, key, iv):
        """
        Decrypts the given text in 16-bytes blocks by using the
        given key and 32-bytes initialization vector.
        """
        if cryptg:
            return cryptg.decrypt_ige(cipher_text, key, iv)
        if libssl.decrypt_ige:
            return libssl.decrypt_ige(cipher_text, key, iv)

        iv1 = iv[: len(iv) // 2]
        iv2 = iv[len(iv) // 2 :]

        aes = pyaes.AES(key)

        plain_text = []
        blocks_count = len(cipher_text) // 16

        cipher_text_block = [0] * 16
        for block_index in range(blocks_count):
            for i in range(16):
                cipher_text_block[i] = cipher_text[block_index * 16 + i] ^ iv2[i]

            plain_text_block = aes.decrypt(cipher_text_block)

            for i in range(16):
                plain_text_block[i] ^= iv1[i]

            iv1 = cipher_text[block_index * 16 : block_index * 16 + 16]
            iv2 = plain_text_block

            plain_text.extend(plain_text_block)

        return bytes(plain_text)

    @staticmethod
    def encrypt_ige(plain_text, key, iv):
        """
        Encrypts the given text in 16-bytes blocks by using the
        given key and 32-bytes initialization vector.
        """
        if padding := len(plain_text) % 16:
            plain_text += os.urandom(16 - padding)

        if cryptg:
            return cryptg.encrypt_ige(plain_text, key, iv)
        if libssl.encrypt_ige:
            return libssl.encrypt_ige(plain_text, key, iv)

        iv1 = iv[: len(iv) // 2]
        iv2 = iv[len(iv) // 2 :]

        aes = pyaes.AES(key)

        cipher_text = []
        blocks_count = len(plain_text) // 16

        for block_index in range(blocks_count):
            plain_text_block = list(
                plain_text[block_index * 16 : block_index * 16 + 16]
            )
            for i in range(16):
                plain_text_block[i] ^= iv1[i]

            cipher_text_block = aes.encrypt(plain_text_block)

            for i in range(16):
                cipher_text_block[i] ^= iv2[i]

            iv1 = cipher_text_block
            iv2 = plain_text[block_index * 16 : block_index * 16 + 16]

            cipher_text.extend(cipher_text_block)

        return bytes(cipher_text)
Exemplo n.º 23
0
except socket.error as e:
    print(str(e))
s.listen(1)

(connection, address) = s.accept()
data = connection.recv(100).decode("utf-8")
connection.close()

# Send the key to B
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((node_B_host, node_B_port))
s.send(bytes(data, 'utf-8'))
s.close()

# Decrypt the key
aes = pyaes.AES(crypto_functions.Kprime)
block_bytes = [ord(c) for c in data]
communication_key = aes.decrypt(block_bytes)

# Start using the key
communication_key = bytes(communication_key)

# Wait for a secure connection from B
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.bind((own_host, own_port))
except socket.error as e:
    print(str(e))
s.listen(1)

(connection, address) = s.accept()
Exemplo n.º 24
0
 def __init__(self, key, iv):
     assert len(key) in AES.rounds_by_key_size
     self.iv = [iv[i] for i in range(len(iv))]
     self.aes = pyaes.AES(key)
Exemplo n.º 25
0
Arquivo: KM.py Projeto: Sabina99/SI
 def __init__(self, txt, key):
     self.key = key
     self.aes = pyaes.AES(self.key)
     self.len = len(txt)
Exemplo n.º 26
0
Arquivo: KM.py Projeto: Sabina99/SI
 def __init__(self, txt, key):
     self.key = key
     self.aes = pyaes.AES(self.key)
     self.lenght = len(txt)
     self.init_vec = list(np.random.randint(255, size=BLOCK_SIZE))
Exemplo n.º 27
0
def raw_decrypt(key, ciphertext):
    assert len(ciphertext) == 16

    aes = pyaes.AES(key)
    return aes.decrypt(ciphertext)
Exemplo n.º 28
0
B_host = own_host
B_port = 1234

operation_mode = None
communication_key = None

# Receive message from A
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.bind((own_host, own_port))
except socket.error as e:
    print(str(e))
s.listen(1)

(connection, address) = s.accept()
data = connection.recv(100).decode("utf-8")
operation_mode = data
connection.close()

# Generate key
aes = pyaes.AES(Kprime)
sending_key = safe_keygen()
encrypted_key = aes.encrypt(sending_key)
encrypted_key = ''.join([chr(i) for i in encrypted_key])

# send to A
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((A_host, A_port))
s.send(bytes(encrypted_key, 'utf-8'))
s.close()