Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

r""" 

S-Boxes and Their Algebraic Representations 

""" 

from __future__ import print_function, division 

from six.moves import range 

from six import integer_types 

 

from sage.combinat.integer_vector import IntegerVectors 

from sage.crypto.boolean_function import BooleanFunction 

from sage.matrix.constructor import Matrix 

from sage.misc.cachefunc import cached_method 

from sage.misc.functional import is_even 

from sage.misc.misc_c import prod as mul 

from sage.modules.free_module_element import vector 

from sage.rings.finite_rings.element_base import is_FiniteFieldElement 

from sage.rings.finite_rings.finite_field_constructor import FiniteField as GF 

from sage.rings.ideal import FieldIdeal, Ideal 

from sage.rings.integer_ring import ZZ 

from sage.rings.integer import Integer 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

from sage.structure.sage_object import SageObject 

 

class SBox(SageObject): 

r""" 

A substitution box or S-box is one of the basic components of 

symmetric key cryptography. In general, an S-box takes ``m`` input 

bits and transforms them into ``n`` output bits. This is called an 

``mxn`` S-box and is often implemented as a lookup table. These 

S-boxes are carefully chosen to resist linear and differential 

cryptanalysis [He2002]_. 

 

This module implements an S-box class which allows an algebraic 

treatment and determine various cryptographic properties. 

 

EXAMPLES: 

 

We consider the S-box of the block cipher PRESENT [BKLPPRSV2007]_:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2); S 

(12, 5, 6, 11, 9, 0, 10, 13, 3, 14, 15, 8, 4, 7, 1, 2) 

sage: S(1) 

5 

 

Note that by default bits are interpreted in big endian 

order. This is not consistent with the rest of Sage, which has a 

strong bias towards little endian, but is consistent with most 

cryptographic literature:: 

 

sage: S([0,0,0,1]) 

[0, 1, 0, 1] 

 

sage: S = SBox(12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2, big_endian=False) 

sage: S(1) 

5 

sage: S([0,0,0,1]) 

[1, 1, 0, 0] 

 

 

Now we construct an ``SBox`` object for the 4-bit small scale AES 

S-Box (cf. :mod:`sage.crypto.mq.sr`):: 

 

sage: sr = mq.SR(1,1,1,4, allow_zero_inversions=True) 

sage: S = SBox([sr.sub_byte(e) for e in list(sr.k)]) 

sage: S 

(6, 5, 2, 9, 4, 7, 3, 12, 14, 15, 10, 0, 8, 1, 13, 11) 

 

AUTHORS: 

 

- Rusydi H. Makarim (2016-03-31) : added more functions to determine related cryptographic properties 

- Yann Laigle-Chapuy (2009-07-01): improve linear and difference matrix computation 

- Martin R. Albrecht (2008-03-12): initial implementation 

 

REFERENCES: 

 

- [He2002]_ 

 

- [BKLPPRSV2007]_ 

 

- [CDL2015]_ 

""" 

 

def __init__(self, *args, **kwargs): 

""" 

Construct a substitution box (S-box) for a given lookup table 

`S`. 

 

INPUT: 

 

- ``S`` - a finite iterable defining the S-box with integer or 

finite field elements 

 

- ``big_endian`` - controls whether bits shall be ordered in 

big endian order (default: ``True``) 

 

EXAMPLES: 

 

We construct a 3-bit S-box where e.g. the bits (0,0,1) are 

mapped to (1,1,1).:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3); S 

(7, 6, 0, 4, 2, 5, 1, 3) 

 

sage: S(0) 

7 

 

TESTS:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox() 

Traceback (most recent call last): 

... 

TypeError: No lookup table provided. 

sage: S = SBox(1, 2, 3) 

Traceback (most recent call last): 

... 

TypeError: Lookup table length is not a power of 2. 

sage: S = SBox(5, 6, 0, 3, 4, 2, 1, 2) 

sage: S.n 

3 

""" 

if "S" in kwargs: 

S = kwargs["S"] 

elif len(args) == 1: 

S = args[0] 

elif len(args) > 1: 

S = args 

else: 

raise TypeError("No lookup table provided.") 

 

_S = [] 

for e in S: 

if is_FiniteFieldElement(e): 

e = e.polynomial().change_ring(ZZ).subs( e.parent().characteristic() ) 

_S.append(e) 

S = _S 

 

if not ZZ(len(S)).is_power_of(2): 

raise TypeError("Lookup table length is not a power of 2.") 

self._S = S 

 

self.m = ZZ(len(S)).exact_log(2) 

self.n = ZZ(max(S)).nbits() 

self._F = GF(2) 

self._big_endian = kwargs.get("big_endian",True) 

 

self.differential_uniformity = self.maximal_difference_probability_absolute 

 

def _repr_(self): 

""" 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: SBox(7,6,0,4,2,5,1,3) #indirect doctest 

(7, 6, 0, 4, 2, 5, 1, 3) 

""" 

return "(" + ", ".join(map(str,list(self))) + ")" 

 

def __len__(self): 

""" 

Return the length of input bit strings. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: len(SBox(7,6,0,4,2,5,1,3)) 

3 

""" 

return self.m 

 

def __eq__(self, other): 

""" 

S-boxes are considered to be equal if all construction 

parameters match. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: loads(dumps(S)) == S 

True 

""" 

return (self._S, self._big_endian) == (other._S, self._big_endian) 

 

def __ne__(self, other): 

""" 

S-boxes are considered to be equal if all construction 

parameters match. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S != S 

False 

""" 

return not self.__eq__(other) 

 

def to_bits(self, x, n=None): 

""" 

Return bitstring of length ``n`` for integer ``x``. The 

returned bitstring is guaranteed to have length ``n``. 

 

INPUT: 

 

- ``x`` - an integer 

 

- ``n`` - bit length (optional) 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.to_bits(6) 

[1, 1, 0] 

 

sage: S.to_bits( S(6) ) 

[0, 0, 1] 

 

sage: S( S.to_bits( 6 ) ) 

[0, 0, 1] 

""" 

if n is None and self.m == self.n: 

n = self.n 

 

if self._big_endian: 

swp = lambda x: list(reversed(x)) 

else: 

swp = lambda x: x 

return swp(self._rpad([self._F(_) for _ in ZZ(x).digits(2)], n)) 

 

def from_bits(self, x, n=None): 

