Ejemplo n.º 1
0
def ecb_oracle(data):
    data += ("""
        Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg
        aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq
        dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg
        YnkK
        """.decode('base64'))
    data = pad(data)
    return AES_ECB_encrypt(data, oracle_key)
Ejemplo n.º 2
0
def detect_image(model, image, mean, std, threshold=0.4):
    image = common.pad(image)
    image = ((image / 255 - mean) / std).astype(np.float32)
    image = image.transpose(2, 0, 1)
    image = torch.from_numpy(image).unsqueeze(0).cuda()
    center, box, landmark = model(image)

    center = center.sigmoid()
    box = torch.exp(box)
    return detect_images_giou_with_netout(center, box, landmark, threshold)
Ejemplo n.º 3
0
def main():
    # 0123456789abcdef0123456789abcdef0123456789abcdef
    # email=XXXXXXXXXXXXX&uid=10&role=user <--------------------- (1)
    # email=XXXXXXXXXXadmin...........&uid=10&role=user <-------- (2)
    # email=XXXXXXXXXXXXX&uid=10&role=admin........... <--------- (attack)

    from common import pad

    r1 = profile_for('XXXXXXXXXXXXX')
    r2 = profile_for('XXXXXXXXXX' + pad('admin'))

    attack = r1[:32] + r2[16:32]

    print user_profile(attack)
Ejemplo n.º 4
0
def process():
    if 'file' not in request.files:
        flash('Choose file')
        return redirect(request.url)
    file = request.files['file']
    if file.filename == '':
        flash('Choose file')
        return redirect(request.url)
    if file and (file.filename.endswith('.png')
                 or file.filename.endswith('.jpg')
                 or file.filename.endswith('.jpeg')):
        filename = secure_filename(file.filename)
        path = os.path.join('static', filename)
        file.save(path)
        blur_orig = imageio.imread(path, pilmode='RGB')
        blur = [blur_orig]

        blur[0], pad_width = common.pad(blur[0], divisor=2**(n_scales - 1))
        blur = common.generate_pyramid(*blur, n_scales=n_scales)
        blur = common.np2tensor(*blur)[0]
        for i in range(len(blur)):
            blur[i] = blur[i].unsqueeze(0)
        sharp = gen(blur)[-1]
        sharp, _ = common.pad(sharp, pad_width=pad_width, negative=True)
        sharp_np = sharp[0].clamp(0, 255).round_().cpu().detach().numpy()
        sharp_np = np.moveaxis(sharp_np, 0, -1)

        imageio.imwrite('static/sharp_' + str(k) + '_' + filename, sharp_np)
        imageio.imwrite('static/blur_' + str(k) + '_' + filename, blur_orig)
        os.remove(path)
        return render_template('index.html',
                               sharp='sharp_' + str(k) + '_' + filename,
                               blur='blur_' + str(k) + '_' + filename)
    else:
        flash('Allowed image types are -> png, jpg, jpeg')
        return redirect(request.url)
Ejemplo n.º 5
0
def encryption_oracle():
    data = ("""
        MDAwMDAwTm93IHRoYXQgdGhlIHBhcnR5IGlzIGp1bXBpbmc=
        MDAwMDAxV2l0aCB0aGUgYmFzcyBraWNrZWQgaW4gYW5kIHRoZSBWZWdhJ3MgYXJlIHB1bXBpbic=
        MDAwMDAyUXVpY2sgdG8gdGhlIHBvaW50LCB0byB0aGUgcG9pbnQsIG5vIGZha2luZw==
        MDAwMDAzQ29va2luZyBNQydzIGxpa2UgYSBwb3VuZCBvZiBiYWNvbg==
        MDAwMDA0QnVybmluZyAnZW0sIGlmIHlvdSBhaW4ndCBxdWljayBhbmQgbmltYmxl
        MDAwMDA1SSBnbyBjcmF6eSB3aGVuIEkgaGVhciBhIGN5bWJhbA==
        MDAwMDA2QW5kIGEgaGlnaCBoYXQgd2l0aCBhIHNvdXBlZCB1cCB0ZW1wbw==
        MDAwMDA3SSdtIG9uIGEgcm9sbCwgaXQncyB0aW1lIHRvIGdvIHNvbG8=
        MDAwMDA4b2xsaW4nIGluIG15IGZpdmUgcG9pbnQgb2g=
        MDAwMDA5aXRoIG15IHJhZy10b3AgZG93biBzbyBteSBoYWlyIGNhbiBibG93
        """).split()
    iv = randstr(16)
    data = choice(data).decode('base64')
    return (iv, AES_CBC_encrypt(pad(data), oracle_key, iv))
