Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

아모에요

[cryptohack.org] General 본문

Study/Hacking

[cryptohack.org] General

dys4nt 2023. 7. 20. 00:19

Encoding

ASCII

 

주어진 리스트를 복붙한 다음 chr를 이용해서 파이썬 스크립트를 구현하면

 

li = [99, 114, 121, 112, 116, 111, 123, 65, 83, 67, 73, 73, 95, 112, 114, 49, 110, 116, 52, 98, 108, 51, 125]

res = ""
for n in li:
    res += chr(n)

print(res)

crypto{ASCII_pr1nt4bl3}

 

Hex

 

마찬가지로 hex로 인코딩된 문자열이 주어진다. 이를 bytes.fromhex() 함수를 이용해서 bytes로 치환하자.

 

s = "63727970746f7b596f755f77696c6c5f62655f776f726b696e675f776974685f6865785f737472696e67735f615f6c6f747d"

b = bytes.fromhex(s)
print(b)

crypto{You_will_be_working_with_hex_strings_a_lot}

 

Base64

 

hex string이 주어지고 이를 byte array로 바꾼 다음 bae64.b64encode() 함수로 b64 encode하자.

import base64

s = "72bca9b68fc16ac7beeb8f849dca1d8a783e8acf9679bf9269f7bf"
b = bytes.fromhex(s)

print(base64.b64encode(b))

crypto/Base+64+Encoding+is+Web+Safe/

 

Bytes and Big Integers

 

long 숫자가 주어지고 이를 pycryptodome 패키지의 long_to_bytes 함수를 이용해서 bytes로 바꾼 다음 출력하면 된다.

 

from Crypto.Util.number import *

num = 11515195063862318899931685488813747395775516287289682636499965282714637259206269
b = long_to_bytes(num)

print(b)

crypto{3nc0d1n6_4ll_7h3_w4y_d0wn}

 

Encoding Challenge

 

#!/usr/bin/env python3

from Crypto.Util.number import bytes_to_long, long_to_bytes
from utils import listener # this is cryptohack's server-side module and not part of python
import base64
import codecs
import random

FLAG = "crypto{????????????????????}"
ENCODINGS = [
    "base64",
    "hex",
    "rot13",
    "bigint",
    "utf-8",
]
with open('/usr/share/dict/words') as f:
    WORDS = [line.strip().replace("'", "") for line in f.readlines()]


class Challenge():
    def __init__(self):
        self.challenge_words = ""
        self.stage = 0

    def create_level(self):
        self.stage += 1
        self.challenge_words = "_".join(random.choices(WORDS, k=3))
        encoding = random.choice(ENCODINGS)

        if encoding == "base64":
            encoded = base64.b64encode(self.challenge_words.encode()).decode() # wow so encode
        elif encoding == "hex":
            encoded = self.challenge_words.encode().hex()
        elif encoding == "rot13":
            encoded = codecs.encode(self.challenge_words, 'rot_13')
        elif encoding == "bigint":
            encoded = hex(bytes_to_long(self.challenge_words.encode()))
        elif encoding == "utf-8":
            encoded = [ord(b) for b in self.challenge_words]

        return {"type": encoding, "encoded": encoded}

    #
    # This challenge function is called on your input, which must be JSON
    # encoded
    #
    def challenge(self, your_input):
        if self.stage == 0:
            return self.create_level()
        elif self.stage == 100:
            self.exit = True
            return {"flag": FLAG}

        if self.challenge_words == your_input["decoded"]:
            return self.create_level()

        return {"error": "Decoding fail"}


listener.start_server(port=13377)

13377.py 파일을 보면 {"type": encoding, "encoded": encoded}로 JSON 형태의 데이터를 리턴하는 것을 확인할 수 있다.

 

pwntools을 이용해서 자동으로 이를 입력받은 다음 디코딩 과정을 거쳐서 디코딩된 데이터를 {"decoded" : dec } 형태로 보내는 코드를 짜면 된다.

 

from pwn import *
from Crypto.Util.number import *
import json
import codecs

r = remote("socket.cryptohack.org",13377)

# context.log_level = "debug"

def send_json(s):
    obj = {}
    obj['decoded'] = s
    s = json.dumps(obj)
    r.sendline(s)

for i in range(100):
    li = r.recvline().split(b":")
    method = li[1].split(b",")[0][2:-1]
    enc = li[2][2:-3]
    # print(method)
    # print(enc)

    if method == b'base64':
        decoded = base64.b64decode(enc).decode()
        send_json(decoded)
    elif method == b'hex':
        decoded = bytes.fromhex(enc.decode()).decode()
        send_json(decoded)
    elif method == b'rot13':
        decoded = codecs.decode(enc.decode(),'rot13')
        send_json(decoded)
    elif method == b'bigint':
        num = int(enc.decode(),16)
        decoded = long_to_bytes(num).decode()
        send_json(decoded)
    else:
        li = enc.decode().split(", ")
        decoded = ""
        for i in li:
            decoded += chr(int(i))
        send_json(decoded)
        
