Пример #1
0
    def aes_setup(self, session_key):
        # Load keys and define encrypt/decrypt functions
        # - for CTR mode, we have different counters in each direction, so need two instances
        # - count must start at zero, and increment in LSB for each block.
        import pyaes

        self.encrypt_request = pyaes.AESModeOfOperationCTR(session_key, pyaes.Counter(0)).encrypt
        self.decrypt_response = pyaes.AESModeOfOperationCTR(session_key, pyaes.Counter(0)).decrypt
Пример #2
0
 def encrypt(self, plain_text, key):
     try:
         iv = secrets.randbits(256)
         iv_vector = pyaes.Counter(iv)
         aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
         data = aes.encrypt(plain_text + ";;")
         hex = binascii.hexlify(data)
         return {'data':hex.decode("ASCII"),'iv':iv_vector.value}
     except Exception as ex:
         raise
Пример #3
0
def get_msgs(session, raw=False):
    sqs_c = boto3.client('sqs',
                         aws_access_key_id=session['accessKey'],
                         aws_secret_access_key=session['secretKey'],
                         aws_session_token=session['sessionToken'])
    msgs = []
    while True:
        print("Checking queue {0}".format(session['sqsUrl']))
        r = sqs_c.receive_message(QueueUrl=session['sqsUrl'],
                                  MaxNumberOfMessages=10)
        if 'Messages' not in r:
            break
        for m in r['Messages']:
            init_ctr, msg = m['Body'].split('|', 1)
            ctr = pyaes.Counter(initial_value=int(init_ctr))
            aes = pyaes.AESModeOfOperationCTR(base64.b64decode(
                session['aesKey']),
                                              counter=ctr)
            dec_m = aes.decrypt(base64.b64decode(msg))
            print("   Found message: {0}".format(dec_m))
            msgs.append(json.loads(dec_m))
            sqs_c.delete_message(QueueUrl=session['sqsUrl'],
                                 ReceiptHandle=m['ReceiptHandle'])
    if raw:
        return sorted(msgs)
    else:
        return sorted([x['msg'] for x in msgs])
Пример #4
0
def decrypt(cipherText, password):
    res = bytes(cipherText, 'utf-8')
    cipherByte = binascii.unhexlify(res)
    key = pbkdf2.PBKDF2(password, passwordSalt).read(32)
    aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
    originalByte = aes.decrypt(cipherByte)
    return originalByte.decode('utf-8')
Пример #5
0
def encrypt_data(plaintext):
    print('AES encryption key:', secret_key)
    iv = secrets.randbits(256)
    aes = pyaes.AESModeOfOperationCTR(secret_key, pyaes.Counter(iv))
    ciphertext = aes.encrypt(plaintext)
    print('Encrypted:', binascii.hexlify(ciphertext))
    return ciphertext, iv
Пример #6
0
    def decrypt(self, ciphertext, iv, key, algo="aes-256-cbc"):
        cipher_type = self._get_algo_cipher_type(algo)

        if cipher_type == "cbc":
            cipher = pyaes.AESModeOfOperationCBC(key, iv=iv)
        elif cipher_type == "ctr":
            # The IV is actually a counter, not an IV but it does almost the
            # same. Notice: pyaes always uses 1 as initial counter! Make sure
            # not to call pyaes directly.

            # We kinda do two conversions here: from byte array to int here, and
            # from int to byte array in pyaes internals. It's possible to fix that
            # but I didn't notice any performance changes so I'm keeping clean code.
            iv_int = 0
            for byte in iv:
                iv_int = (iv_int * 256) + byte
            counter = pyaes.Counter(iv_int)
            cipher = pyaes.AESModeOfOperationCTR(key, counter=counter)
        elif cipher_type == "cfb":
            # Change segment size from default 8 bytes to 16 bytes for OpenSSL
            # compatibility
            cipher = pyaes.AESModeOfOperationCFB(key, iv, segment_size=16)
        elif cipher_type == "ofb":
            cipher = pyaes.AESModeOfOperationOFB(key, iv)

        decrypter = pyaes.Decrypter(cipher)
        data = decrypter.feed(ciphertext)
        data += decrypter.feed()
        return data