Ejemplo n.º 6
0
def encryption_oracle(data):
    global ground_truth  # Used only for verification
    from random import randint

    def randstr(n):
        return ''.join(chr(randint(0, 255)) for _ in range(n))

    data = randstr(randint(5, 10)) + data + randstr(randint(5, 10))
    data = pad(data)

    if randint(0, 1) == 0:
        ground_truth = 'ECB'
        return AES_ECB_encrypt(data, randstr(16))
    else:
        ground_truth = 'CBC'
        return AES_CBC_encrypt(data, randstr(16), randstr(16))
Ejemplo n.º 7
0
def detect(model,
           image,
           threshold=0.4,
           nms_iou=0.5) -> typing.List[common.BBox]:
    mean = [0.408, 0.447, 0.47]
    std = [0.289, 0.274, 0.278]

    image = common.pad(image)
    image = ((image / 255.0 - mean) / std).astype(np.float32)
    image = image.transpose(2, 0, 1)

    torch_image = torch.from_numpy(image)[None]
    if HAS_CUDA:
        torch_image = torch_image.cuda()

    hm, box, landmark = model(torch_image)
    hm_pool = F.max_pool2d(hm, 3, 1, 1)
    scores, indices = ((hm == hm_pool).float() * hm).view(1,
                                                          -1).cpu().topk(1000)
    hm_height, hm_width = hm.shape[2:]

    scores = scores.squeeze()
    indices = indices.squeeze()
    ys = list((indices / hm_width).int().data.numpy())
    xs = list((indices % hm_width).int().data.numpy())
    scores = list(scores.data.numpy())
    box = box.cpu().squeeze().data.numpy()
    landmark = landmark.cpu().squeeze().data.numpy()

    stride = 4
    objs = []
    for cx, cy, score in zip(xs, ys, scores):
        if score < threshold:
            break

        x, y, r, b = box[:, cy, cx]
        xyrb = (np.array([cx, cy, cx, cy]) + [-x, -y, r, b]) * stride
        x5y5 = landmark[:, cy, cx]
        x5y5 = (common.exp(x5y5 * 4) + ([cx] * 5 + [cy] * 5)) * stride
        box_landmark = list(zip(x5y5[:5], x5y5[5:]))
        objs.append(
            common.BBox(0, xyrb=xyrb, score=score, landmark=box_landmark))
    return nms(objs, iou=nms_iou)
Ejemplo n.º 8
0
def create_comparison_state(image, position, radius=5.0, snr=20,
        method='constrained-cubic', extrapad=2, zscale=1.0):
    """
    Take a platonic image and position and create a state which we can
    use to sample the error for peri. Also return the blurred platonic
    image so we can vary the noise on it later
    """
    # first pad the image slightly since they are pretty small
    image = common.pad(image, extrapad, 0)

    # place that into a new image at the expected parameters
    s = init.create_single_particle_state(imsize=np.array(image.shape), sigma=1.0/snr,
            radius=radius, psfargs={'params': np.array([2.0, 1.0, 3.0]), 'error': 1e-6, 'threads': 2},
            objargs={'method': method}, stateargs={'sigmapad': False, 'pad': 4, 'zscale': zscale})
    s.obj.pos[0] = position + s.pad + extrapad
    s.reset()
    s.model_to_true_image()

    timage = 1-np.pad(image, s.pad, mode='constant', constant_values=0)
    timage = s.psf.execute(timage)
    return s, timage[s.inner]