""" 

Return integer for bitstring ``x`` of length ``n``. 

 

INPUT: 

 

- ``x`` - a bitstring 

 

- ``n`` - bit length (optional) 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.from_bits( [1,1,0]) 

6 

 

sage: S( S.from_bits( [1,1,0] ) ) 

1 

sage: S.from_bits( S( [1,1,0] ) ) 

1 

""" 

if n is None and self.m == self.n: 

n = self.m 

 

if self._big_endian: 

swp = lambda x: list(reversed(x)) 

else: 

swp = lambda x: x 

 

return ZZ( [ZZ(_) for _ in self._rpad(swp(x), n)], 2) 

 

def _rpad(self,x, n=None): 

""" 

Right pads ``x`` such that ``len(x) == n``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S._rpad([1,1]) 

[1, 1, 0] 

""" 

if n is None and self.m == self.n: 

n = self.n 

return x + [self._F(0)]*(n-len(x)) 

 

def __call__(self, X): 

""" 

Apply substitution to ``X``. 

 

If ``X`` is a list, it is interpreted as a sequence of bits 

depending on the bit order of this S-box. 

 

INPUT: 

 

- ``X`` - either an integer, a tuple of `\GF{2}` elements of 

length ``len(self)`` or a finite field element in 

`\GF{2^n}`. As a last resort this function tries to convert 

``X`` to an integer. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([7,6,0,4,2,5,1,3]) 

sage: S(7) 

3 

 

sage: S((0,2,3)) 

[0, 1, 1] 

 

sage: S[0] 

7 

 

sage: S[(0,0,1)] 

[1, 1, 0] 

 

sage: k.<a> = GF(2^3) 

sage: S(a^2) 

a 

 

sage: S(QQ(3)) 

4 

 

sage: S([1]*10^6) 

Traceback (most recent call last): 

... 

TypeError: Cannot apply SBox to provided element. 

 

sage: S(1/2) 

Traceback (most recent call last): 

... 

TypeError: Cannot apply SBox to 1/2. 

 

sage: S = SBox(3, 0, 1, 3, 1, 0, 2, 2) 

sage: S(0) 

3 

sage: S([0,0,0]) 

[1, 1] 

""" 

if isinstance(X, integer_types + (Integer,)): 

return self._S[ZZ(X)] 

 

try: 

from sage.modules.free_module_element import vector 

K = X.parent() 

if K.order() == 2**self.n: 

X = vector(X) 

else: 

raise TypeError 

if not self._big_endian: 

X = list(reversed(X)) 

else: 

X = list(X) 

X = ZZ([ZZ(_) for _ in X], 2) 

out = self.to_bits(self._S[X], self.n) 

if self._big_endian: 

out = list(reversed(out)) 

return K(vector(GF(2),out)) 

except (AttributeError, TypeError): 

pass 

 

try: 

if len(X) == self.m: 

if self._big_endian: 

X = list(reversed(X)) 

X = ZZ([ZZ(_) for _ in X], 2) 

out = self._S[X] 

return self.to_bits(out,self.n) 

except TypeError: 

pass 

 

try: 

return self._S[ZZ(X)] 

except TypeError: 

pass 

 

if len(str(X)) > 50: 

raise TypeError("Cannot apply SBox to provided element.") 

else: 

raise TypeError("Cannot apply SBox to %s."%(X,)) 

 

def __getitem__(self, X): 

""" 

See :meth:`SBox.__call__`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([7,6,0,4,2,5,1,3]) 

sage: S[7] 

3 

""" 

return self(X) 

 

def is_permutation(self): 

r""" 

Return ``True`` if this S-Box is a permutation. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.is_permutation() 

True 

 

sage: S = SBox(3,2,0,0,2,1,1,3) 

sage: S.is_permutation() 

False 

""" 

if self.m != self.n: 

return False 

return len(set([self(i) for i in range(2**self.m)])) == 2**self.m 

 

def __iter__(self): 

""" 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: [e for e in S] 

[7, 6, 0, 4, 2, 5, 1, 3] 

""" 

for i in range(2**self.m): 

yield self(i) 

 

def difference_distribution_matrix(self): 

""" 

Return difference distribution matrix ``A`` for this S-box. 

 

The rows of ``A`` encode the differences ``Delta I`` of the 

input and the columns encode the difference ``Delta O`` for 

the output. The bits are ordered according to the endianess of 

this S-box. The value at ``A[Delta I,Delta O]`` encodes how 

often ``Delta O`` is the actual output difference given 

``Delta I`` as input difference. 

 

See [He2002]_ for an introduction to differential 

cryptanalysis. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.difference_distribution_matrix() 

[8 0 0 0 0 0 0 0] 

[0 2 2 0 2 0 0 2] 

[0 0 2 2 0 0 2 2] 

[0 2 0 2 2 0 2 0] 

[0 2 0 2 0 2 0 2] 

[0 0 2 2 2 2 0 0] 

[0 2 2 0 0 2 2 0] 

[0 0 0 0 2 2 2 2] 

""" 

m = self.m 

n = self.n 

 

nrows = 1<<m 

ncols = 1<<n 

 

A = Matrix(ZZ, nrows, ncols) 

 

for i in range(nrows): 

si = self(i) 

for di in range(nrows): 

A[ di , si^self(i^di)] += 1 

A.set_immutable() 

 

return A 

 

def maximal_difference_probability_absolute(self): 

""" 

Return the difference probability of the difference with the 

highest probability in absolute terms, i.e. how often it 

occurs in total. 

 

Equivalently, this is equal to the differential uniformity 

of this S-Box. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.maximal_difference_probability_absolute() 

2 

 

.. note:: 

 

This code is mainly called internally. 

""" 

A = self.difference_distribution_matrix().__copy__() 

A[0,0] = 0 

return max(map(abs, A.list())) 

 

def maximal_difference_probability(self): 

r""" 

Return the difference probability of the difference with the 

highest probability in the range between 0.0 and 1.0 

indicating 0\% or 100\% respectively. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.maximal_difference_probability() 

0.25 

""" 

return self.maximal_difference_probability_absolute()/(2.0**self.n) 

 

@cached_method 

def linear_approximation_matrix(self, scale="absolute_bias"): 