Пример #7
0
def decryptAES(key, ciphertext):
    counter = pyaes.Counter(initial_value=5)
    aes = pyaes.AESModeOfOperationCTR(bytearray.fromhex(key), counter=counter)
    strCipherText = "".join([
        chr(int(ciphertext[x:x + 2], 16))
        for x in range(0, len(ciphertext), 2)
    ])
    return aes.decrypt(strCipherText)
Пример #8
0
 def encrypt(self, plaintext):  #AES data encryption
     aes = pyaes.AESModeOfOperationCTR(
         self.getKey(),
         pyaes.Counter(
             31129547035000047302952433967654195398124239844566322884172163637846056248223
         ))
     ciphertext = aes.encrypt(plaintext)
     return ciphertext
Пример #9
0
 def decrypt(self, enc):  #AES data decryption
     aes = pyaes.AESModeOfOperationCTR(
         self.getKey(),
         pyaes.Counter(
             31129547035000047302952433967654195398124239844566322884172163637846056248223
         ))
     decrypted = aes.decrypt(enc)
     return decrypted
Пример #10
0
def decrypt(iv, key, ciphertext):
    """
    Decrypt the ciphertext with the given key:
    plaintext = AES-256-CTR-Decrypt(ciphertext, key, iv)
    """
    aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
    decrypted = aes.decrypt(ciphertext)
    return decrypted
Пример #11
0
def encrypt(iv, key, plaintext):
    """
    Encrypt the plaintext with the given key:
    ciphertext = AES-256-CTR-Encrypt(plaintext, key, iv)
    """
    aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
    ciphertext = aes.encrypt(plaintext)
    return ciphertext
Пример #12
0
 def receiver_decrypt(self):
     start = datetime.now()
     self.decrypt_symmetric_key()
     data = self.cipher_text
     aes = pyaes.AESModeOfOperationCTR(self.decrypted_symmetric_key,
                                       pyaes.Counter(self.iv))
     original_msg = aes.decrypt(data)
     end = datetime.now()
     print("Time taken to decrypt: " + str(end - start))
Пример #13
0
 def sender_encrypt(self):
     path = input('Enter the file path: ')
     start = datetime.now()
     with open(path, 'rb') as input_file:
         self.plain_text = input_file.read()
         aes = pyaes.AESModeOfOperationCTR(self.key, pyaes.Counter(self.iv))
         self.cipher_text = aes.encrypt(self.plain_text)
     self.encrypt_symmetric_key()
     end = datetime.now()
     print("Time taken to encrypt: " + str(end - start))
def decrypt_aes256ctr(salt_iv: str, psw: str, enc: str) -> bytes:
    warnings.filterwarnings("ignore")
    data = kdf(password=psw,
               salt=salt_iv,
               desired_key_bytes=32 + 16,
               rounds=10)
    key, iv = data[:32], data[32:]
    iv = int.from_bytes(iv, "big")
    counter = pyaes.Counter(iv)
    aes = pyaes.AESModeOfOperationCTR(key, counter)
    return aes.decrypt(enc)
Пример #15
0
def test_crypto_unittest(sim_eval, sim_exec):
    # unit test for AES key generation from SDCard and master secret
    card = sim_exec(
        'import files; from h import b2a_hex; cs = files.CardSlot().__enter__(); RV.write(b2a_hex(cs.get_id_hash())); cs.__exit__()'
    )

    # known value for simulator, generally unknown on random SD cards
    assert card == '95a60b9ff0c944ec2c23a28e599f794e95bb376a451b6037b054f8230b405fb0'
    salt = a2b_hex(card)

    # read key simulator calculates
    key = sim_exec('''\
import files; from h import b2a_hex; \
from pwsave import PassphraseSaver; \
cs = files.CardSlot().__enter__(); \
p=PassphraseSaver(); p._calc_key(cs); RV.write(b2a_hex(p.key)); cs.__exit__()'''
                   )

    assert len(key) == 64
    #assert key == '234af2aa2ab43af83667dfc6e11d08223e0f486ef34539b41a045dd9eb3ea664'

    from pycoin.key.BIP32Node import BIP32Node
    from pycoin.encoding import from_bytes_32, to_bytes_32
    from hashlib import sha256

    mk = BIP32Node.from_wallet_key(simulator_fixed_xprv)

    sk = mk.subkey_for_path('2147431408p/0p')

    md = sha256()
    md.update(salt)
    md.update(to_bytes_32(sk.secret_exponent()))
    md.update(salt)

    expect = sha256(md.digest()).hexdigest()

    assert expect == key

    # check that key works for decrypt / that the file was actually encrypted

    with open(SIM_FNAME, 'rb') as fd:
        raw = fd.read()

    import pyaes
    d = pyaes.AESModeOfOperationCTR(a2b_hex(expect), pyaes.Counter(0)).decrypt
    txt = str(bytearray(d(raw)), 'utf8')

    print(txt)
    assert txt[0] == '[' and txt[-1] == ']'
    import json
    j = json.loads(txt)
    assert isinstance(j, list)
    assert j[0]['pw']
    assert j[0]['xfp']
