Common python scripts and online websites of ctf

script

Picture blasting width and height script in Knowledge points of ctf misc picture questions in

Binary to QR code

Before running, change the image side length, that is, the value of MAX. for example, the binary string length is 625 (25 * 25), which is changed to 25 here

import PIL
from PIL import Image
MAX = 25  #Picture side length
img = Image.new("RGB",(MAX,MAX))
str='1111111001110010001111111100000100001111010100000110111010011100010010111011011101010111100001011101101110101010101000101110110000010011000101010000011111111010101010101111111000000000100000110000000011000111011101101000110000001000010110010010010100010011110100001110111001100111101001010110010010011000001001100001001101000111100011111101110010100010110111110011011111101111000110110010010101101100100011110011111111111011100000000101100011000101001111111010010100101010001100000101010101010001100110111010001001111111100101011101000011001011110111101110100100110010010000110000010110000110110110011111111011010000101110101'
i = 0
for y in range (0,MAX):
    for x in range (0,MAX):
        if(str[i] == '1'):
            img.putpixel([x,y],(0, 0, 0))
        else:
            img.putpixel([x,y],(255,255,255))
        i = i+1
img.show()
img.save("flag.png")

base64

base64 XOR

import base64

s='TkVLTFdUQVpvUlNda1ZXRUpAZVldTltgJCQhLCAgGSknPjc='
s=base64.b64decode(s)
for i in range(256):
	flag=""
	k=0
	for j in s:
		res=j^(k+i)
		flag+=chr(res)
		k+=1
	print(i,flag)

base64 steganography encryption (py2)

# -*- coding: cp936 -*-
import base64

flag = 'Tr0y{Base64isF4n}'  # flag
bin_str = ''.join([bin(ord(c)).replace('0b', '').zfill(8) for c in flag])

base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

with open('0.txt', 'rb') as f0, open('1.txt', 'wb') as f1:  # '0.txt' is clear text, '1 Txt 'is used to store base64 after steganography
    for line in f0.readlines():
        rowstr = base64.b64encode(line.replace('\n', ''))
        equalnum = rowstr.count('=')

        if equalnum and len(bin_str):
            offset = int('0b' + bin_str[:equalnum * 2], 2)
            char = rowstr[len(rowstr) - equalnum - 1]
            rowstr = rowstr.replace(char, base64chars[base64chars.index(char) + offset])
            bin_str = bin_str[equalnum * 2:]

        f1.write(rowstr + '\n')

base64 steganalysis (py2)

# -*- coding: cp936 -*-
b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
#https://tr0y.wang/2017/06/14/Base64steg/
with open('1.txt', 'rb') as f:
    bin_str = ''
    for line in f.readlines():
        stegb64 = ''.join(line.split())
        rowb64 = ''.join(stegb64.decode('base64').encode('base64').split())

        offset = abs(b64chars.index(stegb64.replace('=', '')[-1]) - b64chars.index(rowb64.replace('=', '')[-1]))
        equalnum = stegb64.count('=')  # no equalnum no offset

        if equalnum:
            bin_str += bin(offset)[2:].zfill(equalnum * 2)

        print ''.join([chr(int(bin_str[i:i + 8], 2)) for i in xrange(0, len(bin_str), 8)])  # 8-digit group

1-5 bit crc32 collision

6-bit collision Tools are already available

# coding:utf-8

"""
Author: spaceman
"""

import binascii
import string 
from time import sleep

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass

    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass
 
    return False

# progress bar
def progress(percent=0, width=40):
    left = width * percent // 95
    right = width - left
    print ('\r[', '#' * left, ' ' * right, ']',f' {percent:.0f}%',sep='', end='', flush=True)

# One bit byte
def crc1(strs,dic):
    strs = hex(int(strs,16))
    rs = ''
    for i in dic:
        s = i
        if hex(binascii.crc32(s.encode())) == strs:
            rs += s
            print (strs+'  :  '+s)
    return rs

# Two bit byte
def crc2(strs,dic):
    strs = hex(int(strs,16))
    rs = ''
    for i in dic:
        for j in dic:
            s = i + j
            if hex(binascii.crc32(s.encode())) == strs:
                rs += s
                print (strs+'  :  '+s)
    return rs

# Three bit byte
def crc3(strs,dic):
    strs = hex(int(strs,16))
    rs = ''
    for i in dic:
        for j in dic:
            for k in dic:
                s = i+j+k
                if hex(binascii.crc32(s.encode())) == strs:
                    rs += s
                    print (strs+'  :  '+s)
    return rs