r""" 

Return linear approximation matrix (LAM) `A` for this S-box. 

 

The entry `A[\alpha,\beta]` corresponds to the probability 

`Pr[\alpha\cdot x = \beta\cdot S(x)]`, where `S` is this S-box 

mapping `n`-bit inputs to `m`-bit outputs. 

There are three typical notations for this probability used in 

the literature: 

 

- `Pr[\alpha\cdot x = \beta\cdot S(x)] = 1/2 + e(\alpha, \beta)`, 

where `e(\alpha, \beta)` is called the bias, 

- `2\cdot Pr[\alpha\cdot x = \beta\cdot S(x)] = 1 + c(\alpha, \beta)`, 

where `c(\alpha, \beta) = 2\cdot e(\alpha, \beta)` is the correlation, and 

- `2^{(m+1)}\cdot Pr[\alpha\cdot x = \beta\cdot S(x)] = 2^m + \hat{S}(\alpha, 

\beta)`, where `\hat{S}(\alpha, \beta)` is the Fourier coefficient of S. 

 

See [He2002]_ for an introduction to linear cryptanalysis. 

 

INPUT: 

 

- ``scale`` - string to choose the scaling for the LAM, one of 

- "bias": elements are `e(\alpha, \beta)` 

- "correlation": elements are `c(\alpha, \beta)` 

- "absolute_bias": elements are `2^m\cdot e(\alpha, \beta)` (default) 

- "fourier_coefficient": elements are `\hat{S}(\alpha, \beta)` 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: lat_abs_bias = S.linear_approximation_matrix() 

sage: lat_abs_bias 

[ 4 0 0 0 0 0 0 0] 

[ 0 0 0 0 2 2 2 -2] 

[ 0 0 -2 -2 -2 2 0 0] 

[ 0 0 -2 2 0 0 -2 -2] 

[ 0 2 0 2 -2 0 2 0] 

[ 0 -2 0 2 0 2 0 2] 

[ 0 -2 -2 0 0 -2 2 0] 

[ 0 -2 2 0 -2 0 0 -2] 

 

sage: lat_abs_bias/(1<<S.m) == S.linear_approximation_matrix(scale="bias") 

True 

 

sage: lat_abs_bias/(1<<(S.m-1)) == S.linear_approximation_matrix(scale="correlation") 

True 

 

sage: lat_abs_bias*2 == S.linear_approximation_matrix(scale="fourier_coefficient") 

True 

 

According to this matrix the first bit of the input is equal 

to the third bit of the output 6 out of 8 times:: 

 

sage: for i in srange(8): print(S.to_bits(i)[0] == S.to_bits(S(i))[2]) 

False 

True 

True 

True 

False 

True 

True 

True 

""" 

m = self.m 

n = self.n 

 

nrows = 1<<m 

ncols = 1<<n 

 

scale_factor = 1 

if (scale is None) or (scale == "absolute_bias"): 

scale_factor = 2 

elif scale == "bias": 

scale_factor = 1<<(m+1) 

elif scale == "correlation": 

scale_factor = 1<<m 

elif scale == "fourier_coefficient": 

pass 

else: 

raise ValueError("no such scaling for the LAM: %s" % scale) 

 

L = [self.component_function(i).walsh_hadamard_transform() for i in range(ncols)] 

 

A = Matrix(ZZ, ncols, nrows, L) 

A = A.transpose()/scale_factor 

A.set_immutable() 

 

return A 

 

def maximal_linear_bias_absolute(self): 

""" 

Return maximal linear bias, i.e. how often the linear 

approximation with the highest bias is true or false minus 

`2^{n-1}`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.maximal_linear_bias_absolute() 

2 

""" 

A = self.linear_approximation_matrix().__copy__() 

A[0,0] = 0 

return max(map(abs, A.list())) 

 

def maximal_linear_bias_relative(self): 

""" 

Return maximal bias of all linear approximations of this 

S-box. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.maximal_linear_bias_relative() 

0.25 

""" 

return self.maximal_linear_bias_absolute()/(2.0**self.m) 

 

def ring(self): 

""" 

Create, return and cache a polynomial ring for S-box 

polynomials. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.ring() 

Multivariate Polynomial Ring in x0, x1, x2, y0, y1, y2 over Finite Field of size 2 

""" 

try: 

return self._ring 

except AttributeError: 

pass 

 

m = self.m 

n = self.n 

 

X = range(m) 

Y = range(n) 

self._ring = PolynomialRing(self._F, m+n, ["x%d"%i for i in X] + ["y%d"%i for i in Y]) 

return self._ring 

 

def solutions(self, X=None, Y=None): 

""" 

Return a dictionary of solutions to this S-box. 

 

INPUT: 

 

- ``X`` - input variables (default: ``None``) 

 

- ``Y`` - output variables (default: ``None``) 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([7,6,0,4,2,5,1,3]) 

sage: F = S.polynomials() 

sage: s = S.solutions() 

sage: any(f.subs(_s) for f in F for _s in s) 

False 

""" 

if X is None and Y is None: 

P = self.ring() 

gens = P.gens() 

else: 

P = X[0].parent() 

gens = X + Y 

 

m = self.m 

n = self.n 

 

solutions = [] 

for i in range(1<<m): 

solution = self.to_bits(i,m) + self( self.to_bits(i,m) ) 

solutions.append( dict(zip(gens, solution)) ) 

 

return solutions 

 

def polynomials(self, X=None, Y=None, degree=2, groebner=False): 

""" 

Return a list of polynomials satisfying this S-box. 

 

First, a simple linear fitting is performed for the given 

``degree`` (cf. for example [BC2003]_). If ``groebner=True`` a 

Groebner basis is also computed for the result of that 

process. 

 

INPUT: 

 

- ``X`` - input variables 

 

- ``Y`` - output variables 

 

- ``degree`` - integer > 0 (default: ``2``) 

 

- ``groebner`` - calculate a reduced Groebner basis of the 

spanning polynomials to obtain more polynomials (default: 

``False``) 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: P = S.ring() 

 

By default, this method returns an indirect representation:: 

 

sage: S.polynomials() 

[x0*x2 + x1 + y1 + 1, 

x0*x1 + x1 + x2 + y0 + y1 + y2 + 1, 

x0*y1 + x0 + x2 + y0 + y2, 

x0*y0 + x0*y2 + x1 + x2 + y0 + y1 + y2 + 1, 

x1*x2 + x0 + x1 + x2 + y2 + 1, 

x0*y0 + x1*y0 + x0 + x2 + y1 + y2, 

x0*y0 + x1*y1 + x1 + y1 + 1, 

x1*y2 + x1 + x2 + y0 + y1 + y2 + 1, 

x0*y0 + x2*y0 + x1 + x2 + y1 + 1, 

x2*y1 + x0 + y1 + y2, 

x2*y2 + x1 + y1 + 1, 

y0*y1 + x0 + x2 + y0 + y1 + y2, 

y0*y2 + x1 + x2 + y0 + y1 + 1, 

y1*y2 + x2 + y0] 

 

We can get a direct representation by computing a 

lexicographical Groebner basis with respect to the right 

variable ordering, i.e. a variable ordering where the output 

bits are greater than the input bits:: 

 

sage: P.<y0,y1,y2,x0,x1,x2> = PolynomialRing(GF(2),6,order='lex') 

sage: S.polynomials([x0,x1,x2],[y0,y1,y2], groebner=True) 

[y0 + x0*x1 + x0*x2 + x0 + x1*x2 + x1 + 1, 

y1 + x0*x2 + x1 + 1, 

y2 + x0 + x1*x2 + x1 + x2 + 1] 

""" 