Ejemplo n.º 9
0
start = time.time()
logger.debug('stretching key...')
hashed_password = pyscrypt.hash(password=pwd, salt=salt, N=scrypt_N, r=scrypt_r, p=scrypt_p, dkLen = 32)
hashed_hex = hashed_password.encode('hex')
elapsed = time.time() - start
logger.debug('scrypt(N={},r={},p={}) took {:.1f} seconds'.format(scrypt_N, scrypt_r, scrypt_p, elapsed))
logger.debug('HASH length {} bytes'.format(len(hashed_password)))


# AES key
aes_key = hashed_hex[:32]
logger.debug('KEY length {} bytes'.format(len(aes_key)))


# pad input text
payload = pad(privkey, 16)
logger.debug('DATA length {:,} bytes'.format(len(payload), payload))


# AES encrypt private key with hashed password
e = AES.new(aes_key, AES.MODE_CBC, iv)
ciphertext = e.encrypt(payload)
logger.debug('CIPHERTEXT length {} bytes'.format(len(ciphertext)))


# sanity check: decrypt back again
decryption_suite = AES.new(aes_key, AES.MODE_CBC, iv)
plain_text = decryption_suite.decrypt(ciphertext)
if plain_text == payload:
    logger.debug('DECRYPTION sanity check passed')
else:
Ejemplo n.º 10
0
def profile_for(email):
    from common import AES_ECB_encrypt, pad
    email = email.replace('=', '').replace('&', '')
    profile = 'email=' + email + '&uid=10&role=user'
    return AES_ECB_encrypt(pad(profile), oracle_key)
Ejemplo n.º 11
0
    ]
    reply_indices = [index for index in reply_indices if index > -1]
    if len(reply_indices) > 0:  # remove older messages, signatures, etc.
        text = text[:min(reply_indices) - 5]
    lines = text.split('\n')
    non_quote_lines = [line for line in lines
                       if not line.startswith('>')]  # remove quotes
    text = '\n'.join(non_quote_lines)
    for name in names:  # remove own name as indicator for gender (e.g. in signature)
        if len(name) > 2:
            text = sub(name, '', text, flags=IGNORECASE)
    text = text.replace(
        '?', ''
    )  # replace question mark, as it is also used for unknown characters and redacted text
    encoding = tokenize(text)
    if encoding.shape[0] <= min_sequence_length:
        continue
    if encoding.shape[0] < sequence_length:
        encoding = pad(encoding, sequence_length)
    x.append(encoding[:sequence_length])
    label = 1 if 'female' in gender else 0
    y.append(label)
    checksums.append(checksum)

x = np.vstack(x)
y = np.array(y)

makedirs(out_dir, exist_ok=True)
np.save(join(out_dir, 'x'), x)
np.save(join(out_dir, 'y'), y)
Ejemplo n.º 12
0
def encryption_oracle(data):
    data = data.replace(';', '').replace('=', '')
    data = "comment1=cooking%20MCs;userdata=" + data
    data = data + ";comment2=%20like%20a%20pound%20of%20bacon"
    data = pad(data)
    return AES_CBC_encrypt(data, oracle_key, oracle_iv)
Ejemplo n.º 13
0

mean = [0.408, 0.447, 0.47]
std = [0.289, 0.274, 0.278]

trial_name = "small-H-dense-wide64-UCBA-keep12-noext-ignoresmall2"
jobdir = f"jobs/{trial_name}"

image = common.imread("imgs/selfie.jpg")
model = DBFace(has_landmark=True, wide=64, has_ext=False, upmode="UCBA")
model.load(f"{jobdir}/models/150.pth")
model.eval()
model.cuda()

# preprocess
image = common.pad(image)
image = ((image / 255 - mean) / std).astype(np.float32)
image = image.transpose(2, 0, 1)
image = torch.from_numpy(image).unsqueeze(0).cuda()

# pytorch
center, box, landmark = model(image)
center = center.sigmoid()
box = torch.exp(box)
center = F.max_pool2d(center, kernel_size=3, padding=1, stride=1)

# onnxruntime
ort_session = onnxruntime.InferenceSession(f"{jobdir}/model.onnx")


def to_numpy(tensor):
Ejemplo n.º 14
0
from common import pad

print repr(pad("YELLOW SUBMARINE", 20))