# Four bit byte
def crc4(strs,dic):
    strs = hex(int(strs,16))
    rs = ''
    it = 1
    for i in dic:
        for j in dic:
            for k in dic:
                for m in dic:
                    s = i+j+k+m
                    if hex(binascii.crc32(s.encode())) == strs:
                        rs += s
                        print ()
                        print (strs+'  :  '+s)
                        print ('\n')
        progress(it)
        sleep(0.1)
        it += 1
    return rs
    

# Five bit byte
def crc5(strs,dic):
    strs = hex(int(strs,16))
    rs = ''
    it = 1
    for i in dic:
        progress(it)
        for j in dic:
            for k in dic:
                for m in dic:
                    for n in dic:
                        s = i+j+k+m+n
                        if hex(binascii.crc32(s.encode())) == strs:
                            rs += s
                            print ()
                            print (strs+'  :  '+s)
                            print ('\n')
        sleep(0.1)
        it += 1
    return rs

# Calculate collision crc 
def CrackCrc(crclist,length):
    print ()
    print ("Calculating...")
    print ()
    dic = ''' !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~''' # Character dictionary required for collision
    dic = dic[::-1]
    text = ''
    for i in crclist:
        if length == '1':
            text += crc1(i,dic)
        if length == '2':
            text += crc2(i,dic)
        if length == '3':
            text += crc3(i,dic)
        if length == '4':
            text += crc4(i,dic)
        if length == '5':
            text += crc5(i,dic)
    print ('\n')
    if text == '':
        print ("Collision failure,No result")
        exit()
    print ("Character sequence combination:",end=' ')
    print ()
    print (text)
    print ()
    input("Enter to confirm the end of the procedure...")

# Main function
print ('''
##############################

###### Author: spaceman ######

### Thank you for your use ###

##############################
''')
listcrc = [] # Used to store crc values
length = (input("Please enter text byte size(1-5): ")) # That is, the size of the text content. If the text content is flag, the size is 4
if is_number(length) == False or length not in ("1,2,3,4,5"):
    exit("Non specified number, exit")
print ()
while 1:
    crc = input('Please enter crc value(for example:d1f4eb9a,input n Complete input):')
    if crc == 'n':
        break
    crc = '0x'+crc
    if len(crc) != 10:
        print ("rcr Wrong length,Please re-enter")
        continue
    listcrc.append(crc)

CrackCrc(listcrc,length)

Writes decimal numbers to a file

x=[55,122,188,175,175]

f=b''
for i in x:
    f += i.to_bytes(1,'big')

out=open("1.7z","wb")
out.write(f)

usb traffic

Keyboard traffic

First tshark export data

┌ - (volcano ㉿ kali) - [~ / desktop]
└─$ tshark -r whereiskey.pcapng -T fields -e usb.capdata | sed '/^\s*$/d' > out.txt

Then add a colon between every two numbers

f=open('1.txt','r')
fi=open('out.txt','w')
while 1:
    a=f.readline().strip()
    if a:
        if len(a)==16: # For mouse traffic, len is changed to 8
            out=''
            for i in range(0,len(a),2):
                if i+2 != len(a):
                    out+=a[i]+a[i+1]+":"
                else:
                    out+=a[i]+a[i+1]
            fi.write(out)
            fi.write('\n')
    else:
        break

fi.close()

Rerun script

