def rsa_echo(self):
        now = int(time.time())

        ptext = str({"time": now, "social": self.social}).encode()
        ctext = rsa(ptext, self.remote_pubkey)

        reply = self.parley("echo", ctext)
        assert reply == ptext
def _test_rsa():
    print()
    print("For the next test, we need some text to encrypt.")
    print()
    ptext = input("Enter some text: ").encode()
    print()

    print("Generating an RSA key pair, please wait.")
    pubkey, privkey = make_rsa_keys()

    print("Ciphertext encrypted with our private key:")
    ctext = rsa(ptext, privkey)
    print_indent(ctext)

    print("Plaintext decrypted with our public key:")
    new_ptext = rsa(ctext, pubkey)
    print_indent(new_ptext, as_hex=False)

    return "Passed." if ptext == new_ptext else "Failed."
Beispiel #3
0
def main():
    print("Generating an RSA key pair, please wait.")

    pubkey, privkey = make_rsa_keys(bits=1024)
    oracle = make_oracle(privkey)

    print("Generating and decrypting ciphertext.")
    print()

    ctext = rsa(base64.b64decode(PTEXT_B64), pubkey, as_bytes=False)

    decryptor(ctext, pubkey, oracle)
Beispiel #4
0
def verify_rsa(bs, sig, pubkey, hash_cls=SHA1):
    phash = rsa(sig, pubkey)

    # Сбить ведущий 0x01, хотя бы один 0xff и магию ASN.1.
    # ПРИМЕЧАНИЕ: rsa () уже сбивает ведущий 0x00.
    if phash.startswith(b"\x01\xff"):
        phash = phash[1:]
        while phash[0] == 0xFF:
            phash = phash[1:]
        if phash.startswith(ASN_1):
            phash = phash[len(ASN_1):]

    return phash.startswith(hash_cls(bs).digest())
def verify_rsa(bs, sig, pubkey, hash_cls=SHA1):
    phash = rsa(sig, pubkey)

    # Knock off leading 0x01, at least one 0xff, and ASN.1 magic.
    # NOTE: rsa() already knocks off leading 0x00.
    if phash.startswith(b"\x01\xff"):
        phash = phash[1:]
        while phash[0] == 0xFF:
            phash = phash[1:]
        if phash.startswith(ASN_1):
            phash = phash[len(ASN_1):]

    return phash.startswith(hash_cls(bs).digest())
    def rsa_echo(self, ctext):
        # Clear records of old message hashes.
        now = int(time.time())
        while self.hashes and self.timeout < now - self.hashes[0][0]:
            self.hashes.popleft()

        cur_hash = sha256(ctext).digest()

        for _, old_hash in self.hashes:
            if old_hash == cur_hash:
                return None

        self.hashes.append((now, cur_hash))

        return rsa(ctext, self.privkey)
Beispiel #7
0
def main():
    ptext = random.choice(PTEXTS)

    print("Generating 3 public RSA keys and encrypting a plaintext.")
    print()

    n, c = [], []

    for i in range(3):
        pubkey, privkey = make_rsa_keys()
        ctext = rsa(ptext, pubkey)
        assert rsa(ctext, privkey) == ptext

        print(f"Ciphertext {i}:")
        print_indent(ctext)

        n.append(pubkey[1])
        c.append(from_bytes(ctext))

    if len(set(c)) == 1:
        print("The ciphertexts are sometimes identical.")
        print("This is fine; we also rely upon the public keys differing.")
        print()

    result, n_012 = 0, 1

    for i in range(3):
        ms = n[(i + 1) % 3] * n[(i + 2) % 3]
        result += c[i] * ms * invmod(ms, n[i])

        n_012 *= n[i]

    result = nth_root(result % n_012, 3)

    print("Cracked plaintext:")
    print_indent(to_bytes(result), as_hex=False)
def main():
    ptext = b"kick it, CC"

    print(f"Original plaintext: '{ptext.decode()}'")
    print()

    print("Generating an RSA-256 key pair.")
    pubkey, privkey = make_rsa_keys(256)
    bsize, oracle = byte_length(pubkey[1]), make_oracle(privkey)

    print("Padding and encrypting plaintext using PKCS#1 1.5.")
    padded = pad_pkcs15(ptext, bsize)
    ctext = rsa(padded, pubkey, as_bytes=False)

    print("Cracking ciphertext, please wait.")
    decrypt_state = decrypt_prepare(ctext, pubkey, oracle)
    while not isinstance(decrypt_state, int):
        decrypt_state = decrypt_pass(*decrypt_state, oracle)
    print()

    result = unpad_pkcs15(decrypt_state, bsize)
    print(f"Cracked plaintext: '{result.decode()}'")
def main():
    print(f"Enter a key length in {KEY_LENGTHS}.")
    print("Default is 768. Longer lengths ~dramatically~ extend runtime.")
    print()

    key_length, ans = None, input("> ")
    try:
        key_length = int(ans)
    except ValueError:
        pass
    if key_length not in KEY_LENGTHS:
        key_length = 768
    print()

    ptext, bsize = random.choice(PTEXTS), key_length // 8
    while len(ptext) > bsize - 11:
        ptext = random.choice(PTEXTS)
    print(f"Original plaintext: '{ptext.decode()}'")
    print()

    print(f"Generating an RSA-{key_length} key pair.")
    pubkey, privkey = make_rsa_keys(key_length)

    print("Padding and encrypting plaintext using PKCS#1 1.5.")
    padded = pad_pkcs15(ptext, bsize)
    ctext = rsa(padded, pubkey, as_bytes=False)
    print()

    print(f"Cracking ciphertext using {CPUS} cores, please wait.")
    now = datetime.now()
    cracker = PKCS15Cracker(pubkey, privkey, ctext)
    padded = cracker.decrypt()
    cracker.shutdown()
    print(f"Finished in {datetime.now() - now}.")
    print()

    cracked_ptext = unpad_pkcs15(padded, bsize)
    print(f"Cracked plaintext:  '{cracked_ptext.decode()}'")
Beispiel #10
0
def sign_rsa(bs, privkey, hash_cls=SHA1):
    # Хеш, подвергнутый RSA "расшифровке", дополняется до
    # той же длины, что и модуль RSA в соответствии с PKCS # 1.5.
    phash = ASN_1 + hash_cls(bs).digest()
    phash = b"\x00\x01" + phash.rjust(byte_length(privkey[1]) - 2, b"\xff")
    return rsa(phash, privkey)
Beispiel #11
0
 def oracle(ctext):
     return not rsa(ctext, privkey, as_bytes=False) & 1
def oracle(ctext, privkey):
    bsize = byte_length(privkey[1])
    ptext = rsa(ctext, privkey)
    return ptext.rjust(bsize, b"\x00")[:2] == b"\x00\x02"
 def oracle(ctext):
     ptext = rsa(ctext, privkey)
     return ptext.rjust(bsize, b"\x00")[:2] == b"\x00\x02"
def sign_rsa(bs, privkey, hash_cls=SHA1):
    # The hash subjected to the RSA "decryption" is padded to
    # the same length as the RSA modulus according to PKCS#1.5.
    phash = ASN_1 + hash_cls(bs).digest()
    phash = b"\x00\x01" + phash.rjust(byte_length(privkey[1]) - 2, b"\xff")
    return rsa(phash, privkey)