[BSidesSF2020]decrypto-1
[BSidesSF2020]decrypto-1
題目
Kerckhoffs’s principle states that “A cryptosystem should be secure even if everything about the system, except the key, is public knowledge.” So here’s our unbreakable cipher.
import sys import json import hashlibclass Crypto:def __init__(self, key):if not isinstance(key, bytes):raise TypeError('key must be of type bytes!')self.key = keyself._buf = bytes()self._out = open("/dev/stdout", "wb")def _extend_buf(self):self._buf += self.keydef get_bytes(self, nbytes):while len(self._buf) < nbytes:self._extend_buf()ret, self._buf = self._buf[:nbytes], self._buf[nbytes:]return retdef encrypt(self, buf):if not isinstance(buf, bytes):raise TypeError('buf must be of type bytes!')stream = self.get_bytes(len(buf))return bytes(a ^ b for a, b in zip(buf, stream))def set_outfile(self, fname):self._out = open(fname, "wb")def encrypt_file(self, fname):buf = open(fname, "rb").read()self._out.write(self.encrypt(buf))class JSONCrypto(Crypto):def encrypt_file(self, fname):buf = open(fname, "r").read().strip()h = hashlib.sha256(buf.encode('utf-8')).hexdigest()data = {"filename": fname,"hash": h,"plaintext": buf,}outbuf = json.dumps(data, sort_keys=True, indent=4)self._out.write(self.encrypt(outbuf.encode("utf-8")))def main(argv):if len(argv) not in (3, 4):print("%s <key> <infile> [outfile]" % sys.argv[0])returnargv.pop(0)key = argv.pop(0)inf = argv.pop(0)crypter = JSONCrypto(key.encode("utf-8"))if sys.argv:crypter.set_outfile(argv.pop(0))crypter.encrypt_file(inf)if __name__ == '__main__':main(sys.argv)flag.txt.enc
:TL\Z\QETVRQ SIH fGNV\\\ETV[UVQU ] A_]UC^ QWZC _RY@QYRU_[@^^[CfGNVDQ ] U@VE-d2OM N8 _@boFbC 1SMM[L:解題
科克霍夫斯原理聲明“密碼系統應該是安全的,即使系統的所有內容,除了密鑰,都是公共知識?!彼赃@里是我們的牢不可破的密碼。
牢不可破的密碼,那就可能是一次一密了。
先讀程序:
sys.argv[]是一個從程序外部獲取參數的橋梁,因為我們從外部取得的參數可以是多個,所以獲得的是一個列表,也就是說sys.argv其實可以看作是一個列表,所以才能用[]提取其中的元素。其第一個元素是程序本身,sys.argv[0]表示代碼本身文件路徑,隨后才依次是外部給予的參數。
pop() 函數用于移除列表中的一個元素(默認最后一個元素),并且返回該元素的值。
hash.hexdigest() 返回摘要,作為十六進制數據字符串值。
json.dumps()將一個Python數據結構轉換為JSON對象,indent:參數根據數據格式縮進顯示,讀起來更加清晰,skipkeys:默認值是False,如果dict的keys內的數據不是python的基本類型(str,unicode,int,long,float,bool,None),設置為False時,就會報TypeError的錯誤。此時設置成True,則會跳過這類key 。
解題代碼:
import json data = {"filename": 'flag.txt',"hash": 'h',} outbuf = json.dumps(data, sort_keys=True, indent=4) cipher_pre=open('flag.txt.enc','rb').read() for i in range(43):print(chr(cipher_pre[i]^ord(outbuf[i])))#得到key key='n0t4=l4g' for i in range(8):key+=key#使key足夠長. flag='' for i in range(len(cipher_pre)):flag+=chr(ord(key[i])^cipher_pre[i]) print(flag)運行得到:
{"filename": "flag.txt","hash": "2f98b8afa014bf955533a3e72cee0417413ff744e25f2b5b5838f5741cd69547","plaintext": "CTF{plz_dont_r0ll_ur_own_crypto}" }答案
flag{plz_dont_r0ll_ur_own_crypto}
總結
以上是生活随笔為你收集整理的[BSidesSF2020]decrypto-1的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [CISCN2018]oldstream
- 下一篇: [羊城杯 2020]Power