normalKeys = {"04":"a", "05":"b", "06":"c", "07":"d", "08":"e", "09":"f", "0a":"g", "0b":"h", "0c":"i", "0d":"j", "0e":"k", "0f":"l", "10":"m", "11":"n", "12":"o", "13":"p", "14":"q", "15":"r", "16":"s", "17":"t", "18":"u", "19":"v", "1a":"w", "1b":"x", "1c":"y", "1d":"z","1e":"1", "1f":"2", "20":"3", "21":"4", "22":"5", "23":"6","24":"7","25":"8","26":"9","27":"0","28":"<RET>","29":"<ESC>","2a":"<DEL>", "2b":"\t","2c":"<SPACE>","2d":"-","2e":"=","2f":"[","30":"]","31":"\\","32":"<NON>","33":";","34":"'","35":"<GA>","36":",","37":".","38":"/","39":"<CAP>","3a":"<F1>","3b":"<F2>", "3c":"<F3>","3d":"<F4>","3e":"<F5>","3f":"<F6>","40":"<F7>","41":"<F8>","42":"<F9>","43":"<F10>","44":"<F11>","45":"<F12>"}
shiftKeys = {"04":"A", "05":"B", "06":"C", "07":"D", "08":"E", "09":"F", "0a":"G", "0b":"H", "0c":"I", "0d":"J", "0e":"K", "0f":"L", "10":"M", "11":"N", "12":"O", "13":"P", "14":"Q", "15":"R", "16":"S", "17":"T", "18":"U", "19":"V", "1a":"W", "1b":"X", "1c":"Y", "1d":"Z","1e":"!", "1f":"@", "20":"#", "21":"$", "22":"%", "23":"^","24":"&","25":"*","26":"(","27":")","28":"<RET>","29":"<ESC>","2a":"<DEL>", "2b":"\t","2c":"<SPACE>","2d":"_","2e":"+","2f":"{","30":"}","31":"|","32":"<NON>","33":"\"","34":":","35":"<GA>","36":"<","37":">","38":"?","39":"<CAP>","3a":"<F1>","3b":"<F2>", "3c":"<F3>","3d":"<F4>","3e":"<F5>","3f":"<F6>","40":"<F7>","41":"<F8>","42":"<F9>","43":"<F10>","44":"<F11>","45":"<F12>"}
output = []
keys = open('out.txt')
for line in keys:
    try:
        if line[0]!='0' or (line[1]!='0' and line[1]!='2') or line[3]!='0' or line[4]!='0' or line[9]!='0' or line[10]!='0' or line[12]!='0' or line[13]!='0' or line[15]!='0' or line[16]!='0' or line[18]!='0' or line[19]!='0' or line[21]!='0' or line[22]!='0' or line[6:8]=="00":
             continue
        if line[6:8] in normalKeys.keys():
            output += [[normalKeys[line[6:8]]],[shiftKeys[line[6:8]]]][line[1]=='2']
        else:
            output += ['[unknown]']
    except:
        pass
keys.close()

flag=0
print("".join(output))
for i in range(len(output)):
    try:
        a=output.index('<DEL>')
        del output[a]
        del output[a-1]
    except:
        pass
for i in range(len(output)):
    try:
        if output[i]=="<CAP>":
            flag+=1
            output.pop(i)
            if flag==2:
                flag=0
        if flag!=0:
            output[i]=output[i].upper()
    except:
        pass
print ('output :' + "".join(output))

Keyboard traffic

Still export first

┌──(volcano㉿kali)-[~]
└─$ tshark -r secret.pcapng -T fields -e usb.capdata | sed '/^\s*$/d' > out.txt

Then run the script

nums = []
keys = open('out.txt','r')
posx = 0
posy = 0
for line in keys:
    if len(line) != 13:
         continue
    x = int(line[4:6],16)
    y = int(line[6:8],16)
    if x > 127 :
        x -= 256
    if y > 130 :
        y -= 265
    posx += x
    posy += y
    btn_flag = int(line[2:4],16)
    if btn_flag == 1:   # 1 for left , 2 for right , 0 for nothing
        print posx ,posy
keys.close()

Conversion character

Binary to character

It is common to rotate every eight bits, sometimes every seven bits, and the script needs to be changed slightly

def fun1():#Binary string conversion string
    #String to convert
    f = '0001000001110001000000010001001000010001001000110111001100010000011100010000011101010000010010000100100001001000000100100101'
    b = ''
    i = 0
    j = 8   #Sometimes it has to be changed to 7
    while j <= len(f):
        a = '0' + f[i:j]
        b += chr(int(a,2))
        i = j
        j += 8  #Sometimes it's changed to 7
    print(b)
def fun2():#String to binary string
    #String to convert
    f = ' '
    b = ''
    c = ''
    for i in f:
        a = str(bin(ord(i)))
        b = a[2:].zfill(7)
        c += b
    print(c)
fun1()
#fun2()

Octal to character

