def file_encrypt(filepath): """ 对文件进行DES-CBC加密,并用RSA加密key和iv :param filepath: 原文件路径 :return: 加密文件路径, 原文件md5值, 加密后的key, 加密后的iv """ # 随机生成key和iv key, iv = get_des_param() # 打开原文件 origin_file = open(filepath, 'rb') origin_filedata = origin_file.read().decode('latin') # 计算原文件的消息摘要 origin_digest = md5(origin_filedata) # 加密后文件的地址(统一加上.encrypted后缀) encrypted_filepath = filepath + ".encrypted" # 写入加密文件 encrypted_file = open(encrypted_filepath, 'wb') encrypted_file.write( DES.des_cbc_encrypt(origin_filedata, key, iv).encode('latin')) # 关闭文件 origin_file.close() encrypted_file.close() # 用client的公钥对key和iv进行加密 key_encrypted = RSA.Encrypt(libnum.s2n(key), server_e, server_n) iv_encrypted = RSA.Encrypt(libnum.s2n(iv), server_e, server_n) return encrypted_filepath, origin_digest, key_encrypted, iv_encrypted
def test_s2n_n2s(): s = b"long string to test" val = 2418187513319072758194084480823884981773628276 assert s2n(s) == val assert n2s(val) == s with pytest.raises(TypeError): s2n(100) with pytest.raises(TypeError): n2s("qwe")
def transfer_encrypt(message): """ 对分组传输的每一个分组进行des_cbc加密,且每次使用不同的key和iv :param message: 被加密的分组 :return: key,iv,cipher """ key, iv = get_des_param() cipher = DES.des_cbc_encrypt(message, key, iv, 'b') # 用server的公钥对key和iv进行加密 key_encrypted = RSA.Encrypt(libnum.s2n(key), server_e, server_n) iv_encrypted = RSA.Encrypt(libnum.s2n(iv), server_e, server_n) return key_encrypted, iv_encrypted, cipher
def encipher(plaintext, pk): m = libnum.s2n(plaintext) print(m) n, g = pk r = random.randint(1, n ** 2) c = gmpy2.powmod(g, m, n ** 2) * gmpy2.powmod(r, n, n ** 2) % (n ** 2) return c
def encrypt(info_list): flag_backup = libnum.s2n(flag) enc_flag_binlist = [] for i in range(bits_length): info = info_list[i] flag_temp = flag_backup res = 0 # this is the first step while info != 0: temp = info & 1 info = info >> 1 res = res << 1 res += flag_temp & temp flag_temp = flag_temp >> 1 # this is the first step # this is not end >:< enc_flag = 0 while res != 0: enc_flag += res & 1 res = res >> 1 # this is not end >:< enc_flag = enc_flag & 1 # what is this enc_flag_binlist.append(enc_flag) return binlist_number(enc_flag_binlist)
def short_div(i=65537, b=16): if isinstance(i, bytearray): i = i.decode() if isinstance(i, str): i = libnum.s2n(i) retarr = [] while i > 0: retarr.append(i % b) i //= b return retarr[::-1]
def add(KEY, number, dec): key = libnum.s2n(KEY) key = (key + number) & mask KEY = libnum.n2s(key).rjust(BLOCK_SIZE, "\x00") dec = dec + (BLOCK_SIZE - len(dec) % BLOCK_SIZE) * "\x00" assert len(dec) % BLOCK_SIZE == 0 AES_ECB = AES.new(KEY, AES.MODE_ECB) return AES_ECB.encrypt(dec)
def xor(KEY, number, dec): key = libnum.s2n(KEY) #32Bytes to a big num key = (key ^ number) & mask #low 32 B KEY = libnum.n2s(key).rjust(BLOCK_SIZE, "\x00") dec = dec + (BLOCK_SIZE - len(dec) % BLOCK_SIZE) * "\x00" #dec\x00... assert len(dec) % BLOCK_SIZE == 0 AES_ECB = AES.new(KEY, AES.MODE_ECB) return AES_ECB.encrypt(dec)
def enc(m, pk): m = s2n(m) e, v = getrandbits(256), getrandbits(256) E, V = pow(g, e, p), pow(g, v, p) s = v + e * h2(n2s(E) + n2s(V)) c = m * pow(pk, e + v, p) % p cap = (E, V, s) return c, cap
def encipher(plaintext, pk): if(plaintext.isdigit()): m=int(plaintext) else: m = libnum.s2n(plaintext) n, g = pk r = random.randint(1, n ** 2) c = gmpy2.powmod(g, m, n ** 2) * gmpy2.powmod(r, n, n ** 2) % (n ** 2) return c
def append(m): p = getPrime(2048) q = getPrime(2048) n = p * q result = ["%s\n" % str(n)] pm = padding(flag) for i in range(32): e = getPrime(32) c = pow(s2n(pm), e, n) result.append("%s->%s\n" % (str(e), str(c))) return "".join(result)
def writeSc(): shellcode = asm(shellcraft.execve("sh")) base = elf.bss() i = 0 while i < len(shellcode): # print s2n(shellcode[i: i + 2]) payload = "%" + str(s2n(shellcode[i:i + 2])) + "c%8$hhn" payload = payload.ljust(16, "|") + p64(base + i) # print payload io.sendlineafter("> ", "2") io.sendlineafter("m4x\n", payload) i += 2
def build_forged_table(): global forged_table enckey = '\x00' * 16 cipher = AES.new(enckey, AES.MODE_ECB) payload = '\x00' + libnum.n2s(1) + '\x00' * 14 payload = cipher.encrypt(payload) forged_table[1] = enckey print '[ ] Running forging procedure...' while len(forged_table.keys()) < 7: enckey = os.urandom(16) cipher = AES.new(enckey, AES.MODE_ECB) roll = libnum.s2n(cipher.decrypt(payload)[:2]) if roll < 7 and roll > 1 and roll not in forged_table.keys(): forged_table[roll] = enckey
def encode(plaintext, pk): E = pk[0] n = pk[1] G = pk[2] P_B = pk[3] m = libnum.s2n(plaintext) k = random.randrange(1, n) P1 = ecc_mul(k, G, E, n) P2 = ecc_mul(k, P_B, E, n) x_y = get_x_y(E) Pt = x_y[random.randrange(0, len(x_y) - 1)] p = E[2] C = (m * Pt[0] + Pt[1]) % p ciphertext = [P1, ecc_add(Pt, P2, E), C] return ciphertext
def encrypt(): m = raw_input("请输入明文: ") p = genPrime(1024) q = genPrime(1024) n = p * q fi = (p - 1) * (q - 1) i = (p - 1) * (q - 1) - 1 while True: if gcd(i, (p - 1) * (q - 1)) == 1: e = i break i -= 1 c = pow(s2n(m), e, n) print "密文: ", c return p, q, n, e, c
def decodeBase64(src): delPaddingTail = {0: 0, 2: 4, 1: 2} value = '' n = src.count('=') sin = src[:len(src) - n] for c in sin: value += bin(table.find(c))[2:].zfill(6) value = value[:len(value) - delPaddingTail[n]] # print value middle = [] for i in range(8, len(value) + 1, 8): middle.append(int(value[i - 8:i], 2)) output = middle out = hex(s2n(''.join(map(chr, output))))[2:-1] # print out return out
def encipher(plaintext): long_val = libnum.s2n(plaintext) ciphertext = '' while long_val >= len(b58table): div, mod = div_mod(long_val, table_len) ciphertext = b58table[mod] + ciphertext long_val = div ciphertext = b58table[long_val] + ciphertext pad = 0 for c in plaintext: if c == '\x00': pad += 1 else: break ciphertext = b58table[0] * pad + ciphertext return ciphertext
def sign(m, d, n): """ 对消息m进行签名 :param m: 消息m :param d: 签名用的私钥 :param n: 签名用的公钥 :return: 消息m的签名 """ d = int(d) n = int(n) # 先用md5产生消息的摘要 digest = md5(m) # 转为10进制 digest = libnum.s2n(digest) # 对摘要进行签名 s = pow(digest, d, n) return hex(s)[2:]
def b64encrypt(src, msg): from libnum import n2s, s2n from base64 import b64encode lines = 0 ''' for i in range(len(src)): if src[i] == '\n': lines += 1 length = s2n(msg).bit_length() if lines < 2 * length: return 'Failed' ''' put = [] src = src.split('\n') container = 0 for i in range(len(src)): src[i] += '\n' length = len(src[i]) container += - (length % 3) % 3 * 2 bins = bin(s2n(msg))[2:] bins = '0' * (- (len(bins) % 8) % 8) + bins print container, len(bins) assert container >= len(bins) bins += '0' * (container - len(bins)) index = 0 for i in range(len(src)): cur = b64encode(src[i]) src[i] = cur equal = 0 if cur[-1] == '=': equal += 1 if cur[-2] == '=': equal += 1 if equal == 0: continue if index >= container: break add = int(bins[index: index + 2 * equal], 2) index += 2 * equal change = cur[- equal - 1] assert code.index(change) ^ add == code.index(change) + add change = code[code.index(change) ^ add] src[i] = src[i][0: - equal - 1] + change + '=' * equal return '\n'.join(src)
def check(m, s, e, n): """ 对签名进行验证 :param m: 消息 :param s: 消息的的签名 :param e: 公钥e :param n: 公钥n :return: 是否通过验证 """ s = int(s, 16) e = int(e) n = int(n) # 先用md5产生消息的摘要 digest = md5(m) # 转为10进制 digest = libnum.s2n(digest) # 用公钥对进行验证 temp = pow(s, e, n) if digest == temp: return True else: return False
def __init__(self, args): self.args = args if self.args.verbose: log.setLevel(logging.DEBUG) self.n = args.N or None self.e = args.e or None self.p = args.p or None self.q = args.q or None self.d = args.d or None # high bits of factor self.hbop = args.KHBFA or None self.pbits = args.pbits or None self.sageworks = args.sageworks self.data = args.data or None # 是否需要解密密文 if self.args.decrypt: with open(self.args.decrypt, 'r') as f: self.c = libnum.s2n(f.read().strip()) elif self.args.decrypt_int: self.c = self.args.decrypt_int else: self.c = None
def main(): while True: mode = input("\n请选择模式:\n[E]加密\t[D]解密\n") if mode == 'E' or mode == 'e': m = input("请输入明文:\n") nbits = input("请输入位数:\n") e, n, d = get_keys(nbits) print("公钥e为: " + str(e)) print("公钥n为: " + str(n)) print("私钥d为: " + str(d)) print("明文为: " + m) m = libnum.s2n(m) # print(m) c = Encrypt(m, e, n) print("密文为(10进制): " + str(c)) elif mode == 'D' or mode == 'd': c = input("请输入密文(10进制):\n") d = input("请输入私钥d:\n") n = input("请输入公钥n:\n") c = Decrypto(int(c), d, n) c = libnum.n2s(c) print("密文为: " + str(c)) else: continue
#!/usr/bin/python import base64 import libnum n1 = 123948613128507245097711825164030080528129311429181946930789480629270692835124562568997437300916285601268900901495788327838386854611883075845387070635813324417496512348003686061832004434518190158084956517800098929984855603216625922341285873495112316366384741709770903928077127611563285935366595098601100940173 n2 = 122890614849300155056519159433849880305439158904289542874766496514523043027349829509818565800562562195671251134947871996792136355514373160369135263766229423623131725044925870918859304353484491601318921285331340604341809979578202817714205469839224620893418109679223753141128229197377934231853172927071087589849 e = 65537 q = libnum.gcd(n1,n2) # calculate gcd to discover a prime factor in common p = n1 / q phi = (p-1) * (q - 1) c = libnum.s2n(base64.b64decode(open('ciphertext.txt','r').read())) d = libnum.invmod(e,phi) m = pow(c,d,n1) print "[+] Flag: " + libnum.n2s(m)
#!/usr/bin/env python from Crypto.PublicKey import RSA import RSAwienerHacker import libnum c = libnum.s2n(open('ciphertext.bin').read()) publicKey = RSA.importKey(open('key.public').read()) n = publicKey.n e = publicKey.e d = RSAwienerHacker.hack_RSA(e,n) print libnum.n2s(pow(c,d,n))
def rsa_encrypt(m): return pow(s2n(m), e, n)
def xor(a, b): return s2n(''.join([chr(ord(i) ^ ord(j)) for i, j in zip(a, b)]))
import libnum p = 33499881069427614105926941260008415630190853527846401734073924527104092366847259 q = 34311544767652906613104559081988349779622789386528780506962212898921316785995851 e = 65537 c = 1041107528071306841173559309021779797565643224122373681605690175807597543772146942110201234780086486779654727917253504583448809504547742912197821315234006639347 n = p * q phi = (p - 1) * (q - 1) d = libnum.modular.invmod(e, phi) s="Trinityctf{RS4_1s_rs4lly_easylkjsadfhlkjsa!}" print pow(libnum.s2n(s),e,n) print libnum.n2s(pow(c, d, n)) #easyctf{wh3n_y0u_h4ve_p&q_RSA_iz_ez_7829d89f}
#!/usr/bin/env python import gmpy2 import libnum c1 = 112376755434839067242492450580926874835238627566940029196532175644877689078482714802636681537478746972878719135123815462672622666337365766404438579837929587693947036556506459672209528097159093195480318719604062458476883089712408549646871208319887232708573834573129807851612788612229862109446349174773685766921 k = 151397348765463697819328127490368915291237595957138740365628078489836085372845681091989345334904026246892900348971981402476845038743843701086311667536372419728644485998870855126715225674611022660290971207449534822797616008980284083777280866124762176520095351401654370256535990768524594118090702757650148363921 c2 = 120085813769601903784459580746767828105716607333492124010803514777437504109331448009890874939858984666641139819379969714070220763093188551966830630639308142299719976258227450642141963425187429636880593480951498406380068747404115889400485463839002674872020074254287490910994729347868122864760194135575038263365 q = 133694097868622092961596455982173439482901807533684907590429464542321832157724052684517499871073826858762297729480414306161113412741865099163152505447334863097434932940729269605986418443532208942119505043634990271717198694190123478547503837269948205839761848366722796091382894026537012764323367229104988051357 c3 = 53913320010474614353771348695262553935361078517742942745359182152882204780769206005474818637010209561420480280523029509375286538886061621596249179407728697515399046471231513536340506648832858695583318765423245104561512700887050932667507358898646356134386213016528778706360147066411877832628237361011621917972 key = libnum.s2n('CoCoCoCoCoCoCoCoCoCoCoCoCoCoCoCoCoCoCoCoCoCoCoCo') t = c2 * gmpy2.invert(key, q) % q m = c3 * gmpy2.invert(t, q) % q flag = libnum.n2s(m) print flag
import base64 from pwn import * from libnum import s2n # context.log_level = "debug" p = remote("118.31.18.75", 20013) iv = p.readline() p.recvuntil("work:") iv = base64.b64decode(iv) for x in xrange(100000000000): if hashlib.md5(iv + str(x)).hexdigest().startswith("0000"): p.sendline(base64.b64encode(str(x))) break t = s2n("flag") e = 0x10001 p.recvuntil("n: ") n = p.readline().strip() n = int(n[2:-1], 16) print "n: " + hex(n) print p.recvuntil("x: ") # x = n # while True: # if hex(x)[2:10] == '666c6167': # print x # break # x += n y = pow(t, e, n)
#!/usr/bin/python # coding=utf-8 import gmpy2 import libnum from Crypto.PublicKey import RSA # 读取公钥参数 with open('pubkey.pem', 'r') as f: key = RSA.importKey(f) N = key.n e = key.e print N with open('flag.enc', 'r') as f: cipher = f.read() cipher = libnum.s2n(cipher) print cipher print "please input p" p = int(raw_input(), 10) print 'please input q' q = int(raw_input(), 10) # 计算yp和yq inv_p = gmpy2.invert(p, q) inv_q = gmpy2.invert(q, p) # 计算mp和mq mp = pow(cipher, (p + 1) / 4, p) mq = pow(cipher, (q + 1) / 4, q) # 计算a,b,c,d
################### LAYER 1 ###################### print "[*] Solving layer 1: Weak key factored with ECM method" # layer 1 public key n = 94738740796943840961823530695778701408987757287583492665919730017973847138345511139064596113422435977583856843887008168202003855906708039013487349390571801141407245039011598810542232029634564848797998534872251549660454277336502838185642937637576121533945369150901808833844341421315429263207612372324026271327 e = 65537 # layer 1 factored with ECC method p = 9733382803370256893136109840971590971460094779242334919432347801491641617443615856221168611138933576118196795282443503609663168324106758595642231987245583 q = 9733382803370256893136109840971590971460094779242334919432347801491641617443615856221168611138933576118196795282443503609663168324106758595642231987246769 # valid p and q right!? assert(n % p == 0) assert(n % q == 0) c = libnum.s2n(open('almost_almost_almost_almost_there.encrypted','rb').read()) phi = (p - 1) * (q - 1) d = libnum.invmod(e, phi) m = pow(c,d,n) zippassword = libnum.n2s(m) ################### LAYER 2 ###################### print "[*] Solving layer 2: Common factors!" # unzip layer2 unzip = subprocess.check_output(['unzip','-o','-P',zippassword,'almost_almost_almost_almost_there.zip']) # get next modulus l2n = int(subprocess.check_output(['openssl', 'rsa', '-noout', '-modulus', '-pubin', '-in', 'almost_almost_almost_there.pub']).split('=')[1],16) # load ciphertext l2c = libnum.s2n(open('almost_almost_almost_there.encrypted','rb').read())
import hmac from libnum import n2s,s2n import hashlib from Crypto.Cipher import DES dhp=s2n('\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xC9\x0F\xDA\xA2\x21\x68\xC2\x34\xC4\xC6\x62\x8B\x80\xDC\x1C\xD1\x29\x02\x4E\x08\x8A\x67\xCC\x74\x02\x0B\xBE\xA6\x3B\x13\x9B\x22\x51\x4A\x08\x79\x8E\x34\x04\xDD\xEF\x95\x19\xB3\xCD\x3A\x43\x1B\x30\x2B\x0A\x6D\xF2\x5F\x14\x37\x4F\xE1\x35\x6D\x6D\x51\xC2\x45\xE4\x85\xB5\x76\x62\x5E\x7E\xC6\xF4\x4C\x42\xE9\xA6\x37\xED\x6B\x0B\xFF\x5C\xB6\xF4\x06\xB7\xED\xEE\x38\x6B\xFB\x5A\x89\x9F\xA5\xAE\x9F\x24\x11\x7C\x4B\x1F\xE6\x49\x28\x66\x51\xEC\xE6\x53\x81\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF') dhg=2 dhpi=s2n('\xDB\x58\x40\xCD\x93\x72\x8B\x76\xD1\x71\xE0\xD7\x63\xBC\x78\x94\xF9\xAC\xA4\x1E\xD0\x2C\x07\xFB\x2B\x10\xEC\x6F\xF9\x43\x43\xBC\x65\x81\x36\x62\x79\x0A\x1B\x51\x88\x13\xD4\x97\x42\x35\x73\xFF\xC7\x70\xDA\xC8\xEF\x18\x34\x4D\x99\x53\x2E\x0A\x5D\x1E\xF4\x43\x04\x9C\xB0\x6B\xA8\x69\x9D\x49\x04\xF4\xD4\x70\xD1\xB9\x2E\x2B\x0D\x86\x21\x2D\x89\xFF\x8E\xDE\x90\x01\xD5\x69\x7F\x6C\xB4\x2E\x71\x5D\x0C\x49\x07\xBE\x6B\x62\x28\x0B\xEE\x8F\xDD\xAE\x60\x48\xCE\x47\x9A\xED\x9B\x0F\xF0\x3B\xAA\x54\x93\x5D\xC1\x28\xF7\x5D') dhpr=s2n('\x7C\xFA\x40\x2B\x3F\xD6\x7B\xF1\xF4\xDE\x20\x4A\x6B\x8A\xF8\x44\x14\x4F\x1F\x8C\x27\x5F\x5A\x93\xD8\xA6\xCA\xDF\xB2\x95\xA4\xE8\x20\xE2\x5C\x3D\x18\x48\x76\xAF\xC5\x31\x04\x67\x4C\x73\xC3\xFF\x26\xA2\x9C\x09\xC9\xB5\x5F\xB4\xD8\x98\x49\xA2\x37\x62\xE3\x2A\xA0\xCF\x83\x88\x4A\x1C\x06\x97\x5A\x35\x5B\xF6\xAA\x98\x79\x0D\xEB\xC2\xBF\xFB\x83\x41\x15\x02\x79\xEB\xC1\x2C\xBF\xB9\xF6\x77\xB0\xE5\xFF\x34\x97\x82\x51\xCB\xF7\x8E\x45\x14\xCE\xB5\x3F\xAF\xB0\x14\x85\x43\x50\x8A\xB6\x45\x95\x15\x2A\xA3\x2A\xA0\xAD\x3A') rnda=217227749115035578303115991742495457394555440946835514581165277149237157052227668403784536767326288414650333354135580192264021152700162919686294299135414279647180805138410303 rndb=162938785206550875564738389732121139210582420609551964823025935645144235158388990738283910163537245485378422827807450374238085561899166174523954514183122557647647478238328309 dh=pow(dhpi,rndb,dhp) dh1=pow(dhpr,rnda,dhp) assert dh==dh1 dh=n2s(dh) Ni_b='\x97\x00\x3e\x96\xbc\x24\xfc\xf4\x33\x01\xd1\xc4\x3c\x8f\x39\xdb' Nr_b='\x91\xf6\x7d\x69\x87\xaf\x88\x55\xe0\x0f\x7d\xc7\x7c\x1f\x7a\x54' key='L2Lkey' c='\x73\x3D\x05\xC9\x29\xE8\x90\x87\x18\x64\x2E\xEE\xBE\x68\xA3\xC7\x10\xC1\x2C\x09\xB2\x2A\x5C\xFB\x14\xED\xD9\x05\x71\xC3\xDB\x7B\x1B\x59\x8E\xF4\x78\xA2\x34\x4E\x44\x92\x50\x79\x20\xF9\x07\x02' CKYI='\x9a\x4f\x20\xcd\xb1\x31\x48\xb8' CKYR='\x31\x32\x33\x36\x35\x34\x33\x32' #dh=137247906241040090919876955385584427953146893027590677633961074744220353577993931739850208608460762088573995334151351475802221588909889893766807776125874588605505199531437797262808324394122286799024347058396174077697126829526904781090123860153287092978076421343799399389218986715724110092376523175888317759494 skeyid = hmac.new(key, Ni_b+Nr_b).digest() skeyid_d = hmac.new(skeyid, dh+CKYI + CKYR + '\x00').digest() skeyid_a = hmac.new(skeyid, skeyid_d + dh + CKYI + CKYR + '\x01').digest() skeyid_e = hmac.new(skeyid, skeyid_a + dh + CKYI + CKYR + '\x02').digest() deskey=skeyid_e[:8] iv=hashlib.md5(n2s(dhpi)+n2s(dhpr)).digest()[:8] cipher = DES.new(deskey, DES.MODE_CBC, iv) print cipher.decrypt(c)
import libnum from secret import flag n = 31648734237121093449062759741858353305299887460770378610317325262532812380992998717086045560716165196764876375024736812043316931187449612112014480335819632714635828887393277480117469682571740475521815029501119616029222685021833456834860463301835674320610441456152948762730967186631332998314439886858424113209771045636380932420113750370162135069772576775040641310241869572513488894613647466722538462125698729611696700513321039673589745449355070643639740553615493170049122321689282686291783694560650322957955382056776701778000873105279611461240600373669009171156764610102006874690207503067227784467578546117377910059849 e = 65537 m = libnum.s2n(flag) c = pow(m, e, n) print(c) # 8472470163184012462000528080165090036188635885351596354139960232632956476301235845514827002690956926418292313944863809902769808978125514574094431792449203362125295767224649917756465720590402146607448107700602949310739551154185709505943529176162811567787744455172636958664487513824170824375184591735235862997624339895241609184318108298806242891811364998857087830133524421290948873392796863425163637415895626597006868886489528223728832282320568060824925378471122592356209291540463778941231812179060437264730095781564995912183149503687379604059903141658253650016548620225566653730700129092787790523080898273898653528474
def test_s2n(self): s = "long string to test" val = 2418187513319072758194084480823884981773628276 self.assertEqual(libnum.s2n(s), val) self.assertRaises(TypeError, libnum.s2n, 100)