from bfv.batch_encoder import BatchEncoder from bfv.bfv_encryptor import BFVEncryptor from bfv.bfv_decryptor import BFVDecryptor from bfv.bfv_key_generator import BFVKeyGenerator from bfv.bfv_parameters import BFVParameters from util.polynomial import Polynomial from util.ciphertext import Ciphertext import os
from bfv.batch_encoder import BatchEncoder from bfv.bfv_encryptor import BFVEncryptor from bfv.bfv_decryptor import BFVDecryptor from bfv.bfv_key_generator import BFVKeyGenerator from bfv.bfv_parameters import BFVParameters from util.polynomial import Polynomial from util.ciphertext import Ciphertext
######################################################################################### calc msg defcheck(msg): p,n = 3**40 + 118, 1337 for c in msg: if c == '+': n += n elif c == '*': n *= n n %= p return n == 31337
p,n = 3**40 + 118, 1337 Fp = GF(p) g = Fp.primitive_element() t = discrete_log(Fp(2), Fp(g)) # g^t = 2 a = discrete_log(Fp(1337), Fp(g)) # g^a = 1337 b = discrete_log(Fp(31337), Fp(g)) # g^b = 31337
from sage.allimport * from sage.stats.distributions.discrete_gaussian_integer import DiscreteGaussianDistributionIntegerSampler from secret import flag
defgenerate_key(): whileTrue: F = Matrix([[PRz(My_generator(Df, d)) for _ inrange(n)] for _ inrange(n)]) G = Matrix([[PRz(My_generator(Df, d)) for _ inrange(k)] for _ inrange(n)]) try: H = F.change_ring(PRqm).inverse() * G.change_ring(PRqm) H = Matrix([[PRz(Hij.lift()) for Hij in Hi] for Hi in H.transpose()]).transpose() return F, G, H except ArithmeticError: continue
d = 64 q = 12289 p = 17 n = 2 k = 1 sigma_f, sigma_s, sigma_e = 0.4, 0.6, 0.6
PRq = PolynomialRing(Zmod(q), 'xq') PRp = PolynomialRing(Zmod(p), 'xp') PRz = PolynomialRing(ZZ, 'xz') mod_polynomial = PRz.cyclotomic_polynomial(d * 2) PRqm = PRq.quotient(mod_polynomial) PRpm = PRp.quotient(mod_polynomial) Df = get_accurate_Discrete_Gaussian(sigma_f) Ds = get_accurate_Discrete_Gaussian(sigma_s) De = get_accurate_Discrete_Gaussian(sigma_e) m = [] base = int.from_bytes(flag, byteorder='big') while base > 0: m.append(int(base % p)) base = base // p m = PRz(m)
s = vector([PRz(My_generator(Ds, d)) for _ inrange(n)]) e = PRz(My_generator(Ds, d)) open('data.txt', 'w').write('H = ' + str([list(vi) for vi in H]) + '\n' + 'c = ' + str(c) + '\n')
#n:The highest degree of a modular polynomial #v:vector of modular polynomial #a:vector of a polynomial multiplier
#aim to construct a matrix of c=a*b%v defconstruct_poly_mul_mat(n,v,b): assert v[-1] == 1#use this after monic
#step1 construct a matrix of d=a*b mat1 = Matrix(ZZ,n,2*n-1) for i inrange(n): for j inrange(n): mat1[i,j+i] = b[j]
#step2 construct a matrix of c=d%v mat2 = Matrix(ZZ,2*n-1,n) for i inrange(n): mat2[i,i] = 1 for i inrange(n,2*n-1): for j inrange(i-n,n): mat2[i,j] = -v[j-(i-n)] init_row = vector(ZZ,n*[0]) for j inrange(i-n): temp = -v[n-1-j]*vector(ZZ,mat2[i-j-1]) init_row += temp for j inrange(n): mat2[i,j] += init_row[j] #step3 multiply them and return return(mat1*mat2)
L = block_matrix(ZZ, [ [identity_matrix(n), matrix.zero(n,n), H1], [matrix.zero(n,n), identity_matrix(n), H2], [matrix.zero(n,n), matrix.zero(n,n), identity_matrix(n)*q] ]) L = L.BKZ(block_size=30)
Found = 0 for i inrange(128): for j inrange(i+1,128): F = Matrix(PRz, [ [list(map(int,L[i][:n])), list(map(int,L[i][n:2*n]))], [list(map(int,L[j][:n])), list(map(int,L[j][n:2*n]))] ])
G = Matrix(PRqm, [ [list(map(int,L[i][-n:]))], [list(map(int,L[j][-n:]))] ])
FF = Matrix(PRqm,2,2) for ii inrange(2): for jj inrange(2): FF[ii,jj] = PRqm(F[ii,jj])
FFF = Matrix(PRpm,2,2) for ii inrange(2): for jj inrange(2): FFF[ii,jj] = PRpm(F[ii,jj])
from Crypto.Util.number import * from tqdm import *
classShamirSS: def__init__(self, coefs, value): self.coefs = coefs self.value = value
shares = [] for i in trange(10000): files = "share_" + str(i) + ".sobj" sharesi = load(files) shares.append(sharesi)
defconvert_2_Matrix(single_share): L = [] R = [] for i in single_share: L.append(i.coefs) R.append(i.value) L = Matrix(Zmod(257), L) R = vector(Zmod(257), R) A = L[:, :36] B = L[:, 36:] if(B.rank() != 36): v = B.left_kernel().basis()[0] return (v*A, v*R)
L = Matrix(Zmod(257), 0, 36) R = [] for i in tqdm(shares): res = convert_2_Matrix(i) if(res != None): l, r = res L = L.stack(l) R.append(r) R = vector(Zmod(257), R)
flag = L.solve_right(R) print("".join(list(map(chr, flag))))
defencode(message, k, ps=None): '''Take a message of length inferior to k - 11 and return the concatenation of length k: 0x00 || 0x02 || PS || 0x00 || message where PS is a random string containing no zero byte of length k - len(message) - 3. message - the message to encode, a byte string k - the length of the padded byte string ps - a fixed string to use instead of generating a random one, it's necessary for testing using test vectors, rnd - the random generator to use, it must conform to the interface of the random.Random class. ''' m_len = len(message) if m_len > k - 11: raise Exception('MessageTooLong') ps_len = k - len(message) - 3 if ps: iflen(ps) != ps_len: raise Exception('wrong ps length', len(ps), ps_len) else: ps = b"" whilelen(ps) != ps_len: byte = os.urandom(1) if byte != b"\x00": ps += byte returnb'\x00\x02' + ps + b'\x00' + message
defdecode(message: bytes): ''' Verify that a padded message conform to the PKCSv1 1.5 encoding and return the unpadded message. ''' if message[:2] != b'\x00\x02': raise Exception('DecryptionError') i = message.find(b'\x00', 2) if i == -1: raise Exception('DecryptionError') if i < 10: raise Exception('DecryptionError') return message[i+1:]
from Crypto.Util.number import * from tqdm import * from pwn import *
context.log_level = "CRITICAL"
SUCCESS = 0 for ROUNDS in trange(100): sh = process(["python3", "crypto2.py"])
#################################################################################### get n, e sh.recvuntil(b"[+] n =") n = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] e =") e = int(sh.recvline().strip().decode())
#################################################################################### get aeskey sh.recvuntil(b"[+] x0 =") x0 = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] x1 =") x1 = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] v =") v = x0 sh.sendline(str(v).encode()) sh.recvuntil(b"[+] M0 =") M0 = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] M1 =") M1 = int(sh.recvline().strip().decode()) aeskey = long_to_bytes(M0)[-32:] sh.recvuntil(b"[+] K =")
nums = 14 KK = int(sh.recvline().strip().decode()) KK = bin(KK)[2:].zfill(1024)
#################################################################################### CCA rounds = 70 padding = bytes_to_long(b"\x00\x02"+126*b"\x80") K = (bin((M1 - padding) >> (1024-nums))[2:]).zfill(nums) known = nums
secrets = [] for i inrange(1, rounds+1): sh.recvuntil(b"[+] x0 =") x0_i = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] x1 =") x1_i = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] v =") v = (pow(2, (known-1)*e, n) * (x0-x1) + x0_i) % n sh.sendline(str(v).encode())
from Crypto.Util.number import * from tqdm import * from pwn import *
context.log_level = "CRITICAL"
defcomp(a1,a2): for i inrange(len(a1)): if(a1[i] != a2[i] and a1[i] != "*"): returnFalse returnTrue
SUCCESS = 0 for ROUNDS in trange(10000): sh = process(["python3", "crypto2.py"])
#################################################################################### get n, e sh.recvuntil(b"[+] n =") n = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] e =") e = int(sh.recvline().strip().decode())
#################################################################################### get aeskey sh.recvuntil(b"[+] x0 =") x0 = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] x1 =") x1 = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] v =") v = x0 sh.sendline(str(v).encode()) sh.recvuntil(b"[+] M0 =") M0 = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] M1 =") M1 = int(sh.recvline().strip().decode()) aeskey = long_to_bytes(M0)[-32:] sh.recvuntil(b"[+] K =")
nums = 15 nums2 = 3 KK = int(sh.recvline().strip().decode()) KK = bin(KK)[2:].zfill(1024)
#################################################################################### CCA padding = bytes_to_long(b"\x00\x02"+126*b"\x80") rounds = 70 K = ["*"for i inrange(1024)] ind1 = 0 for i inrange(nums): K[ind1] = bin((M1 - padding) >> (1024-nums))[2:].zfill(nums)[i] ind1 += 1 for i inrange(nums2): K[-(33*8)+i] = (bin(M1)[2:]).zfill(1024)[-(33*8)+i] known = nums
defALL0(k): returnint(k.replace("*", "0"), 2)
secrets = [] for i inrange(1, rounds+1): sh.recvuntil(b"[+] x0 =") x0_i = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] x1 =") x1_i = int(sh.recvline().strip().decode()) sh.recvuntil(b"[+] v =") v = (pow(2, (known-1)*e, n) * (x0-x1) + x0_i) % n sh.sendline(str(v).encode())