s="146154141147173144157137171157165137153156157167137160141167156163150157160175"
x=[] 
for i in range(len(s)//3) : # modify the size according to the title, and divide the length of the string by 3
    x.append(s[3*i:3*i+3])
y=[]
flag=""
for j in range(len(x)):
    y.append(int(x[j],base=8))

for k in range(len(x)):
    flag+=chr(y[k])
print(flag)

Decimal to character

Applicable to the given is a long string of decimal

s="98117103107117123110974810048110103100971079749125"
x=len(s)//2
flag=""
for i in range(x):
    if len(s) != 0:
        if  int(s[:3])< 127:
            flag += chr(int(s[:3]))
            s = s[3:]
        else:
            flag += chr(int(s[:2]))
            s = s[2:]
print(flag)

hex to character

import binascii

s=""

s=binascii.unhexlify(s) 
print(s.decode('utf-8')) 

lsb steganography of bmp

import PIL.Image as Image 
img = Image.open('low.bmp')
img_tmp = img.copy()
pix = img_tmp.load()
width,height = img_tmp.size
for w in range(width):
   for h in range(height):
      if pix[w,h]&1 == 0:
         pix[w,h] = 0
      else:
         pix[w,h] = 255
img_tmp.show()

TTL steganography

import binascii
with open('attachment.txt','r') as fp:
    a=fp.readlines()
    p=[]
    for x in range(len(a)):
       p.append(int(a[x])) 
    s=''
    for i in p:
        if(i==63):
            b='00'
        elif(i==127):
            b='01'
        elif(i==191):
            b='10'
        else:
            b='11'
        s +=b
# print(s)
flag = ''
for i in range(0,len(s),8):
    flag += chr(int(s[i:i+8],2))
flag = binascii.unhexlify(flag)
wp = open('ans.zip','wb')
wp.write(flag)
wp.close()

Affine cipher

# Affine cipher
z = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
     'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
     'U', 'V', 'W', 'X', 'Y', 'Z']


# The 52 elements in the Z integer ring are represented by a list
def exgcd(a, b, arr):  # By extending Euclid's theorem, we can find the inverse element of a in the ring of integers
    if b == 0:
        arr[0] = 1
        arr[1] = 0
        return a
    r = exgcd(b, a % b, arr)
    tmp = arr[0]
    arr[0] = arr[1]
    arr[1] = tmp - int(a / b) * arr[1]
    return r


def Get_ei(a, b):
    arr = [0, 1, ]
    r = exgcd(a, b, arr)
    if r == 1:
        return int((arr[0] % b + b) % b)
    else:
        return -1


def encrypt(k1, k2, message):  # Encryption process
    a = str(message)
    t = ""

    for i in a:

        if i in z:

            c = z.index(i)
            Y = (k1 * c + k2) % 52
            t += z[Y]
        else:
            t += i
    return t
    # print(ord(i))


# *************begin************#

# **************end*************#

def decrypt(k1, k2, message):  # Decryption process
    k1_ = Get_ei(k1, 52)
    t = ""
    a = str(message)
    for i in a:
        if i in z:
            c = z.index(i)
            X = (k1_ * (c - k2)) % 52
            t += z[X]
        else:
            t += i
    return t


def main():
    mode = int(input())  # 1 for encryption and 0 for decryption
    message = input()  # Messages to be encrypted or decrypted
    key1 = int(input())  # The range of key is between 0 and 51
    key2 = int(input())  # The range of key is between 0 and 51
    if mode == 1:
        translated = encrypt(key1, key2, message)
    else:
        translated = decrypt(key1, key2, message)
    print(translated)


if __name__ == '__main__':
    main()

Flip picture content up and down

from PIL import Image
im = Image.open("1.jpg")
pim = im.load()
an = Image.open("1.jpg")
ans = an.load()
for i in range(im.size[0]):
    for j in range(im.size[1]):
        ans[i, j] = pim[im.size[0]-i-1, j]
an.show()

Fourier transform

import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread('FFT.png', 0) #Directly read as grayscale image
f = np.fft.fft2(img) #Do frequency conversion
fshift = np.fft.fftshift(f) #Transfer pixels to do amplitude spectrum
s1 = np.log(np.abs(fshift))#Take absolute value: change the complex number into a real number and take the logarithm (in order to change the data to 0-255
plt.subplot(121)
plt.imshow(img, 'gray')
plt.title('original')
plt.subplot(122)
plt.imshow(s1,'gray')
plt.title('center')
plt.show()

Bulk read compressed package

import zipfile

for i in range(1, 87): 
    # Read compressed package
    z = zipfile.ZipFile(r'C:\Users\Desktop\flag/' + str(i)+'.zip', 'r')
    
    # Read the picture content in the compressed package
    filename = z.namelist()[0]
    content = str(z.read(filename))
    
    # Print out the base64 encoded part
    len1 = len(content)
    content1 = content[len1-101:len1-1] #Change according to the title
    print(content1)