def nterms(nvars, deg): 

""" 

Return the number of monomials possible up to a given 

degree. 

 

INPUT: 

 

- ``nvars`` - number of variables 

 

- ``deg`` - degree 

 

TESTS:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: F = S.polynomials(degree=3) # indirect doctest 

""" 

total = 1 

divisor = 1 

var_choices = 1 

 

for d in range(1, deg+1): 

var_choices *= (nvars - d + 1) 

divisor *= d 

total += var_choices/divisor 

return total 

 

m = self.m 

n = self.n 

F = self._F 

 

if X is None and Y is None: 

P = self.ring() 

X = P.gens()[:m] 

Y = P.gens()[m:] 

else: 

P = X[0].parent() 

 

gens = X+Y 

 

bits = [] 

for i in range(1<<m): 

bits.append( self.to_bits(i,m) + self(self.to_bits(i,m)) ) 

 

ncols = (1<<m)+1 

 

A = Matrix(P, nterms(m+n, degree), ncols) 

 

exponents = [] 

for d in range(degree+1): 

exponents += IntegerVectors(d, max_length=m+n, min_length=m+n, min_part=0, max_part=1).list() 

 

row = 0 

for exponent in exponents: 

A[row,ncols-1] = mul([gens[i]**exponent[i] for i in range(len(exponent))]) 

for col in range(1<<m): 

A[row,col] = mul([bits[col][i] for i in range(len(exponent)) if exponent[i]]) 

row +=1 

 

for c in range(ncols): 

A[0,c] = 1 

 

RR = A.echelon_form(algorithm='row_reduction') 

 

# extract spanning stet 

gens = (RR.column(ncols-1)[1<<m:]).list() 

 

if not groebner: 

return gens 

 

FI = set(FieldIdeal(P).gens()) 

I = Ideal(gens + list(FI)) 

gb = I.groebner_basis() 

 

gens = [] 

for f in gb: 

if f not in FI: # filter out field equations 

gens.append(f) 

return gens 

 

def interpolation_polynomial(self, k=None): 

r""" 

Return a univariate polynomial over an extension field 

representing this S-box. 

 

If ``m`` is the input length of this S-box then the extension 

field is of degree ``m``. 

 

If the output length does not match the input length then a 

``TypeError`` is raised. 

 

INPUT: 

 

- ``k`` - an instance of `\GF{2^m}` (default: ``None``) 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: f = S.interpolation_polynomial() 

sage: f 

x^6 + a*x^5 + (a + 1)*x^4 + (a^2 + a + 1)*x^3 

+ (a^2 + 1)*x^2 + (a + 1)*x + a^2 + a + 1 

 

sage: a = f.base_ring().gen() 

 

sage: f(0), S(0) 

(a^2 + a + 1, 7) 

 

sage: f(a^2 + 1), S(5) 

(a^2 + 1, 5) 

""" 

if self.m != self.n: 

raise TypeError("Lagrange interpolation only supported if self.m == self.n.") 

 

if k is None: 

k = GF(2**self.m,'a') 

l = [] 

for i in range(2**self.m): 

i = self.to_bits(i, self.m) 

o = self(i) 

if self._big_endian: 

i = reversed(i) 

o = reversed(o) 

l.append( (k(vector(i)), k(vector(o))) ) 

 

P = PolynomialRing(k,'x') 

return P.lagrange_polynomial(l) 

 

def cnf(self, xi=None, yi=None, format=None): 

