Пример #1
0
def decrypt(ciphertext, key, iv):
    """Decrypts the data using specified key and IV

    Args:
        ciphertext (str): The base64-encoded data to be AES-256 decrypted
        key (str): The base64-encoded AES-256 key to decrypt with
        iv (str): The base64-encoded IV to decrypt with

    Returns: msg in raw form
    """
    assert isinstance(ciphertext, str)
    assert isinstance(key, str)
    assert isinstance(iv, str)
    ciphertext_raw = common.b64decode(ciphertext)
    key_raw = common.b64decode(key)
    iv_raw = common.b64decode(iv)

    assert len(key_raw) == 32  #AES-256

    #IV : byte string
    #...
    #For all other modes, it must be `block_size` bytes longs.
    assert len(iv_raw) == AES.block_size

    cipher = AES.new(key_raw, AES.MODE_CBC, iv_raw)
    padded_msg = cipher.decrypt(ciphertext_raw)
    msg = unpad(padded_msg)
    return msg
def get_target():
        global key
        IV = common.randbytes(16)
        text = common.b64decode(random.choice(choices))

        ct = common.aes_cbc_encrypt(text, key, IV)
        return ct, IV
Пример #3
0
def main():
        if len(sys.argv) < 3:
                key = SAMPLE_KEY
                filename = SAMPLE_FILENAME
        else:
                key = sys.argv[1]
                filename = sys.argv[2]

        f = open(filename, "r")
        ciphertext = ""
        for line in f:
                ciphertext += common.b64decode(line.rstrip())

        print common.aes_cbc_decrypt(ciphertext, key, "\x00" * 16)
        
        
        if False:
                for _ in range(1000):
                        key = common.randbytes(16)
                        pt = common.randbytes(random.randint(1, 64))
                        iv = common.randbytes(16)

                        AFTER = binascii.hexlify(common.aes_cbc_decrypt(common.aes_cbc_encrypt(pt, key, iv), key, iv))

                        PT = binascii.hexlify(common.pkcs7_pad(pt, len(pt) + (16 - (len(pt) % 16))))

                        print PT == AFTER
def get_target():
    global key
    IV = common.randbytes(16)
    text = common.b64decode(random.choice(choices))

    ct = common.aes_cbc_encrypt(text, key, IV)
    return ct, IV
def setup():
        global ct_list
        global KEY

        KEY = common.randbytes(16)
        
        for p in pt_encoded:
                ct_list.append(common.aes_ctr_encrypt(common.b64decode(p), KEY, NONCE))
Пример #6
0
 def test_ss(self):
     # ret = requests.get('https://ssrshare.xyz/freessr/').text
     # ss_content = base64.b64decode(ret).decode()
     # ss_list = ss_content.split()
     ss_0 = 'ssr://NDUuNzkuOTkuNTI6MTA0MTg6b3JpZ2luOmFlcy0yNTYtY2ZiOnBsYWluOk5USXdabUk1T1RCaE1UWTNPV0V6TldJMVptWTJOVGN3WldJLz9vYmZzcGFyYW09JnJlbWFya3M9NTc2TzVadTk1WXFnNVlpcDU2YVA1YkM4NUxxYTViZWU2TFM1NVlpcDZKS1omZ3JvdXA9VTFOU1UwaEJVa1V1UTA5Tg'
     params = ss_0.split('ssr://')[1]
     params = b64decode(params)
     params = params.split(':')
     print(params)
     ip = params[0]
     port = params[1]
     big_o = params[2]
     small_o = params[4]
     method = params[3]
     parse_res = urlparse(params[5])
     path = parse_res.path.split('/')[0]
     password = b64decode(path)
def setup():
    global ct_list
    global KEY

    KEY = common.randbytes(16)

    for p in pt_encoded:
        ct_list.append(common.aes_ctr_encrypt(common.b64decode(p), KEY, NONCE))