Пример #16
0
def encryption(p):
    password = "******"
    passwordSalt = os.urandom(16)
    key = pbkdf2.PBKDF2(password, passwordSalt).read(32)
    p1 = []
    p1.clear()
    iv = secrets.randbits(256)
    aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
    ciphertext = aes.encrypt(p)
    p1.append(ciphertext), p1.append(key), p1.append(iv)
    return p1
Пример #17
0
def _encryption(p):
    password = "******"
    passwordSalt = os.urandom(16)
    key = pbkdf2.PBKDF2(password, passwordSalt).read(16)

    m = []
    m.clear()
    iv = secrets.randbits(128)
    aes = pyaes.AESModeOfOperationCTR(key, pyaes.Counter(iv))
    ciphertext = aes.encrypt(p)
    m.append(ciphertext), m.append(key), m.append(iv)
    return m
Пример #18
0
def aes_decrypt(key, iv_ciphertext):
    """AES decrypt arbitrary length message. (uses CTR mode)

    Returns plaintext, which is 16 bytes shorter than iv_ciphertext.

    iv_ciphertext must be >= 16 bytes. (i.e., needs to have 16 byte IV)
    """
    assert len(iv_ciphertext) >= 16
    #WEAKNESS -- unknown if pyaes is constant time
    iv = iv_ciphertext[:16]
    ciphertext = iv_ciphertext[16:]
    counter = pyaes.Counter(int.from_bytes(iv, 'big'))
    cipher = pyaes.AESModeOfOperationCTR(key, counter)
    return cipher.decrypt(ciphertext)
Пример #19
0
async def handle_handshake(reader, writer):
    handshake = await reader.readexactly(64)

    for user in USERS:
        secret = bytes.fromhex(USERS[user])

        dec_prekey_and_iv = handshake[SKIP_LEN:SKIP_LEN + PREKEY_LEN + IV_LEN]
        dec_prekey, dec_iv = dec_prekey_and_iv[:PREKEY_LEN], dec_prekey_and_iv[
            PREKEY_LEN:]
        dec_key = hashlib.sha256(dec_prekey + secret).digest()
        dec_ctr = pyaes.Counter(int.from_bytes(dec_iv, "big"))
        decryptor = pyaes.AESModeOfOperationCTR(dec_key, dec_ctr)

        enc_prekey_and_iv = handshake[SKIP_LEN:SKIP_LEN + PREKEY_LEN +
                                      IV_LEN][::-1]
        enc_prekey, enc_iv = enc_prekey_and_iv[:PREKEY_LEN], enc_prekey_and_iv[
            PREKEY_LEN:]
        enc_key = hashlib.sha256(enc_prekey + secret).digest()
        enc_ctr = pyaes.Counter(int.from_bytes(enc_iv, "big"))
        encryptor = pyaes.AESModeOfOperationCTR(enc_key, enc_ctr)

        decrypted = decryptor.decrypt(handshake)

        MAGIC_VAL = b'\xef\xef\xef\xef'
        check_val = decrypted[56:60]
        if check_val != MAGIC_VAL:
            continue

        dc_idx = int.from_bytes(decrypted[60:62], "little") - 1

        if dc_idx < 0 or dc_idx >= len(TG_DATACENTERS):
            continue

        dc = TG_DATACENTERS[dc_idx]

        return encryptor, decryptor, user, dc, enc_key + enc_iv
    return False