""" 

Return a representation of this S-Box in conjunctive normal 

form. 

 

This function examines the truth tables for each output bit of 

the S-Box and thus has complexity `n * 2^m` for an ``m x n`` 

S-Box. 

 

INPUT: 

 

- ``xi`` - indices for the input variables (default: ``1...m``) 

 

- ``yi`` - indices for the output variables (default: ``m+1 ... m+n``) 

 

- ``format`` - output format, see below (default: ``None``) 

 

FORMATS: 

 

- ``None`` - return a list of tuples of integers where each 

tuple represents a clause, the absolute value of an integer 

represents a variable and the sign of an integer indicates 

inversion. 

 

- ``symbolic`` - a string that can be parsed by the 

``SymbolicLogic`` package. 

 

- ``dimacs`` - a string in DIMACS format which is the gold 

standard for SAT-solver input (cf. http://www.satlib.org/). 

 

- ``dimacs_headless`` - a string in DIMACS format, but without 

the header. This is useful for concatenation of outputs. 

 

EXAMPLES: 

 

We give a very small example to explain the output format:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(1,2,0,3); S 

(1, 2, 0, 3) 

sage: cnf = S.cnf(); cnf 

[(1, 2, -3), (1, 2, 4), 

(1, -2, 3), (1, -2, -4), 

(-1, 2, -3), (-1, 2, -4), 

(-1, -2, 3), (-1, -2, 4)] 

 

This output completely describes the S-Box. For instance, we 

can check that ``S([0,1]) -> [1,0]`` satisfies every clause if 

the first input bit corresponds to the index ``1`` and the 

last output bit corresponds to the index ``3`` in the 

output. 

 

We can convert this representation to the DIMACS format:: 

 

sage: print(S.cnf(format='dimacs')) 

p cnf 4 8 

1 2 -3 0 

1 2 4 0 

1 -2 3 0 

1 -2 -4 0 

-1 2 -3 0 

-1 2 -4 0 

-1 -2 3 0 

-1 -2 4 0 

 

For concatenation we can strip the header:: 

 

sage: print(S.cnf(format='dimacs_headless')) 

1 2 -3 0 

1 2 4 0 

1 -2 3 0 

1 -2 -4 0 

-1 2 -3 0 

-1 2 -4 0 

-1 -2 3 0 

-1 -2 4 0 

 

This might be helpful in combination with the ``xi`` and 

``yi`` parameter to assign indices manually:: 

 

sage: print(S.cnf(xi=[10,20],yi=[30,40], format='dimacs_headless')) 

10 20 -30 0 

10 20 40 0 

10 -20 30 0 

10 -20 -40 0 

-10 20 -30 0 

-10 20 -40 0 

-10 -20 30 0 

-10 -20 40 0 

 

We can also return a string which is parse-able by the 

``SymbolicLogic`` package:: 

 

sage: log = SymbolicLogic() 

sage: s = log.statement(S.cnf(format='symbolic')) 

sage: log.truthtable(s)[1:] 

[['False', 'False', 'False', 'False', 'False'], 

['False', 'False', 'False', 'True', 'False'], 

['False', 'False', 'True', 'False', 'False'], 

['False', 'False', 'True', 'True', 'True'], 

['False', 'True', 'False', 'False', 'True'], 

['False', 'True', 'False', 'True', 'True'], 

['False', 'True', 'True', 'False', 'True'], 

['False', 'True', 'True', 'True', 'True'], 

['True', 'False', 'False', 'False', 'True'], 

['True', 'False', 'False', 'True', 'True'], 

['True', 'False', 'True', 'False', 'True'], 

['True', 'False', 'True', 'True', 'True'], 

['True', 'True', 'False', 'False', 'True'], 

['True', 'True', 'False', 'True', 'True'], 

['True', 'True', 'True', 'False', 'True'], 

['True', 'True', 'True', 'True', 'True']] 

 

 

This function respects endianness of the S-Box:: 

 

sage: S = SBox(1,2,0,3, big_endian=False); S 

(1, 2, 0, 3) 

sage: cnf = S.cnf(); cnf 

[(1, 2, -4), (1, 2, 3), 

(-1, 2, 4), (-1, 2, -3), 

(1, -2, -4), (1, -2, -3), 

(-1, -2, 4), (-1, -2, 3)] 

 

S-Boxes with m!=n also work: 

 

sage: o = list(range(8)) + list(range(8)) 

sage: shuffle(o) 

sage: S = SBox(o) 

sage: S.is_permutation() 

False 

 

sage: len(S.cnf()) == 3*2^4 

True 

 

 

TESTS: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(1,2,0,3, big_endian=False) 

sage: S.cnf([1000,1001,1002], [2000,2001,2002]) 

Traceback (most recent call last): 

... 

TypeError: first arg required to have length 2, got 3 instead. 

""" 

m, n = self.m, self.n 

 

if xi is None: 

xi = [i+1 for i in range(m)] 

 

if yi is None: 

yi = [m+i+1 for i in range(n)] 

 

if len(xi) != m: 

raise TypeError("first arg required to have length %d, got %d instead."%(m,len(xi))) 

 

if len(yi) != n: 

raise TypeError("second arg required to have length %d, got %d instead."%(n,len(yi))) 

 

output_bits = range(n) 

if not self._big_endian: 

output_bits = list(reversed(output_bits)) 

 

C = [] # the set of clauses 

for e in range(2**m): 

x = self.to_bits(e, m) 

y = self(x) # evaluate at x 

for output_bit in output_bits: # consider each bit 

clause = [(-1)**(int(v)) * i for v,i in zip(x, xi)] 

clause.append( (-1)**(1-int(y[output_bit])) * yi[output_bit] ) 

C.append(tuple(clause)) 

 

if format is None: 

return C 

elif format == 'symbolic': 

gd = self.ring().gens() 

formula = [] 

for clause in C: 

clause = "|".join([str(gd[abs(v)-1]).replace("-","~") for v in clause]) 

formula.append("("+clause+")") 

return " & ".join(formula) 

 

elif format.startswith('dimacs'): 

if format == "dimacs_headless": 

header = "" 

else: 

header = "p cnf %d %d\n"%(m+n,len(C)) 

values = " 0\n".join([" ".join(map(str,line)) for line in C]) 

return header + values + " 0\n" 

else: 

raise ValueError("Format '%s' not supported."%(format,)) 

 

def component_function(self, b): 

r""" 

Return a Boolean function corresponding to the component function 

`b \cdot S(x)`. 

 

If `S` is an `m \times n` S-Box, then `b \in \GF{2}^n` and 

`\cdot` denotes dot product of two vectors. 

 

INPUT: 

 

- ``b`` -- either an integer or a tuple of `\GF{2}` elements of 

length ``self.n`` 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([7,6,0,4,2,5,1,3]) 

sage: f3 = S.component_function(3) 

sage: f3.algebraic_normal_form() 

x0*x1 + x0*x2 + x0 + x2 

 

sage: f5 = S.component_function([1, 0, 1]) 

sage: f5.algebraic_normal_form() 

x0*x2 + x0 + x1*x2 

""" 

m = self.m 

n = self.n 

ret = BooleanFunction(m) 

 

if isinstance(b, integer_types + (Integer,)): 

b = vector(GF(2), self.to_bits(b, n)) 

elif len(b) == n: 

b = vector(GF(2), b) 

else: 

raise TypeError("cannot compute component function using parameter %s"%(b,)) 

 

for x in range(1<<m): 

ret[x] = bool(b.dot_product(vector(GF(2), self.to_bits(self(x), n)))) 

return ret 

 

def nonlinearity(self): 

""" 

Return the nonlinearity of this S-Box. 

 

The nonlinearity of an S-Box is defined as the minimum nonlinearity 

of all its component functions. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = mq.SR(1,4,4,8).sbox() 

sage: S.nonlinearity() 

112 

""" 

m = self.m 

return (1 << (m-1)) - self.maximal_linear_bias_absolute() 

 

def linearity(self): 

""" 

Return the linearity of this S-Box. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = mq.SR(1, 4, 4, 8).sbox() 

sage: S.linearity() 

32 

""" 

return self.maximal_linear_bias_absolute() << 1 

 

def is_apn(self): 