Пример #8
0
def process_store(handler, arguments, db_con=None):
    """Process a request to store a key/val pair in db

    Returns: None
    """
    assert isinstance(handler, BaseHTTPServer.BaseHTTPRequestHandler)
    assert isinstance(arguments, dict)
    assert isinstance(db_con, datastore.DatabaseConnection) or db_con is None

    if db_con is None:
        try:
            db_con = datastore.DatabaseConnection()
        except datastore.DatabaseReadError:
            return handler.server_error('Unable to connect to database.')

    #ensure required args are present
    for required_arg in STORE_REQUIRED_ARGS:
        if required_arg not in arguments:
            return handler.invalid_request(
                "Missing argument '{0}' from arguments".format(required_arg))

    #handle URL encoding
    for key, val_list in arguments.items():
        val = val_list[0]  #only use first value for specified GET param
        arguments[key] = urllib.unquote(val).decode('utf8')

        if DEBUG_MODE:
            print "DEBUG: URL params: {0}={1}".format(key, val)

    #validate args
    try:
        arguments['app_id'] = str(arguments['app_id'])
        common.b64decode(arguments['app_id'])
        assert arguments['app_id'] != ''
        arguments['app_secret'] = str(arguments['app_secret'])
        common.b64decode(arguments['app_secret'])
        assert arguments['app_id'] != ''
        arguments['key'] = str(arguments['key'])
        arguments['value'] = str(arguments['value'])
    except (AssertionError, TypeError), err:
        if DEBUG_MODE:
            print 'One of the arguments failed validation: {0}'.format(err)
        handler.invalid_request('Invalid app_id or app_secret')
def setup():
    global ct_list
    global KEY

    KEY = common.randbytes(16)

    f = open(INPATH, "r")
    for line in f:
        ct_list.append(
            common.aes_ctr_encrypt(common.b64decode(line.rstrip()), KEY,
                                   NONCE))
def main():
        ct = aes_ctr_encrypt("HELLO" * 50, "YELLOW SUBMARINE", 0)
        pt = aes_ctr_decrypt(ct, "YELLOW SUBMARINE", 0)
        print aes_ctr_decrypt(common.b64decode(target), "YELLOW SUBMARINE", 0)

        for _ in range(100):
                # print "boop"
                key = common.randbytes(16)
                nonce = random.randint(0, 2**64 - 1)
                pt = common.randbytes(random.randint(3, 1000))
                ct = aes_ctr_encrypt(pt, key, nonce)
                if pt != aes_ctr_decrypt(ct, key, nonce):
                        print "mismatch: pt = %s, ct = %s, key = %s, nonce = %d" % (binascii.hexlify(pt), binascii.hexlify(ct), binascii.hexlify(key), nonce)
                        break
Пример #11
0
def encrypt(data, key, iv=None):
    """Encrypts the data using specified key and IV (specified or random)

    Args:
        data: The data to be encrypted in raw form
        key (str): The base64-encoded key to use for AES-256 encryption
        iv (Optional[str]): If specified, the base64-encoed iv used for AES-256
            encryption. If not specified, a random one is generated.


    Returns: (iv, ciphertext) where both IV and ciphertext are base64-encoded
    strings.
    """
    assert isinstance(key, str)
    assert isinstance(iv, str) or iv is None
    key_raw = common.b64decode(key)
    assert len(key_raw) == 32  #AES-256

    iv_raw = None
    if iv is None:
        #IV : byte string
        #...
        #For all other modes, it must be `block_size` bytes long.
        iv_raw = os.urandom(AES.block_size)
        iv = common.b64encode(iv_raw)
    else:
        assert isinstance(iv, str)
        iv_raw = common.b64decode(iv)
        assert len(iv_raw) == AES.block_size

    padded = pad(
        str(data))  #defend known-plaintext attacks and length analysis

    cipher = AES.new(key_raw, AES.MODE_CBC, iv_raw)
    ciphertext_raw = cipher.encrypt(padded)
    ciphertext = common.b64encode(ciphertext_raw)
    return (iv, ciphertext)