Пример #20
0
async def do_handshake(dc, dec_key_and_iv=None):
    try:
        reader_tgt, writer_tgt = await asyncio.open_connection(
            dc, TG_DATACENTER_PORT)
    except ConnectionRefusedError as E:
        return False
    except OSError as E:
        return False

    rnd = bytearray([random.randrange(0, 256) for i in range(64)])
    rnd[56] = 0xef
    rnd[57] = 0xef
    rnd[58] = 0xef
    rnd[59] = 0xef

    if dec_key_and_iv:
        rnd[SKIP_LEN:SKIP_LEN + KEY_LEN + IV_LEN] = dec_key_and_iv[::-1]

    rnd = bytes(rnd)

    dec_key_and_iv = rnd[SKIP_LEN:SKIP_LEN + KEY_LEN + IV_LEN][::-1]
    dec_key, dec_iv = dec_key_and_iv[:KEY_LEN], dec_key_and_iv[KEY_LEN:]
    dec_ctr = pyaes.Counter(int.from_bytes(dec_iv, "big"))
    decryptor = pyaes.AESModeOfOperationCTR(dec_key, dec_ctr)

    enc_key_and_iv = rnd[SKIP_LEN:SKIP_LEN + KEY_LEN + IV_LEN]
    enc_key, enc_iv = enc_key_and_iv[:KEY_LEN], enc_key_and_iv[KEY_LEN:]
    enc_ctr = pyaes.Counter(int.from_bytes(enc_iv, "big"))
    encryptor = pyaes.AESModeOfOperationCTR(enc_key, enc_ctr)

    rnd_enc = rnd[:56] + encryptor.encrypt(rnd)[56:]

    writer_tgt.write(rnd_enc)
    await writer_tgt.drain()

    return encryptor, decryptor, reader_tgt, writer_tgt
Пример #21
0
def aes_encrypt(key, plaintext, iv=None):
    """AES encrypt arbitrary length message. (uses CTR mode with big-endian increment)

    Returns iv_ciphertext which is 16 bytes longer than the input plaintext.

    If iv not supplied, uses random 16 bytes.
    Generally you should not provide iv (reuse of iv on two different messages will leak plaintext!).
    """
    #WEAKNESS -- unknown if pyaes is constant time
    if iv is None:
        iv = token_bytes(16)
    else:
        assert len(iv) == 16
    counter = pyaes.Counter(int.from_bytes(iv, 'big'))
    cipher = pyaes.AESModeOfOperationCTR(key, counter)
    return iv + cipher.encrypt(plaintext)
Пример #22
0
    def decrypt(self, passwordc, mode, key, iv):
        self.passwordc = passwordc
        if (mode == '1'):
            counter = pyaes.Counter(initial_value=100)
            aes = pyaes.AESModeOfOperationCTR(key, counter=counter)
            passwordd = aes.decrypt(passwordc)
            return passwordd

        elif (mode == '2'):
            aes = pyaes.AESModeOfOperationCBC(key, iv=iv)
            passwordd = aes.decrypt(passwordc)
            return passwordd

        elif (mode == '3'):
            aes = pyaes.AESModeOfOperationECB(key)
            passwordd = aes.decrypt(passwordc)
            return passwordd
Пример #23
0
    def encrypt(self, password, mode, key, iv):
        self.password = password
        if (mode == '1'):
            counter = pyaes.Counter(initial_value=100)
            aes = pyaes.AESModeOfOperationCTR(key, counter=counter)
            passwordc = aes.encrypt(self.password)
            return passwordc

        elif (mode == '2'):
            aes = pyaes.AESModeOfOperationCBC(key, iv=iv)
            passpad = self._pad(password)
            passwordc = aes.encrypt(passpad)
            return passwordc

        elif (mode == '3'):
            aes = pyaes.AESModeOfOperationECB(key)
            passpad = self._pad(password)
            passwordc = aes.encrypt(passpad)
            return passwordc

        else:
            print 'Please select the proper mode of encryption!'
Пример #24
0
 def create_aes_ctr(key, iv):
     ctr = pyaes.Counter(iv)
     return pyaes.AESModeOfOperationCTR(key, ctr)
Пример #25
0
def decryption(c, k, iv):
    aes = pyaes.AESModeOfOperationCTR(k, pyaes.Counter(iv))
    decrypted = aes.decrypt(c)
    return decrypted