r""" 

Return ``True`` if this S-Box is an almost perfect nonlinear (APN) 

function. 

 

An `m \times m` S-Box `S` is called almost perfect nonlinear if for 

every nonzero `\alpha \in \GF{2}^m` and every 

`\beta \in \GF{2}^m`, the equation 

`S(x) \oplus S(x \oplus \alpha) = \beta` has 0 or 2 solutions. 

Equivalently, the differential uniformity of `S` is equal to 2. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([0,1,3,6,7,4,5,2]) 

sage: S.is_apn() 

True 

sage: S.differential_uniformity() 

2 

""" 

if self.m != self.n: 

raise TypeError("APN function is only defined for self.m == self.n") 

return self.differential_uniformity() == 2 

 

def differential_branch_number(self): 

r""" 

Return differential branch number of this S-Box. 

 

The differential branch number of an S-Box `S` is defined as 

 

.. MATH:: 

 

\min_{v, w \neq v} \{ \mathrm{wt}(v \oplus w) + \mathrm{wt}(S(v) \oplus S(w)) \} 

 

where `\mathrm{wt}(x)` denotes the Hamming weight of vector `x`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2]) 

sage: S.differential_branch_number() 

3 

""" 

m = self.m 

n = self.n 

ret = (1<<m) + (1<<n) 

 

for a in range(1<<m): 

for b in range(1<<n): 

if (a != b): 

x = a ^ b 

y = self(a) ^ self(b) 

w = ZZ(x).popcount() + ZZ(y).popcount() 

if w < ret: 

ret = w 

return ret 

 

def linear_branch_number(self): 

r""" 

Return linear branch number of this S-Box. 

 

The linear branch number of an S-Box `S` is defined as 

 

.. MATH:: 

 

\min_{\substack{\alpha \neq 0, \beta \\ \mathrm{LAM}(\alpha, \beta) \neq 0}} 

\{ \mathrm{wt}(\alpha) + \mathrm{wt}(\beta) \} 

 

where `\mathrm{LAM}(\alpha, \beta)` is the entry at row `\alpha` and 

column `\beta` of linear approximation matrix correspond to this 

S-Box. The `\mathrm{wt}(x)` denotes the Hamming weight of `x`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2]) 

sage: S.linear_branch_number() 

2 

""" 

m = self.m 

n = self.n 

ret = (1<<m) + (1<<n) 

lat = self.linear_approximation_matrix() 

 

for a in range(1, 1<<m): 

for b in range(1<<n): 

if lat[a,b] != 0: 

w = ZZ(a).popcount() + ZZ(b).popcount() 

if w < ret: 

ret = w 

return ret 

 

@cached_method 

def autocorrelation_matrix(self): 

r""" 

Return autocorrelation matrix correspond to this S-Box. 

 

for an `m \times n` S-Box `S`, its autocorrelation matrix entry at 

row `a \in \GF{2}^m` and column `b \in \GF{2}^n` 

(considering their integer representation) is defined as: 

 

.. MATH:: 

 

\sum_{x \in \GF{2}^m} (-1)^{b \cdot S(x) \oplus b \cdot S(x \oplus a)} 

 

Equivalently, the columns `b` of autocorrelation matrix correspond to 

the autocorrelation spectrum of component function `b \cdot S(x)`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(7,6,0,4,2,5,1,3) 

sage: S.autocorrelation_matrix() 

[ 8 8 8 8 8 8 8 8] 

[ 8 0 0 0 0 0 0 -8] 

[ 8 0 -8 0 0 0 0 0] 

[ 8 0 0 0 0 -8 0 0] 

[ 8 -8 0 0 0 0 0 0] 

[ 8 0 0 0 0 0 -8 0] 

[ 8 0 0 -8 0 0 0 0] 

[ 8 0 0 0 -8 0 0 0] 

""" 

from sage.combinat.matrices.hadamard_matrix import hadamard_matrix 

 

n = self.n 

A = self.difference_distribution_matrix() * hadamard_matrix(1<<n) 

A.set_immutable() 

 

return A 

 

@cached_method 

def boomerang_connectivity_matrix(self): 

r""" 

Return the boomerang connectivity matrix for this S-Box. 

 

Boomerang connectivity matrix of an invertible `m \times m` 

S-Box `S` is an `2^m \times 2^m` matrix with entry at row 

`\Delta_i \in \mathbb{F}_2^m` and column `\Delta_o \in \mathbb{F}_2^m` 

equal to 

 

.. MATH:: 

 

|\{ x \in \mathbb{F}_2^m | S^{-1}( S(x) \oplus \Delta_o) \oplus 

S^{-1}( S(x \oplus \Delta_i) \oplus \Delta_o) = \Delta_i\}|. 

 

For more results concering boomerang connectivity matrix, see [CHPSS18]_ . 

 

EXAMPLES:: 

 

sage: from sage.crypto.sboxes import PRESENT 

sage: PRESENT.boomerang_connectivity_matrix() 

[16 16 16 16 16 16 16 16 16 16 16 16 16 16 16 16] 

[16 0 4 4 0 16 4 4 4 4 0 0 4 4 0 0] 

[16 0 0 6 0 4 6 0 0 0 2 0 2 2 2 0] 

[16 2 0 6 2 4 4 2 0 0 2 2 0 0 0 0] 

[16 0 0 0 0 4 2 2 0 6 2 0 6 0 2 0] 

[16 2 0 0 2 4 0 0 0 6 2 2 4 2 0 0] 

[16 4 2 0 4 0 2 0 2 0 0 4 2 0 4 8] 

[16 4 2 0 4 0 2 0 2 0 0 4 2 0 4 8] 

[16 4 0 2 4 0 0 2 0 2 0 4 0 2 4 8] 

[16 4 2 0 4 0 2 0 2 0 0 4 2 0 4 8] 

[16 0 2 2 0 4 0 0 6 0 2 0 0 6 2 0] 

[16 2 0 0 2 4 0 0 4 2 2 2 0 6 0 0] 

[16 0 6 0 0 4 0 6 2 2 2 0 0 0 2 0] 

[16 2 4 2 2 4 0 6 0 0 2 2 0 0 0 0] 

[16 0 2 2 0 0 2 2 2 2 0 0 2 2 0 0] 

[16 8 0 0 8 0 0 0 0 0 0 8 0 0 8 16] 

""" 

Si = self.inverse() 

 

m = self.m 

n = self.n 

 

nrows = 1 << m 

ncols = 1 << n 

 

