1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
| import random, time import numpy as np from sage.all import PolynomialRing, Zmod, randint, inverse_mod from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split, StratifiedKFold from sklearn.metrics import accuracy_score, confusion_matrix, roc_auc_score import joblib
q = 1342261 n = 1031 PR = PolynomialRing(Zmod(q), "x") x = PR.gens()[0] Q = PR.quotient(x**n + 1)
SEED = 42 random.seed(SEED); np.random.seed(SEED)
TEST_XS = [-1]
R_smallF = 160
B_ratio = 70
N_POS = 20000 N_NEG = 20000 TEST_SIZE = 0.2 N_FOLDS = 5
ALPHA_GRID = (1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0) TARGET_TOTAL_ERR = 0.35 FP_BUDGET = 0.007 CLASS_PRIOR = (0.5, 0.5)
XGB_OK = False; LGB_OK = False try: import xgboost as xgb XGB_OK = True except Exception: pass if not XGB_OK: try: import lightgbm as lgb LGB_OK = True except Exception: pass
def lift_centered_int(a, q): a = int(a) % q return a if a <= q//2 else a - q
def eval_at_point(pk_list, t): V, p = 0, 1 for c in pk_list: V += int(c)*p p = (p*t) % q return lift_centered_int(V, q)
def smallF_candidates_intersection(V1, V2, R=R_smallF): """ 枚举 δ in [-R,R] 上的同余类: S1 = { F ≡ δ1 * V1^{-1} (mod q) } S2 = { F ≡ δ2 * V2^{-1} (mod q) } 取 S1 ∩ S2,返回: - match_cnt: 交集类数量 - min_abs_F: 交集中“最小 |F| 的代表”(F 取中心代表) - min_max_delta: 令该 F 成立的最小 max(|δ1|,|δ2|) 随机公钥几乎无交集;结构公钥常有交集,且有小 |F|。 """ if V1 % q == 0 or V2 % q == 0: return 1, 0, 0
inv1 = int(inverse_mod(V1 % q, q)) inv2 = int(inverse_mod(V2 % q, q))
cls1 = {} for d1 in range(-R, R+1): F1 = (d1 * inv1) % q b1 = abs(d1) if F1 not in cls1 or b1 < cls1[F1]: cls1[F1] = b1
match_cnt, min_abs_F, min_max_delta = 0, None, None
for d2 in range(-R, R+1): F2 = (d2 * inv2) % q if F2 in cls1: match_cnt += 1 F_cent = lift_centered_int(F2, q) cost = max(cls1[F2], abs(d2)) if (min_abs_F is None) or (abs(F_cent) < abs(min_abs_F)): min_abs_F = F_cent if (min_max_delta is None) or (cost < min_max_delta): min_max_delta = cost
if min_abs_F is None: return 0, q, R+1 return match_cnt, abs(min_abs_F), min_max_delta
def smallF_score(V1, V2, R=R_smallF): best = (10**9, None) for F in range(-R, R+1): if F == 0: continue Y1 = lift_centered_int(F*V1, q) if abs(Y1) >= best[0]: continue Y2 = lift_centered_int(F*V2, q) s = max(abs(Y1), abs(Y2)) if s < best[0]: best = (s, abs(F)) if s == 0: break return best
def ratio_consistency(V1, V2, B=B_ratio): best = 10**9 for a in range(-B, B+1): for b in range(-B, B+1): if a==0 and b==0: continue r = lift_centered_int(a*V1 - b*V2, q) ar = abs(r) if ar < best: best = ar if ar == 0: return 0 return best
def coeff_stats(pk_list): cs = [lift_centered_int(c, q) for c in pk_list] m = sum(cs)/n msq = sum(c*c for c in cs)/n bins = [q//64, q//32, q//16, q//8] fracs = [sum(1 for c in cs if abs(c)<=b)/n for b in bins] linf = max(abs(c) for c in cs) return [m, msq] + fracs + [linf]
def decision_feature_absF(pk1_list, pk2_list, R=R_smallF): V1 = eval_at_point(pk1_list, -1) V2 = eval_at_point(pk2_list, -1) hits = [] for F in range(-R, R+1): if F==0: continue Y1 = lift_centered_int(F*V1, q) if abs(Y1) > R: continue Y2 = lift_centered_int(F*V2, q) if abs(Y2) > R: continue if (V1*Y2 - V2*Y1) % q == 0: hits.append(abs(F)) if hits: uniq = sorted(set(hits)) return [len(uniq), min(uniq)] return [0, 0]
def extract_features(pk1_list, pk2_list): feats = [] V1 = eval_at_point(pk1_list, -1) V2 = eval_at_point(pk2_list, -1)
match_cnt, min_absF_inter, min_max_delta = smallF_candidates_intersection(V1, V2, R_smallF) feats += [match_cnt, min_absF_inter, min_max_delta]
s, bestF = smallF_score(V1, V2, R_smallF) feats += [s, (bestF if bestF else 0)] feats += [ratio_consistency(V1, V2, B_ratio)]
feats += [V1/(q/2), V2/(q/2)]
feats += coeff_stats(pk1_list) feats += coeff_stats(pk2_list)
feats += decision_feature_absF(pk1_list, pk2_list, R_smallF)
return feats
def extract_features_plus(pk1_list, pk2_list): return extract_features(pk1_list, pk2_list)
def GenNTRU_once(): while True: f = [randint(-1, 1) for _ in range(n)] g1 = [randint(-1, 1) for _ in range(n)] g2 = [randint(-1, 1) for _ in range(n)] fx = Q(f); g1x = Q(g1); g2x = Q(g2) try: h1 = (g1x / fx).lift() h2 = (g2x / fx).lift() return [int(c) % q for c in h1.list()], [int(c) % q for c in h2.list()] except Exception: continue
def RandPK_once(): pk1 = Q.random_element().lift() pk2 = Q.random_element().lift() return [int(c) % q for c in pk1.list()], [int(c) % q for c in pk2.list()]
def build_dataset(N0, N1, use_plus=True, verbose=True): X, y = [], [] if verbose: print(f"[+] Generating coin=0 (NTRU) : {N0}") for i in range(N0): pk1, pk2 = GenNTRU_once() X.append(extract_features_plus(pk1, pk2) if use_plus else extract_features(pk1, pk2)) y.append(1) if verbose and (i+1) % 500 == 0: print(f" - {i+1}/{N0}")
if verbose: print(f"[+] Generating coin=1 (random): {N1}") for i in range(N1): pk1, pk2 = RandPK_once() X.append(extract_features_plus(pk1, pk2) if use_plus else extract_features(pk1, pk2)) y.append(0) if verbose and (i+1) % 500 == 0: print(f" - {i+1}/{N1}")
return np.array(X, float), np.array(y, int)
def train_xgb(X_tr, y_tr, X_va, y_va): clf = xgb.XGBClassifier( n_estimators=600, max_depth=6, learning_rate=0.06, subsample=0.9, colsample_bytree=0.9, reg_lambda=1.0, reg_alpha=0.0, objective='binary:logistic', eval_metric='auc', random_state=SEED, n_jobs=4 ) clf.fit(X_tr, y_tr, eval_set=[(X_va, y_va)], verbose=False) return clf
def train_lgb(X_tr, y_tr, X_va, y_va): clf = lgb.LGBMClassifier( n_estimators=800, num_leaves=63, learning_rate=0.05, subsample=0.9, colsample_bytree=0.9, reg_lambda=1.0, random_state=SEED, n_jobs=4 ) clf.fit(X_tr, y_tr, eval_set=[(X_va, y_va)], eval_metric='auc', verbose=False) return clf
def train_rf(X_tr, y_tr): clf = RandomForestClassifier( n_estimators=800, max_depth=None, min_samples_split=2, min_samples_leaf=1, n_jobs=4, random_state=SEED ) clf.fit(X_tr, y_tr) return clf
def kfold_train(X, y, n_folds=5): skf = StratifiedKFold(n_splits=n_folds, shuffle=True, random_state=SEED) models, oof = [], np.zeros(len(y)) for i,(tr,va) in enumerate(skf.split(X,y),1): X_tr, X_va, y_tr, y_va = X[tr], X[va], y[tr], y[va] print(f"[+] Fold {i}/{n_folds} (XGB priority)") if XGB_OK: clf = train_xgb(X_tr, y_tr, X_va, y_va) elif LGB_OK: clf = train_lgb(X_tr, y_tr, X_va, y_va) else: clf = train_rf(X_tr, y_tr) models.append(clf) if hasattr(clf,"predict_proba"): p = clf.predict_proba(X_va)[:,1] else: if hasattr(clf,"decision_function"): df = clf.decision_function(X_va) p = (df-df.min())/(df.max()-df.min()+1e-9) else: p = clf.predict(X_va).astype(float) oof[va] = p auc = roc_auc_score(y_va, p) print(f" fold AUC = {auc:.4f}") return models, oof
def tune_threshold_by_cost(y_true, probs, alpha_fp=2.0, target_fp_rate=None): best_t, best_acc, best_cost, best_cm = 0.5, -1.0, 1e18, None for t in np.linspace(0.01,0.99,99): y_pred = (probs>=t).astype(int) cm = confusion_matrix(y_true, y_pred, labels=[1,0]) TP,FN = cm[0,0], cm[0,1] FP,TN = cm[1,0], cm[1,1] fp_rate = FP / max(FP+TN, 1) if (target_fp_rate is not None) and (fp_rate>target_fp_rate): continue acc = accuracy_score(y_true, y_pred) cost = alpha_fp*FP + FN if target_fp_rate is not None: if acc>best_acc: best_acc, best_t, best_cm = acc, t, cm else: if cost<best_cost: best_cost, best_t, best_cm = cost, t, cm if best_cm is None: for t in np.linspace(0.01,0.99,99): y_pred = (probs>=t).astype(int) cm = confusion_matrix(y_true, y_pred, labels=[1,0]) TP,FN = cm[0,0], cm[0,1] FP,TN = cm[1,0], cm[1,1] acc = accuracy_score(y_true, y_pred) cost = alpha_fp*FP + FN if cost<best_cost: best_cost, best_t, best_cm = cost, t, cm best_acc = acc return best_t, (best_acc, best_cm)
def auto_pick_alpha_threshold(y_true, oof_probs, alpha_grid=ALPHA_GRID, target_total_err_rate=TARGET_TOTAL_ERR, fp_budget_ratio=FP_BUDGET): best = None for a in alpha_grid: t, (acc, cm) = tune_threshold_by_cost(y_true, oof_probs, alpha_fp=a, target_fp_rate=fp_budget_ratio) TP,FN = cm[0,0], cm[0,1] FP,TN = cm[1,0], cm[1,1] err_rate = (FP+FN) / max(TP+FN+FP+TN,1) info = dict(alpha=a, threshold=t, acc=acc, cm=cm, err_rate=err_rate) if (best is None) or (err_rate<best["err_rate"]): best = info return best["alpha"], best["threshold"], best
def save_bundle(models, threshold, path="ntru_coin_xgb_bundle.pkl"): joblib.dump({"models":models, "threshold":threshold}, path) print(f"[+] Model bundle saved to {path}")
def load_bundle(path="ntru_coin_xgb_bundle.pkl"): b = joblib.load(path) print(f"[+] Model bundle loaded from {path}") return b["models"], b["threshold"]
def ensemble_predict_proba(models, X): probs=[] for clf in models: if hasattr(clf,"predict_proba"): p = clf.predict_proba(X)[:,1] else: if hasattr(clf,"decision_function"): df = clf.decision_function(X) p = (df-df.min())/(df.max()-df.min()+1e-9) else: p = clf.predict(X).astype(float) probs.append(p) return np.mean(probs, axis=0)
def predict_coin(models, threshold, pk1_list, pk2_list): feat = np.array(extract_features_plus(pk1_list, pk2_list), dtype=float).reshape(1,-1) p = ensemble_predict_proba(models, feat)[0] return bool(p>=threshold), float(p)
if __name__ == "__main__": print("=== NTRU coin 判别(强化版)===") print(f"lib: XGB={XGB_OK}, LGB={LGB_OK}") print(f"n={n}, q={q}, TEST_XS={TEST_XS}, R_smallF={R_smallF}, B_ratio={B_ratio}") print(f"dataset: pos={N_POS}, neg={N_NEG}, test_size={TEST_SIZE}, kfold={N_FOLDS}") t0 = time.time()
X, y = build_dataset(N_POS, N_NEG, use_plus=True, verbose=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=TEST_SIZE, stratify=y, random_state=SEED)
models, oof_probs = kfold_train(X_tr, y_tr, n_folds=N_FOLDS)
best_alpha, threshold, info = auto_pick_alpha_threshold( y_true=y_tr, oof_probs=oof_probs, alpha_grid=ALPHA_GRID, target_total_err_rate=TARGET_TOTAL_ERR, fp_budget_ratio=FP_BUDGET ) print(f"[AUTO] pick ALPHA_FP={best_alpha}, threshold={threshold:.3f}, err_rate={info['err_rate']:.4f}") print(f"[AUTO] OOF CM [[TP FN],[FP TN]]:\n{info['cm']}")
proba_te = ensemble_predict_proba(models, X_te) y_pred_te = (proba_te>=threshold).astype(int) acc_te = accuracy_score(y_te, y_pred_te) cm_te = confusion_matrix(y_te, y_pred_te, labels=[1,0]) auc_te = roc_auc_score(y_te, proba_te) print(f"[TEST] acc={acc_te:.4f}, auc={auc_te:.4f}\n[TEST] CM [[TP FN],[FP TN]]:\n{cm_te}")
save_bundle(models, threshold, "ntru_coin_xgb_bundle.pkl")
pk1_pos, pk2_pos = GenNTRU_once() pk1_neg, pk2_neg = RandPK_once() pp, sp = predict_coin(models, threshold, pk1_pos, pk2_pos) pn, sn = predict_coin(models, threshold, pk1_neg, pk2_neg) print(f"[Sanity] coin=0 -> {pp} (p={sp:.4f})") print(f"[Sanity] coin=1 -> {pn} (p={sn:.4f})") print(f"Done. Time: {time.time()-t0:.1f}s")
|