print(r.recvline())

crypto{3nc0d3_d3c0d3_3nc0d3}

 

XOR

XOR Starter

 

문자열 label의 각 문자에 대해서 13과 XOR한 다음 결과를 출력하는 코드를 작성하면

s = b'label'

for i in range(5):
    print(chr(s[i] ^ 13))

aloha가 나온다.

crypto{aloha}

 

XOR Properties

 

k1, k2^k1, k2^k3, flag^k1^k3^k2가 주어진다.

flag = flag^k1^k3^k2^k2^k3^k1이므로

 

이를 계산하는 코드를 구현하면

 

from pwn import *

k1 = bytes.fromhex("a6c8b6733c9b22de7bc0253266a3867df55acde8635e19c73313")
k2k1 = bytes.fromhex("37dcb292030faa90d07eec17e3b1c6d8daf94c35d4c9191a5e1e")
k2k3 = bytes.fromhex("c1545756687e7573db23aa1c3452a098b71a7fbf0fddddde5fc1")
fk1k3k2 = bytes.fromhex("04ee9855208a2cd59091d04767ae47963170d1660df7f56f5faf")

flag = xor(xor(fk1k3k2,k2k3),k1)

print(flag)

crypto{x0r_i5_ass0c1at1v3}

 

Favorite byte

 

브포로 모든 1바이트에 대해서 xor하는 코드를 구현하자.

 

from pwn import *

b = bytes.fromhex("73626960647f6b206821204f21254f7d694f7624662065622127234f726927756d")

for i in range(256):
    print(xor(b,i))

crypto{0x10_15_my_f4v0ur173_by7e}

 

You either know, XOR you don't

 

hex 스트링과 플래그 포맷 crypto{}를 XOR하여서 key를 추출하려 시도하였는데, crypto{에 대해서 myXORke까지 출력되었다. 키를 myXORkey라 가정하고 이 키를 이용해서 주어진 스트링과 XOR하면 플래그가 나온다.

 

from pwn import *

b = bytes.fromhex("0e0b213f26041e480b26217f27342e175d0e070a3c5b103e2526217f27342e175d0e077e263451150104")
f = b"myXORkey"

print(xor(b,f))

crypto{1f_y0u_Kn0w_En0uGH_y0u_Kn0w_1t_4ll}

 

Lemur XOR

 

두 이미지 파일이 주어진다. 이 이미지 파일들을 XOR하면 플래그가 나올 것 같다.

import numpy as np
from PIL import Image

img1 = Image.open("lemur.png")
img2 = Image.open("flag.png")

n1 = np.array(img1)*255
n2 = np.array(img2)*255

res_img = np.bitwise_xor(n1,n2).astype(np.uint8)

Image.fromarray(n_img).save('res.png')

crypto{X0Rly_n0t!}

 

Mathematics

Greatest Common Divisor

 

gcd(66528,52920)을 계산하면 된다.

import sympy as sp

print(sp.gcd(66528,52920))

1512

 

Extended GCD

 

확장된 유클리드 알고리즘을 이용해서 합동식을 계산하면 된다.

 

def EEA(a,b):
    r1,r2 = a,b
    p1,p2 = 1,0
    q1,q2 = 0,1
    
    while r2>0:
        n = r1 // r2
        r1,r2 = r2,r1%r2
        p1,p2 = p2,p1-n*p2
        q1,q2 = q2,q1-n*q2
    print("{} = {} * ({}) + {} * ({})".format(r1,a,p1,b,q1))

EEA(26513, 32321)

-8404

 

Modular Arithmetic 1

두 수중 작은 값이므로 4

 

Modular Arithmetic 2

a^(p-1) mod p를 계산하고 a와 p는 서로소이므로 정답은 1이다.

 

Modular Inverting

3의 mod 13에 대한 잉여역수를 계산하라고 한다. 3의 11승을 계산하면 된다. => 9

 

Data Formats

Privacy-Enhanced Mail?

from Crypto.PublicKey import RSA
s = open("privacy_enhanced_mail.pem",'r').read()
k = RSA.import_key(s)
print(k.d)

 

CERTainly not

import ssl
from Crypto.PublicKey import RSA

db = open("2048b-rsa-example-cert.der",'rb').read()
pem = ssl.DER_cert_to_PEM_cert(db)

k = RSA.import_key(pem)
print(k.n)

SSH Keys

from Crypto.PublicKey import RSA
t = open("bruce_rsa.pub",'r').read()
k = RSA.import_key(t)

print(k.n)

Transparency

https://thetransparencyflagishere.cryptohack.org/

에 접속하면 플래그가 나온다.

 

crypto{thx_redpwn_for_inspiration}

'Study > Hacking' 카테고리의 다른 글

[dreamhack.io] Textbook-CBC  (0) 2023.07.14
[dreamhack.io] phpythonode  (0) 2023.07.13
[dreamhack.io] node_api  (0) 2023.07.13
[HackTheBox] Templated  (0) 2023.07.13
[pwn.college] Talking Web - level1  (0) 2023.07.13