A = Matrix(ZZ, nrows, ncols) 

 

for x in range(nrows): 

for di in range(nrows): 

for do in range(ncols): 

l = Si( self(x) ^ do ) 

r = Si( self(x ^ di) ^ do ) 

if (l ^ r == di): 

A[di, do] += 1 

 

A.set_immutable() 

return A 

 

 

def linear_structures(self): 

r""" 

Return a list of 3-valued tuple `(b, \alpha, c)` such that `\alpha` is 

a `c`-linear structure of the component function `b \cdot S(x)`. 

 

A Boolean function `f : \GF{2}^m \mapsto \GF{2}` is said 

to have a `c`-linear structure if there exists a nonzero `\alpha` such 

that `f(x) \oplus f(x \oplus \alpha)` is a constant function `c`. 

 

An `m \times n` S-Box `S` has a linear structure if there exists a 

component function `b \cdot S(x)` that has a linear structure. 

 

The three valued tuple `(b, \alpha, c)` shows that `\alpha` is a 

`c`-linear structure of the component function `b \cdot S(x)`. This 

implies that for all output differences `\beta` of the S-Box 

correspond to input difference `\alpha`, we have `b \cdot \beta = c`. 

 

.. SEEALSO:: 

 

:meth:`is_linear_structure`, 

:meth:`has_linear_structure`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([0,1,3,6,7,4,5,2]) 

sage: S.linear_structures() 

[(1, 1, 1), (2, 2, 1), (3, 3, 1), (4, 4, 1), (5, 5, 1), (6, 6, 1), (7, 7, 1)] 

""" 

n = self.n 

m = self.m 

act = self.autocorrelation_matrix() 

ret = [] 

 

for j in range(1, 1<<n): 

for i in range(1, 1<<m): 

if (abs(act[i,j]) == (1<<m)): 

c = ((1 - (act[i][j] >> self.m)) >> 1) 

ret.append((j, i, c)) 

return ret 

 

def has_linear_structure(self): 

""" 

Return ``True`` if there exists a nonzero component function of this 

S-Box that has a linear structure. 

 

.. SEEALSO:: 

 

:meth:`is_linear_structure`, 

:meth:`linear_structures`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2) 

sage: S.has_linear_structure() 

True 

""" 

return any(self.component_function(i).has_linear_structure() for i in range(1, 1<<self.n)) 

 

def is_linear_structure(self, a, b): 

r""" 

Return ``True`` if `a` is a linear structure of the component function 

`b \cdot S(x)` where S is this `m \times n` S-Box. 

 

INPUT: 

 

- ``a`` -- either an integer or a tuple of `\GF{2}` elements of 

length equal to the input size of SBox 

- ``b`` -- either an integer or a tuple of `\GF{2}` elements of 

length equal to the output size of SBox 

 

.. SEEALSO:: 

 

:meth:`linear_structures`, 

:meth:`has_linear_structure`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2) 

sage: S.component_function(1).autocorrelation() 

(16, -16, 0, 0, 0, 0, 0, 0, -16, 16, 0, 0, 0, 0, 0, 0) 

sage: S.is_linear_structure(1, 1) 

True 

sage: S.is_linear_structure([1, 0, 0, 1], [0, 0, 0, 1]) 

True 

sage: S.is_linear_structure([0, 1, 1, 1], 1) 

False 

""" 

return self.component_function(b).is_linear_structure(a) 

 

def max_degree(self): 

""" 

Return the maximal algebraic degree of all its component functions. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2]) 

sage: S.max_degree() 

3 

""" 

n = self.n 

ret = 0 

 

for i in range(n): 

deg_Si = self.component_function(1<<i).algebraic_normal_form().degree() 

if deg_Si > ret: 

ret = deg_Si 

return ret 

 

def min_degree(self): 

""" 

Return the minimal algebraic degree of all its component functions. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2]) 

sage: S.min_degree() 

2 

""" 

n = self.n 

ret = self.m 

 

for b in range(1, 1<<n): 

deg_bS = self.component_function(b).algebraic_normal_form().degree() 

if deg_bS < ret: 

ret = deg_bS 

return ret 

 

def is_balanced(self): 

r""" 

Return ``True`` if this S-Box is balanced. 

 

An S-Box is balanced if all its component functions are balanced. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2]) 

sage: S.is_balanced() 

True 

""" 

n = self.n 

 

for b in range(1, 1<<n): 

bS = self.component_function(b) 

if not bS.is_balanced(): 

return False 

return True 

 

def is_almost_bent(self): 

r""" 

Return ``True`` if this S-Box is an almost bent (AB) function. 

 

An `m \times m` S-Box `S`, for `m` odd, is called almost bent if its 

nonlinearity is equal to `2^{m-1} - 2^{(m-1)/2}`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([0,1,3,6,7,4,5,2]) 

sage: S.is_almost_bent() 

True 

""" 

if self.m != self.n: 

raise TypeError("almost bent function only exists for self.m == self.n") 

 

m = self.m 

 

if is_even(m): 

return False 

 