Пример #26
0
iv = iv.encode('utf-8')

aes = pyaes.AESModeOfOperationOFB(key, iv=iv)
plaintext = "Text may be any length you wish, no padding is required"
ciphertext = aes.encrypt(plaintext)

#repr(ciphertext)
logging.info(ciphertext)
print(ciphertext)

# The counter mode of operation maintains state, so decryption requires
# a new instance be created
#aes = pyaes.AESModeOfOperationCTR(key)
#aes = pyaes.AESModeOfOperationCFB(key, iv = iv, segment_size = 8)
aes = pyaes.AESModeOfOperationOFB(key, iv=iv)
decrypted = aes.decrypt(ciphertext)
logging.info("Dedecrypted Message: %s", decrypted)
# True
if decrypted == plaintext:

    print(decrypted == plaintext)

# To use a custom initial value
counter = pyaes.Counter(initial_value=100)
aes = pyaes.AESModeOfOperationCTR(key, counter=counter)
ciphertext = aes.encrypt(plaintext)

# '''WZ\x844\x02\xbfoY\x1f\x12\xa6\xce\x03\x82Ei)\xf6\x97mX\x86\xe3\x9d
#    _1\xdd\xbd\x87\xb5\xccEM_4\x01$\xa6\x81\x0b\xd5\x04\xd7Al\x07\xe5
#    \xb2\x0e\\\x0f\x00\x13,\x07'''
#print repr(ciphertext)
Пример #27
0
server = config.get('host', 'server')
port = config.getint('host', 'port')
keepalive = config.getint('host', 'keep-alive')
secretkey = config.get('key', 'key')
clientid = config.get('credential', 'client')
#server = "192.168.1.158"


def on_connect(client, userdata, flags, rc):
    print("Connected with Code :" + str(rc))
    client.subscribe(topic)


key = secretkey
key = key.encode('utf-8')
counter = pyaes.Counter(initial_value=0)
aes = pyaes.AESModeOfOperationCTR(key, counter=counter)


def on_message(client, userdata, msg):
    client = mqtt.Client()

    #start process exec
    start = time.clock()

    msg = msg.payload

    #start decrypption time
    startDS = time.clock()

    decrypted = aes.decrypt(msg).decode('utf-8')
Пример #28
0
def encryptAES(key, plaintext):
    counter = pyaes.Counter(initial_value=5)
    aes = pyaes.AESModeOfOperationCTR(bytearray.fromhex(key), counter=counter)
    ciphertext = aes.encrypt(plaintext)
    return binascii.hexlify(ciphertext)
Пример #29
0
                              128).to_bytes(0x10, byteorder='big')
                    print_v('Normal key:',
                            binascii.hexlify(key).decode('utf-8').upper())

        print('Converting {} ({})...'.format(
            rom_file[1], 'ignore encryption' if ignore_encryption else
            ('zerokey encrypted' if zerokey_encrypted else
             ('encrypted' if encrypted else 'decrypted'))))

        # Game Executable fist-half ExtHeader
        print_v('\nVerifying ExtHeader...')
        rom.seek(game_cxi_offset + 0x200)
        extheader = rom.read(0x400)
        if encrypted:
            print_v('Decrypting ExtHeader...')
            ctr_extheader = pyaes.Counter(initial_value=ctr_extheader_v)
            cipher_extheader = pyaes.AESModeOfOperationCTR(
                key, counter=ctr_extheader)
            extheader = cipher_extheader.decrypt(extheader)
        extheader_hash = hashlib.sha256(extheader).digest()
        rom.seek(0x4160)
        ncch_extheader_hash = rom.read(0x20)
        if extheader_hash != ncch_extheader_hash:
            print(
                'This file may be corrupt (invalid ExtHeader hash). '
                'If you are certain that the rom is decrypted, use --ignore-encryption'
            )
            if ignore_bad_hashes:
                print('Converting anyway because --ignore-bad-hashes was '
                      'passed.')
            else:
Пример #30
0
 def decrypt(self, ciphertext):
     counter = pyaes.Counter(initial_value=self.decrypt_counter)
     aes = pyaes.AESModeOfOperationCTR(self.key, counter=counter)
     self.decrypt_counter += len(ciphertext)
     return aes.decrypt(ciphertext)