autokey blasting (py2)

from ngram_score import ngram_score
from pycipher import Autokey
import re
from itertools import permutations

qgram = ngram_score('quadgrams.txt')
trigram = ngram_score('trigrams.txt')
ctext = 'achnrvxzzuglarucalznwcygfggrufryvbzqjoxjymxvchhhdmliddcwmhghclpebtzwlojvew'
ctext = re.sub(r'[^A-Z]','',ctext.upper())

# keep a list of the N best things we have seen, discard anything else
class nbest(object):
    def __init__(self,N=1000):
        self.store = []
        self.N = N
        
    def add(self,item):
        self.store.append(item)
        self.store.sort(reverse=True)
        self.store = self.store[:self.N]
    
    def __getitem__(self,k):
        return self.store[k]

    def __len__(self):
        return len(self.store)

#init
N=100
for KLEN in range(3,20):
    rec = nbest(N)

    for i in permutations('ABCDEFGHIJKLMNOPQRSTUVWXYZ',3):
        key = ''.join(i) + 'A'*(KLEN-len(i))
        pt = Autokey(key).decipher(ctext)
        score = 0
        for j in range(0,len(ctext),KLEN):
            score += trigram.score(pt[j:j+3])
        rec.add((score,''.join(i),pt[:30]))

    next_rec = nbest(N)
    for i in range(0,KLEN-3):
        for k in xrange(N):
            for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
                key = rec[k][1] + c
                fullkey = key + 'A'*(KLEN-len(key))
                pt = Autokey(fullkey).decipher(ctext)
                score = 0
                for j in range(0,len(ctext),KLEN):
                    score += qgram.score(pt[j:j+len(key)])
                next_rec.add((score,key,pt[:30]))
        rec = next_rec
        next_rec = nbest(N)
    bestkey = rec[0][1]
    pt = Autokey(bestkey).decipher(ctext)
    bestscore = qgram.score(pt)
    for i in range(N):
        pt = Autokey(rec[i][1]).decipher(ctext)
        score = qgram.score(pt)
        if score > bestscore:
            bestkey = rec[i][1]
            bestscore = score       
    print bestscore,'autokey, klen',KLEN,':"'+bestkey+'",',Autokey(bestkey).decipher(ctext)

Online website

Repair QR code

https://merricx.github.io/qrazybox

Some aggregation sites

Commonly used base coding, url coding and various encryption
http://www.hiencode.com/
https://tool.lu/
https://ctf.bugku.com/tools.html
https://www.ctftools.com/down/
https://www.idcd.com/

bugku Old online tools Can be used to enumerate fence passwords and Caesar passwords

CyberChef It is recommended to download it locally. This tool is very easy to use, especially when encountering the encryption of multi-layer dolls (Magic)

G language code running online

https://ncviewer.com/

md5 decryption

https://www.cmd5.com/
https://www.somd5.com/

Identification of various codes

Identification of bar code, QR code, etc
https://demo.dynamsoft.com/barcode-reader/
Aztec Code identification
https://products.aspose.app/barcode/recognize/aztec#result

Coding of arrow symbols, flowers, notes, Braille, etc

Click switch

https://www.qqxiuzi.cn/bianma/wenbenjiami.php?s=jiantou

Virginia decryption

Many times you can run out of plaintext directly
https://www.guballa.de/vigenere-solver

rot5/13/18/47

https://www.qqxiuzi.cn/bianma/ROT5-13-18-47.php

emoji encryption

base100 and Emoji AES are common

https://aghorler.github.io/emoji-aes/
http://www.atoolbox.net/Tool.php?Id=937
https://ctf.bugku.com/tool/base100

brainfuck/Ook!

https://www.splitbrain.org/services/ook

Zero width character decryption

http://330k.github.io/misc_tools/unicode_steganography.html
https://yuanfux.github.io/zero-width-web/
http://www.atoolbox.net/Tool.php?Id=829

exif information view

https://exif.tuchong.com/

Large prime decomposition (RSA common)

http://www.factordb.com/

Word frequency analysis

https://quipqiup.com/

Xiong Yue / animal sound / Buddha Yue

http://hi.pcmoe.net/index.html

pyc Decompilation

https://tool.lu/pyc/

Keywords: Python CTF

Added by thoand on Wed, 12 Jan 2022 05:12:36 +0200