return self.nonlinearity() == 2**(m-1) - 2**((m-1)//2) 

 

def fixed_points(self): 

""" 

Return a list of all fixed points of this S-Box. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([0,1,3,6,7,4,5,2]) 

sage: S.fixed_points() 

[0, 1] 

""" 

m = self.m 

return [i for i in range(1<<m) if i == self(i)] 

 

def inverse(self): 

""" 

Return the inverse of this S-Box. 

 

Note that the S-Box must be invertible, otherwise it will raise 

a ``TypeError``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([0, 1, 3, 6, 7, 4, 5, 2]) 

sage: Sinv = S.inverse() 

sage: [Sinv(S(i)) for i in range(8)] 

[0, 1, 2, 3, 4, 5, 6, 7] 

""" 

if not self.is_permutation(): 

raise TypeError("S-Box must be a permutation") 

 

m = self.m 

L = [self(i) for i in range(1<<m)] 

return SBox([L.index(i) for i in range(1<<m)], big_endian=self._big_endian) 

 

def is_monomial_function(self): 

r""" 

Return ``True`` if this S-Box is a monomial/power function. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([0,1,3,6,7,4,5,2]) 

sage: S.is_monomial_function() 

False 

sage: S.interpolation_polynomial() 

(a + 1)*x^6 + (a^2 + a + 1)*x^5 + (a^2 + 1)*x^3 

 

sage: S = SBox(0,1,5,6,7,2,3,4) 

sage: S.is_monomial_function() 

True 

sage: S.interpolation_polynomial() 

x^6 

""" 

return self.interpolation_polynomial().is_monomial() 

 

def is_plateaued(self): 

r""" 

Return ``True`` if this S-Box is plateaued, i.e. for all nonzero 

`b \in \mathbb{F}_2^n` the Boolean function `b \cdot S(x)` 

is plateaued. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox(0, 3, 1, 2, 4, 6, 7, 5) 

sage: S.is_plateaued() 

True 

""" 

n = self.n 

 

for b in range(1, 1<<n): 

bS = self.component_function(b) 

if not bS.is_plateaued(): 

return False 

return True 

 

def is_bent(self): 

r""" 

Return ``True`` if this S-Box is bent, i.e. its nonlinearity 

is equal to `2^{m-1} - 2^{m/2 - 1}` where `m` is the input size 

of the S-Box. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: R.<x> = GF(2**2, 'a')[] 

sage: base = R.base_ring() 

sage: a = base.gen() 

sage: G = a * x^2 + 1 

sage: S = SBox([G(x * y**(14)) for x in sorted(base) for y in sorted(base)]) 

sage: S.is_bent() 

True 

sage: S.nonlinearity() 

6 

sage: S.linear_approximation_matrix() 

[ 8 -2 2 -2] 

[ 0 -2 2 -2] 

[ 0 -2 2 -2] 

[ 0 -2 2 -2] 

[ 0 -2 2 -2] 

[ 0 -2 -2 2] 

[ 0 2 2 2] 

[ 0 2 -2 -2] 

[ 0 -2 2 -2] 

[ 0 2 -2 -2] 

[ 0 -2 -2 2] 

[ 0 2 2 2] 

[ 0 -2 2 -2] 

[ 0 2 2 2] 

[ 0 2 -2 -2] 

[ 0 -2 -2 2] 

""" 

m = self.m 

n = self.n 

 

if not is_even(m) or n > m//2: 

return False 

 

return self.nonlinearity() == 2**(m-1) - 2**(m//2 - 1) 

 

def is_involution(self): 

r""" 

Return ``True`` if this S-Box is an involution, i.e. the inverse S-Box 

is equal itself. 

 

EXAMPLES:: 

 

sage: from sage.crypto.sbox import SBox 

sage: S = SBox([x**254 for x in sorted(GF(2**8))]) 

sage: S.is_involution() 

True 

""" 

return self == self.inverse() 

 

def feistel_construction(*args): 

r""" 

Return an S-Box constructed by Feistel structure using smaller S-Boxes in 

``args``. The number of round in the construction is equal to the number of 

S-Boxes provided as input. For more results concerning the differential 

uniformity and the nonlinearity of S-Boxes constructed by Feistel structures 

see [CDL2015]_ . 

 

INPUT: 

 

- ``args`` - a finite iterable SBox objects 

 

EXAMPLES: 

 

Suppose we construct an `8 \times 8` S-Box with 3-round Feistel construction 

from the S-Box of PRESENT:: 

 

sage: from sage.crypto.sbox import SBox 

sage: s = SBox(12,5,6,11,9,0,10,13,3,14,15,8,4,7,1,2) 

sage: from sage.crypto.sbox import feistel_construction 

sage: S = feistel_construction(s, s, s) 

 

The properties of the constructed S-Box can be easily examined:: 

 

sage: S.nonlinearity() 

96 

sage: S.differential_branch_number() 

2 

sage: S.linear_branch_number() 

2 

""" 

if len(args) == 1: 

if isinstance(args[0], SBox): 

sboxes = [args[0]] 

else: 

sboxes = args[0] 

elif len(args) > 1: 

sboxes = args 

else: 

raise TypeError("No input provided") 

 

for sb in sboxes: 

if not isinstance(sb, SBox): 

raise TypeError("All input must be an instance of SBox object") 

 

b = sboxes[0].m 

m = 2*b 

 

def substitute(x): 

mask = (1<<b) - 1 

xl = (x>>b) & mask 

xr = x & mask 

for sb in sboxes: 

xl, xr = sb(xl) ^ xr, xl 

return (xl<<b) | xr 

 

return SBox([substitute(i) for i in range(1<<m)]) 

 

def misty_construction(*args): 

r""" 

Return an S-Box constructed by MISTY structure using smaller S-Boxes in 

``args``. The number of round in the construction is equal to the number of 

S-Boxes provided as input. For further result related to the nonlinearity 

and differential uniformity of the constructed S-Box one may consult [CDL2015]_. 

 

INPUT: 

 

- ``args`` - a finite iterable SBox objects 

 

EXAMPLES: 

 

We construct an `8 \times 8` S-Box using 3-round MISTY structure with the following 

`4 \times 4` S-Boxes `S1, S2, S3` (see Example 2 in [CDL2015]_):: 

 

sage: from sage.crypto.sbox import SBox 

sage: S1 = SBox([0x4,0x0,0x1,0xF,0x2,0xB,0x6,0x7,0x3,0x9,0xA,0x5,0xC,0xD,0xE,0x8]) 

sage: S2 = SBox([0x0,0x0,0x0,0x1,0x0,0xA,0x8,0x3,0x0,0x8,0x2,0xB,0x4,0x6,0xE,0xD]) 

sage: S3 = SBox([0x0,0x7,0xB,0xD,0x4,0x1,0xB,0xF,0x1,0x2,0xC,0xE,0xD,0xC,0x5,0x5]) 

sage: from sage.crypto.sbox import misty_construction 

sage: S = misty_construction(S1, S2, S3) 

sage: S.differential_uniformity() 

8 

sage: S.linearity() 

64 

""" 

if len(args) == 1: 

if isinstance(args[0], SBox): 

sboxes = [args[0]] 

else: 

sboxes = args[0] 

elif len(args) > 1: 

sboxes = args 

else: 

raise TypeError("No input provided") 

 

for sb in sboxes: 

if not isinstance(sb, SBox): 

raise TypeError("All input must be an instance of SBox object") 

 

b = sboxes[0].m 

m = 2*b 

 

def substitute(x): 

mask = (1<<b) - 1 

xl = (x>>b) & mask 

xr = x & mask 

for sb in sboxes: 

xl, xr = sb(xr) ^ xl, xl 

return (xl<<b) | xr 

 

return SBox([substitute(i) for i in range(1<<m)])