Crypto is fun 😉

Information
Challenge: RsaCtfTool
Category: Crypto
Difficulty: Easy
Files: RsaCtfTool.zip 1 KB
flag.txt.aes 33 b
key 384 b
pubkey.pem 356 b
Environment: Remnux VM
Walkthrough
1. File Analysis
We are given three files.
Pubkey.pem:
-----BEGIN PUBLIC KEY-----
MIHeMA0GCSqGSIb3DQEBAQUAA4HMADCByAKBwHfR4yv+QfsHYSvLlS6LGW2cMDlB
3RlH1PteD7gN6nU4KhyMlRznOUQI7cgB082btMWs1usPYfUSrqkDs+1EDrzzw42M
G683YvLlJRfcO2syc+YNJTDqtVHW5V3SNJ2J+WKCw0A5+ab2qA+sfhRFhvPJ7gsL
vUj+blt5qweyGVheMOQvy+WXI+Vi/jwtlW3it25kBLZUoESDBg+HZKnxz3MgcJ6X
roMdjPPwTH2f8sOrCTI1jJzNUYxJ9JQ0QPTrxwIDAQAB
-----END PUBLIC KEY-----
key:
13822f9028b100e2b345a1ad989d9cdedbacc3c706c9454ec7d63abb15b58bef8ba545bb0a3b883f91bf12ca12437eb42e26eff38d0bf4f31cf1ca21c080f11877a7bb5fa8ea97170c932226eab4812c821d082030100030d84ebc63fd8767cde994e0bd1a1f905c27fb0d7adb55e3a1f101d8b5b997ba6b1c09a5e1cc65a9206906ef5e01f13d7beeebdf389610fb54676f76ec0afc51a304403d44bb3c739fd8276f0895c3587a710d15e43fc67284070519e6e0810caf86b134f02ec54018
flag.txt.aes:
xxd -p flag.txt.aes
#4845da3014a52429e914c3117b1c45a0a68d6454e83057af6fcadadae011814d0a
2. Paramater Recovery
First, let’s load the key and check its values:
from Crypto.PublicKey import RSA
with open("pubkey.pem","r") as f:
public_key = RSA.import_key(f.read())
The exponent is 65537. Entering the value of n in factor db, shows that it is actually integer p (below) to the power of 3.
p = 10410080216253956216713537817182443360779235033823514652866757961082890116671874771565125457104853470727423173827404139905383330210096904014560996952285911
To find the private key, we can calculate phi by multiplying p with p with p -1 :
n = public_key.n
enc_flag = bytes.fromhex("4845da3014a52429e914c3117b1c45a0a68d6454e83057af6fcadadae011814d0a")
key = 0x13822f9028b100e2b345a1ad989d9cdedbacc3c706c9454ec7d63abb15b58bef8ba545bb0a3b883f91bf12ca12437eb42e26eff38d0bf4f31cf1ca21c080f11877a7bb5fa8ea97170c932226eab4812c821d082030100030d84ebc63fd8767cde994e0bd1a1f905c27fb0d7adb55e3a1f101d8b5b997ba6b1c09a5e1cc65a9206906ef5e01f13d7beeebdf389610fb54676f76ec0afc51a304403d44bb3c739fd8276f0895c3587a710d15e43fc67284070519e6e0810caf86b134f02ec54018
e = 65537
phi = p * p * (p-1)
d = pow(e, -1, phi)
decrypted = pow(key, d, n)
decryption_key = bytes.fromhex(hex(decrypted)[2:])
print(decryption_key)
#b'secretkey\x96\x1dW\xbe\xc09<'
Now that we found the decryption key, we can use AES to decrypt it. We can try with AES.ECB first (since we only have a key):
from Crypto.Cipher import AES
cipher = AES.new(decryption_key, AES.MODE_ECB)
flag = cipher.decrypt(enc_flag)
This raises an error, as the encrypted flag is 33 bytes long. We can try by removing the last byte:
from Crypto.Cipher import AES
cipher = AES.new(decryption_key, AES.MODE_ECB)
flag = cipher.decrypt(enc_flag[:-1])
print(flag)
#b'HTB{pl4y1ng_w1th_pr1m3s_1s_fun!}'