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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
| import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.optimize import linprog, milp, LinearConstraint, Bounds import pandas as pd from itertools import product
operations = { 'Type A (Order 1)': {'random_cost': 2, 'security': 10, 'masking_order': 1}, 'Type B (Order 2)': {'random_cost': 5, 'security': 25, 'masking_order': 2}, 'Type C (Order 3)': {'random_cost': 9, 'security': 45, 'masking_order': 3}, 'Type D (Order 4)': {'random_cost': 14, 'security': 70, 'masking_order': 4} }
required_security = 150 min_masking_order = 2
print("=" * 70) print("SIDE-CHANNEL COUNTERMEASURE OPTIMIZATION") print("Minimizing Random Number Consumption with Masking Order Constraints") print("=" * 70) print()
op_names = list(operations.keys()) n_ops = len(op_names) random_costs = np.array([operations[op]['random_cost'] for op in op_names]) security_values = np.array([operations[op]['security'] for op in op_names]) masking_orders = np.array([operations[op]['masking_order'] for op in op_names])
print("Operation Parameters:") print("-" * 70) df_ops = pd.DataFrame({ 'Operation': op_names, 'Random Cost (per op)': random_costs, 'Security Value': security_values, 'Masking Order': masking_orders }) print(df_ops.to_string(index=False)) print() print(f"Required Total Security: {required_security}") print(f"Minimum Masking Order per Operation: {min_masking_order}") print()
c = random_costs
A_ub = -security_values.reshape(1, -1) b_ub = np.array([-required_security])
A_order = np.zeros((n_ops, n_ops)) b_order = np.zeros(n_ops) for i in range(n_ops): if masking_orders[i] > 0: A_order[i, i] = -masking_orders[i] b_order[i] = -min_masking_order
A_ub_combined = np.vstack([A_ub, A_order]) b_ub_combined = np.hstack([b_ub, b_order])
bounds = [(0, None) for _ in range(n_ops)]
print("=" * 70) print("SOLVING LINEAR PROGRAMMING RELAXATION") print("=" * 70) print()
result_lp = linprog(c, A_ub=A_ub_combined, b_ub=b_ub_combined, bounds=bounds, method='highs')
if result_lp.success: print("LP Relaxation Solution (Fractional):") print("-" * 70) for i, op in enumerate(op_names): print(f"{op}: {result_lp.x[i]:.4f} operations") print() print(f"Minimum Random Numbers (Fractional): {result_lp.fun:.4f}") print(f"Total Security Achieved: {np.dot(security_values, result_lp.x):.4f}") print() else: print("LP relaxation failed to find a solution") print()
print("=" * 70) print("SOLVING INTEGER LINEAR PROGRAMMING") print("=" * 70) print()
from scipy.optimize import milp
constraints_milp = LinearConstraint(A_ub_combined, -np.inf, b_ub_combined) integrality = np.ones(n_ops) bounds_milp = Bounds(lb=np.zeros(n_ops), ub=np.full(n_ops, 100))
result_milp = milp(c=c, constraints=constraints_milp, integrality=integrality, bounds=bounds_milp)
optimal_solution = None optimal_cost = None
if result_milp.success: print("Integer Programming Solution:") print("-" * 70) optimal_solution = np.round(result_milp.x).astype(int) optimal_cost = np.dot(random_costs, optimal_solution) for i, op in enumerate(op_names): print(f"{op}: {optimal_solution[i]} operations") print() print(f"Minimum Random Numbers Required: {optimal_cost}") print(f"Total Security Achieved: {np.dot(security_values, optimal_solution)}") print() print("Constraint Verification:") print("-" * 70) total_sec = np.dot(security_values, optimal_solution) print(f"Security constraint: {total_sec} >= {required_security} : {'✓' if total_sec >= required_security else '✗'}") for i in range(n_ops): order_achieved = masking_orders[i] * optimal_solution[i] print(f"Masking order {op_names[i]}: {order_achieved} >= {min_masking_order} : {'✓' if order_achieved >= min_masking_order else '✗'}") print() else: print("Integer programming failed. Using brute force search...") min_cost = float('inf') best_solution = None max_each = 20 for combo in product(range(max_each), repeat=n_ops): x = np.array(combo) if np.dot(security_values, x) < required_security: continue valid = True for i in range(n_ops): if masking_orders[i] * x[i] < min_masking_order: valid = False break if not valid: continue cost = np.dot(random_costs, x) if cost < min_cost: min_cost = cost best_solution = x if best_solution is not None: optimal_solution = best_solution optimal_cost = min_cost print("Brute Force Solution:") print("-" * 70) for i, op in enumerate(op_names): print(f"{op}: {optimal_solution[i]} operations") print() print(f"Minimum Random Numbers Required: {optimal_cost}") print(f"Total Security Achieved: {np.dot(security_values, optimal_solution)}") print()
print("=" * 70) print("EFFICIENCY ANALYSIS") print("=" * 70) print()
if optimal_solution is not None: naive_ops = np.ceil(required_security / security_values[-1]).astype(int) naive_solution = np.zeros(n_ops, dtype=int) naive_solution[-1] = naive_ops naive_cost = random_costs[-1] * naive_ops print("Naive Approach (using only highest-order masking):") print(f"Operations: {naive_ops} × {op_names[-1]}") print(f"Random Numbers: {naive_cost}") print() savings = naive_cost - optimal_cost savings_pct = (savings / naive_cost) * 100 print(f"Optimization Savings: {savings} random numbers ({savings_pct:.1f}% reduction)") print()
print("=" * 70) print("GENERATING VISUALIZATIONS") print("=" * 70) print()
fig = plt.figure(figsize=(18, 12))
ax1 = fig.add_subplot(2, 3, 1) if optimal_solution is not None: colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A'] bars = ax1.bar(range(n_ops), optimal_solution, color=colors, edgecolor='black', linewidth=1.5) ax1.set_xlabel('Operation Type', fontsize=11, fontweight='bold') ax1.set_ylabel('Number of Operations', fontsize=11, fontweight='bold') ax1.set_title('Optimal Operation Distribution', fontsize=12, fontweight='bold') ax1.set_xticks(range(n_ops)) ax1.set_xticklabels([f'Type {chr(65+i)}' for i in range(n_ops)], rotation=0) ax1.grid(axis='y', alpha=0.3) for i, (bar, val) in enumerate(zip(bars, optimal_solution)): height = bar.get_height() ax1.text(bar.get_x() + bar.get_width()/2., height, f'{int(val)}', ha='center', va='bottom', fontweight='bold')
ax2 = fig.add_subplot(2, 3, 2) if optimal_solution is not None: random_consumption = random_costs * optimal_solution explode = [0.05 if x > 0 else 0 for x in random_consumption] colors_pie = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A'] wedges, texts, autotexts = ax2.pie(random_consumption, explode=explode, labels=[f'Type {chr(65+i)}' for i in range(n_ops)], autopct='%1.1f%%', colors=colors_pie, startangle=90, textprops={'fontweight': 'bold'}) ax2.set_title('Random Number Consumption by Type', fontsize=12, fontweight='bold')
ax3 = fig.add_subplot(2, 3, 3) security_range = np.linspace(100, 300, 50) min_costs = []
for target_sec in security_range: b_ub_temp = np.hstack([np.array([-target_sec]), b_order]) result_temp = linprog(c, A_ub=A_ub_combined, b_ub=b_ub_temp, bounds=bounds, method='highs') if result_temp.success: min_costs.append(result_temp.fun) else: min_costs.append(np.nan)
ax3.plot(security_range, min_costs, linewidth=2.5, color='#2C3E50') ax3.axvline(x=required_security, color='red', linestyle='--', linewidth=2, label='Required Security') if optimal_solution is not None: ax3.plot(np.dot(security_values, optimal_solution), optimal_cost, 'ro', markersize=12, label='Optimal Solution', zorder=5) ax3.set_xlabel('Total Security Level', fontsize=11, fontweight='bold') ax3.set_ylabel('Random Numbers Required', fontsize=11, fontweight='bold') ax3.set_title('Security vs Random Cost Tradeoff', fontsize=12, fontweight='bold') ax3.legend(fontsize=9) ax3.grid(True, alpha=0.3)
ax4 = fig.add_subplot(2, 3, 4, projection='3d')
n_points = 20 x_range = np.linspace(0, 10, n_points) y_range = np.linspace(0, 10, n_points) X, Y = np.meshgrid(x_range, y_range) Z = np.zeros_like(X)
for i in range(n_points): for j in range(n_points): x1, x2 = X[i, j], Y[i, j] remaining_sec = max(0, required_security - security_values[0]*x1 - security_values[1]*x2) if remaining_sec == 0: x3_min = max(0, np.ceil(min_masking_order / masking_orders[2])) x4_min = max(0, np.ceil(min_masking_order / masking_orders[3])) Z[i, j] = (random_costs[0]*x1 + random_costs[1]*x2 + random_costs[2]*x3_min + random_costs[3]*x4_min) else: x3_min = max(0, np.ceil(min_masking_order / masking_orders[2])) x4_needed = max(0, np.ceil((remaining_sec - security_values[2]*x3_min) / security_values[3])) x4_min = max(x4_needed, np.ceil(min_masking_order / masking_orders[3])) Z[i, j] = (random_costs[0]*x1 + random_costs[1]*x2 + random_costs[2]*x3_min + random_costs[3]*x4_min)
surf = ax4.plot_surface(X, Y, Z, cmap='viridis', alpha=0.8, edgecolor='none')
if optimal_solution is not None: ax4.scatter([optimal_solution[0]], [optimal_solution[1]], [optimal_cost], color='red', s=200, marker='o', edgecolor='black', linewidth=2, label='Optimal', zorder=10)
ax4.set_xlabel('Type A Operations', fontsize=10, fontweight='bold') ax4.set_ylabel('Type B Operations', fontsize=10, fontweight='bold') ax4.set_zlabel('Total Random Cost', fontsize=10, fontweight='bold') ax4.set_title('3D Cost Surface', fontsize=12, fontweight='bold') fig.colorbar(surf, ax=ax4, shrink=0.5, aspect=5)
ax5 = fig.add_subplot(2, 3, 5) if optimal_solution is not None: masking_contribution = masking_orders * optimal_solution x_pos = np.arange(n_ops) colors_bar = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A'] bars = ax5.bar(x_pos, masking_contribution, color=colors_bar, edgecolor='black', linewidth=1.5) ax5.axhline(y=min_masking_order, color='red', linestyle='--', linewidth=2, label=f'Min Required ({min_masking_order})') ax5.set_xlabel('Operation Type', fontsize=11, fontweight='bold') ax5.set_ylabel('Total Masking Order Contribution', fontsize=11, fontweight='bold') ax5.set_title('Masking Order Verification', fontsize=12, fontweight='bold') ax5.set_xticks(x_pos) ax5.set_xticklabels([f'Type {chr(65+i)}' for i in range(n_ops)]) ax5.legend(fontsize=9) ax5.grid(axis='y', alpha=0.3) for bar, val in zip(bars, masking_contribution): height = bar.get_height() ax5.text(bar.get_x() + bar.get_width()/2., height, f'{int(val)}', ha='center', va='bottom', fontweight='bold')
ax6 = fig.add_subplot(2, 3, 6) if optimal_solution is not None: strategies = ['Naive\n(High Order Only)', 'Optimized\n(Mixed Strategy)'] costs_comparison = [naive_cost, optimal_cost] colors_comp = ['#E74C3C', '#27AE60'] bars = ax6.bar(strategies, costs_comparison, color=colors_comp, edgecolor='black', linewidth=2, width=0.6) ax6.set_ylabel('Random Numbers Required', fontsize=11, fontweight='bold') ax6.set_title('Strategy Comparison', fontsize=12, fontweight='bold') ax6.grid(axis='y', alpha=0.3) for bar, val in zip(bars, costs_comparison): height = bar.get_height() ax6.text(bar.get_x() + bar.get_width()/2., height, f'{int(val)}', ha='center', va='bottom', fontweight='bold', fontsize=11) mid_x = 0.5 ax6.annotate('', xy=(mid_x, optimal_cost), xytext=(mid_x, naive_cost), arrowprops=dict(arrowstyle='<->', color='red', lw=2)) ax6.text(mid_x + 0.15, (naive_cost + optimal_cost) / 2, f'-{savings}\n({savings_pct:.1f}%)', fontsize=10, fontweight='bold', color='red')
plt.tight_layout() plt.savefig('masking_optimization_analysis.png', dpi=300, bbox_inches='tight') print("Visualization saved as 'masking_optimization_analysis.png'") print()
fig2 = plt.figure(figsize=(14, 6))
ax_3d1 = fig2.add_subplot(1, 2, 1, projection='3d')
type_b_range = np.linspace(0, 8, 25) type_c_range = np.linspace(0, 8, 25) B, C = np.meshgrid(type_b_range, type_c_range) Cost_surface = np.zeros_like(B)
for i in range(B.shape[0]): for j in range(B.shape[1]): b_ops, c_ops = B[i, j], C[i, j] if masking_orders[1] * b_ops < min_masking_order: b_ops = np.ceil(min_masking_order / masking_orders[1]) if masking_orders[2] * c_ops < min_masking_order: c_ops = np.ceil(min_masking_order / masking_orders[2]) current_sec = security_values[1] * b_ops + security_values[2] * c_ops remaining = max(0, required_security - current_sec) d_ops = max(np.ceil(remaining / security_values[3]), np.ceil(min_masking_order / masking_orders[3])) Cost_surface[i, j] = (random_costs[1] * b_ops + random_costs[2] * c_ops + random_costs[3] * d_ops)
surf1 = ax_3d1.plot_surface(B, C, Cost_surface, cmap='plasma', alpha=0.7, edgecolor='none')
if optimal_solution is not None and optimal_solution[1] > 0 and optimal_solution[2] > 0: ax_3d1.scatter([optimal_solution[1]], [optimal_solution[2]], [optimal_cost], color='lime', s=300, marker='*', edgecolor='black', linewidth=2, label='Optimal Point', zorder=100)
ax_3d1.set_xlabel('Type B Ops (Order 2)', fontsize=10, fontweight='bold') ax_3d1.set_ylabel('Type C Ops (Order 3)', fontsize=10, fontweight='bold') ax_3d1.set_zlabel('Total Random Cost', fontsize=10, fontweight='bold') ax_3d1.set_title('3D Cost Landscape: Type B vs Type C', fontsize=12, fontweight='bold') ax_3d1.view_init(elev=25, azim=45) fig2.colorbar(surf1, ax=ax_3d1, shrink=0.5, aspect=10)
ax_3d2 = fig2.add_subplot(1, 2, 2, projection='3d')
solutions_3d = [] for total_ops in range(3, 25): for combo in product(range(total_ops+1), repeat=n_ops): if sum(combo) != total_ops: continue x = np.array(combo) valid = True for i in range(n_ops): if masking_orders[i] * x[i] < min_masking_order and x[i] > 0: valid = False break if not valid: continue sec = np.dot(security_values, x) if sec < required_security: continue cost = np.dot(random_costs, x) max_order = max([masking_orders[i] * x[i] for i in range(n_ops) if x[i] > 0], default=0) solutions_3d.append((sec, cost, max_order))
if solutions_3d: solutions_3d = np.array(solutions_3d) scatter = ax_3d2.scatter(solutions_3d[:, 0], solutions_3d[:, 1], solutions_3d[:, 2], c=solutions_3d[:, 1], cmap='coolwarm', s=50, alpha=0.6, edgecolor='black', linewidth=0.5) if optimal_solution is not None: opt_sec = np.dot(security_values, optimal_solution) opt_max_order = max([masking_orders[i] * optimal_solution[i] for i in range(n_ops) if optimal_solution[i] > 0]) ax_3d2.scatter([opt_sec], [optimal_cost], [opt_max_order], color='lime', s=400, marker='*', edgecolor='black', linewidth=2, label='Optimal', zorder=100) ax_3d2.set_xlabel('Total Security', fontsize=10, fontweight='bold') ax_3d2.set_ylabel('Random Cost', fontsize=10, fontweight='bold') ax_3d2.set_zlabel('Max Masking Order', fontsize=10, fontweight='bold') ax_3d2.set_title('3D Pareto Frontier Analysis', fontsize=12, fontweight='bold') ax_3d2.view_init(elev=20, azim=135) ax_3d2.legend(fontsize=9) fig2.colorbar(scatter, ax=ax_3d2, shrink=0.5, aspect=10, label='Cost')
plt.tight_layout() plt.savefig('masking_3d_analysis.png', dpi=300, bbox_inches='tight') print("3D analysis saved as 'masking_3d_analysis.png'") print()
plt.show()
print("=" * 70) print("ANALYSIS COMPLETE") print("=" * 70)
|