#CKKS特性:对于CKKS同态加密,有ENC(a+b)=ENC(a)+ENC(b),乘,减也符合,还有a*ENC(b)=ENC(ab),除此之外无法进行别的功能(如比较),除了反转之外的功能
#题面有输出128个不同值,之后CKKS加密并提供base64后数值,要返回原值的大小排序
#这里的原理是利用ENC(a-b)=ENC(a)-ENC(b),先小化数值,然后可以利用与0关系判断大小,接下来就是构造矩阵把数值一一比较
#比较函数:>0.000001,记1,>-0.000001,记0.5,<,记0,中间給0.5是为了自己减自己,最后要减0.5消除他
#题外点,CKKS加密最后是小数,所以只要相近整数就可以
#本脚本要和ps.py使用
import base64
import math
import time
from typing import Callable, List

import tenseal as ts
import tenseal.sealapi as sealapi
import ps

from pwn import remote, process, context


HOST = "1.95.113.92"
PORT = 9999

context.log_level = "debug"

with open("ctx.public", "rb") as f:
    ctx_bytes = f.read()

io = remote(HOST, PORT)

io.recvuntil(b"pow) solve ")
pow_str = io.recvline().strip()

r = process(["python3", "pow.py", "solve", pow_str])
r.recvline()
io.sendlineafter(b"Solution? ", r.recvline().strip())
io.recvuntil(b"Correct\n")

ct_bytes = base64.b64decode(io.recvline().strip())

start = time.time()

ctx_high = ts.context_from(ctx_bytes)
ctx = ctx_high.seal_context().data

enc = ts.ckks_vector_from(ctx_high, ct_bytes).ciphertext()[0]

public_key = ctx_high.public_key().data

galois_keys = sealapi.GaloisKeys()
galois_keys.load(ctx, "galois.key")

relin_keys = ctx_high.relin_keys().data

encryptor = sealapi.Encryptor(ctx, public_key)
evaluator = sealapi.Evaluator(ctx)
encoder = sealapi.CKKSEncoder(ctx)


plain_mul = sealapi.Plaintext()
encoder.encode([1.0 / 512] * 128, 2**40, plain_mul)
evaluator.multiply_plain_inplace(enc, plain_mul)
evaluator.rescale_to_next_inplace(enc)


def transform(enc):
    base = None

    for i in range(128):
        ct_new = sealapi.Ciphertext()
        evaluator.rotate_vector(enc, 128 * ((128 - i) % 128) + i, galois_keys, ct_new)

        if i == 0:
            base = ct_new
        else:
            evaluator.add_inplace(base, ct_new)

    plain_mul = sealapi.Plaintext()
    encoder.encode(
        [1.0 if i % 128 == 0 else 0.0 for i in range(32768 // 2)],
        2**40,
        plain_mul
    )

    evaluator.mod_switch_to_inplace(plain_mul, base.parms_id())
    evaluator.multiply_plain_inplace(base, plain_mul)
    evaluator.rescale_to_next_inplace(base)

    return base


def RepC(enc):
    base = sealapi.Ciphertext()
    evaluator.rotate_vector(enc, 0, galois_keys, base)

    for i in range(1, 128):
        ct_new = sealapi.Ciphertext()
        evaluator.rotate_vector(enc, i + 128 * 127, galois_keys, ct_new)
        evaluator.add_inplace(base, ct_new)

    return base


def EvalChebyshevCoefficients(
    func: Callable[[float], float],
    a: float,
    b: float,
    degree: int
) -> List[float]:
    coeff_total = degree + 1
    b_minus_a = 0.5 * (b - a)
    b_plus_a = 0.5 * (b + a)
    pi_by_deg = math.pi / float(coeff_total)

    function_points = [0.0] * coeff_total

    for i in range(coeff_total):
        x = math.cos(pi_by_deg * (i + 0.5)) * b_minus_a + b_plus_a
        function_points[i] = func(x)

    mult_factor = 2.0 / float(coeff_total)
    coefficients = [0.0] * coeff_total

    for i in range(coeff_total):
        s = 0.0
        for j in range(coeff_total):
            s += function_points[j] * math.cos(pi_by_deg * i * (j + 0.5))
        coefficients[i] = s * mult_factor

    return coefficients


def cmp_func(x):
    if x > 0.00001:
        return 1
    elif x > -0.00001:
        return 0.5
    else:
        return 0


def compare(a, b):
    tmp = sealapi.Ciphertext()
    evaluator.sub(b, a, tmp)

    poly = EvalChebyshevCoefficients(cmp_func, -1.0, 1.0, 512)
    tmp = ps.eval_poly_ps(tmp, poly, evaluator, encoder, encryptor, relin_keys)

    base = sealapi.Ciphertext()
    evaluator.rotate_vector(tmp, 0, galois_keys, base)

    for i in range(1, 128):
        ct_new = sealapi.Ciphertext()
        evaluator.rotate_vector(tmp, 128 * i, galois_keys, ct_new)
        evaluator.add_inplace(base, ct_new)

    plain_sub = sealapi.Plaintext()
    encoder.encode([0.5 for _ in range(32768 // 2)], 2**40, plain_sub)

    evaluator.mod_switch_to_inplace(plain_sub, base.parms_id())

    target_scale = min(comp1.scale, comp2.scale)
    base.scale = target_scale
    plain_sub.scale = target_scale

    evaluator.sub_plain_inplace(base, plain_sub)

    return base


enc = transform(enc)
comp1 = RepC(enc)

comp2 = ts.ckks_vector_from(ctx_high, ct_bytes).ciphertext()[0]

plain_mul = sealapi.Plaintext()
encoder.encode([1.0 / 512] * (32768 // 2), 2**40, plain_mul)

evaluator.multiply_plain_inplace(comp2, plain_mul)
evaluator.rescale_to_next_inplace(comp2)

evaluator.mod_switch_to_inplace(comp2, comp1.parms_id())

target_scale = min(comp1.scale, comp2.scale)
comp1.scale = target_scale
comp2.scale = target_scale

print("[*] Comparing...")
target = compare(comp1, comp2)

target.save("tmp")
payload = base64.b64encode(open("tmp", "rb").read())

io.sendlineafter("😶‍🌫️ :".encode(), payload)

end = time.time()
print("[+] Done")
print("[+] Time taken:", end - start)

io.interactive()