Пример #12
0
def get_value(key, app_id=None, app_secret=None):
    """Fetch configuration value stored for key

    Args:
        key (str): The plaintext key that you want to look up
        app_id (Optional[str]): If specified, the base64-encoded id assigned
            to the app that wants to query its data
        app_secret (Optional[str]): If specified, the base64-encoded secret
            assigned to the app that wants to query its data. This is a
            decryption key.

    Raises: KeyNotStoredAndNoFallbackError
    """
    assert isinstance(key, str)
    if app_id is not None and app_secret is not None:
        assert isinstance(app_id, str)
        assert isinstance(app_secret, str)
        common.b64decode(app_id)
        common.b64decode(app_secret)

        with datastore.DatabaseConnection() as db_con:
            try:
                return db_con.get_key_val(app_id, app_secret, key)
            except datastore.DecryptionFailError:
                pass

    #try fallback
    if key in KEY_FALLBACKS.keys():
        val = os.getenv(KEY_FALLBACKS[key], None)
        if val is not None:
            return val
    err_msg = "Unable to acquire value for '{0}'".format(key)
    if key in KEY_FALLBACKS.keys():
        err_msg = ''.join([err_msg,
                           ' (set environment variable {0})'.format(KEY_FALLBACKS[key])])
    raise KeyNotStoredAndNoFallbackError(err_msg)
Пример #13
0
def main():
    ct = aes_ctr_encrypt("HELLO" * 50, "YELLOW SUBMARINE", 0)
    pt = aes_ctr_decrypt(ct, "YELLOW SUBMARINE", 0)
    print aes_ctr_decrypt(common.b64decode(target), "YELLOW SUBMARINE", 0)

    for _ in range(100):
        # print "boop"
        key = common.randbytes(16)
        nonce = random.randint(0, 2**64 - 1)
        pt = common.randbytes(random.randint(3, 1000))
        ct = aes_ctr_encrypt(pt, key, nonce)
        if pt != aes_ctr_decrypt(ct, key, nonce):
            print "mismatch: pt = %s, ct = %s, key = %s, nonce = %d" % (
                binascii.hexlify(pt), binascii.hexlify(ct),
                binascii.hexlify(key), nonce)
            break
Пример #14
0
def main():
        if len(sys.argv) < 3:
                key = SAMPLE_KEY
                filename = SAMPLE_FILENAME
        else:
                key = sys.argv[1]
                filename = sys.argv[2]
        f = open(filename, "r")
        ciphertext = ""
        for line in f:
                ciphertext += common.b64decode(line.rstrip())

        plaintext = ""
        for i in range(0, len(ciphertext), 16):
                plaintext += common.aes_decrypt_block(ciphertext[i:i+16], key)

        print plaintext
def main():
        if len(sys.argv) < 2:
                f = open (SAMPLE_FILENAME, "r")
        else:
                f = open (sys.argv[1], "r")

        ct = ""
        for line in f:
                ct += line.rstrip()

        ct = common.b64decode(ct)

        assert common.hamming_distance("this is a test", "wokka wokka!!!") == 37

        pt, key = common.break_repeating_xor(ct)
        print pt
        print key
def encryption_oracle(pt):
        global key
        return common.aes_ecb_encrypt(common.randbytes(random.randint(2, 50)) + pt + common.b64decode(TARGET_PT), key)
def encryption_oracle(pt):
        global key
        return common.aes_ecb_encrypt(pt + common.b64decode(TARGET_PT), key)
def encryption_oracle(pt):
    global key
    return common.aes_ecb_encrypt(pt + common.b64decode(TARGET_PT), key)
def encryption_oracle(pt):
    global key
    return common.aes_ecb_encrypt(
        common.randbytes(random.randint(2, 50)) + pt +
        common.b64decode(TARGET_PT), key)