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

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

r""" 

Rijndael-GF 

 

Rijndael-GF is an algebraic implementation of the AES cipher which seeks to 

provide a fully generalized algebraic representation of both the whole AES 

cipher as well as its individual components. 

 

This class is an algebraic implementation of the Rijndael-GF extension of the 

AES cipher, as described in [DR2002]_. The AES cipher itself is defined to 

operate on a state in `(\GF{2})^{8 n_t}` where 

`n_t \in \{16, 20, 24, 28, 32\}`. Rijndael-GF is a generalization of AES which 

allows for operations in `(\GF{2^8})^{n_t}`, enabling more algebraically 

sophisticated study of AES and its variants. This implementation of 

Rijndael-GF is suitable for learning purposes, for comparison to other 

algebraic ciphers, and for studying various techniques of algebraic 

cryptanalysis of AES. This cipher is different from 

:mod:`Mini-AES <sage.crypto.block_cipher.miniaes>`, which is a 

teaching tool for beginners to understand the basic structure of AES. 

 

An algebraic implementation of Rijndael-GF is achieved by recognizing that 

for each round component function `\phi` of AES (SubBytes, ShiftRows, etc.) 

operating on state matrices, every entry of the output matrix `B = \phi(A)` is 

representable as a polynomial with variables being the entries of the input 

state matrix `A`. Correspondingly, this implementation of Rijndael-GF provides 

a ``RijndaelGF.Round_Component_Poly_Constr`` class which allows for creation 

of these such polynomials. For each round component function `\phi` of 

Rijndael-GF there exists a ``Round_Component_Poly_Constr`` object with a 

``__call__`` method of the form ``__call__(i, j)`` which returns a polynomial 

representing `\phi(A)_{i,j}` in terms of the entries of `A`. 

There additionally are various methods provided which allow for easy polynomial 

evaluation and for simple creation of ``Round_Component_Poly_Constr`` objects 

representing more complex aspects of the cipher. 

 

This approach to implementing Rijndael-GF bears some similarity to the 

multivariate quadratic (MQ) systems utilized in :mod:`SR <sage.crypto.mq.sr>`, 

in that the MQ systems also seek to describe the AES cipher as a system of 

algebraic equations. Despite this initial similarity though, Rijndael-GF and 

:mod:`SR <sage.crypto.mq.sr>` are quite different as this implementation 

seeks to provide a fully generalized algebraic representation of both the 

whole AES cipher as well as its individual components, while 

:mod:`SR <sage.crypto.mq.sr>` is instead a family of parameterizable variants 

of the AES suitable as a framework for comparing different cryptanalytic 

techniques that can be brought to bear on the AES. 

 

AUTHORS: 

 

- Thomas Gagne (2015-06): initial version 

 

EXAMPLES 

 

We build Rijndael-GF with a block length of 4 and a key length of 6:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 6) 

 

We can encrypt plaintexts and decrypt and ciphertexts by calling the 

``encrypt`` and ``decrypt`` methods or by calling the Rijndael-GF object 

explicitly. Note that the default input format is a hex string. :: 

 

sage: plaintext = '00112233445566778899aabbccddeeff' 

sage: key = '000102030405060708090a0b0c0d0e0f1011121314151617' 

sage: rgf.encrypt(plaintext, key) 

'dda97ca4864cdfe06eaf70a0ec0d7191' 

sage: rgf.decrypt('dda97ca4864cdfe06eaf70a0ec0d7191', key) 

'00112233445566778899aabbccddeeff' 

 

We can also use binary strings as input and output. :: 

 

sage: plain = '11101011100111110000000111001100' * 4 

sage: key = '01100010111101101000110010111010' * 6 

sage: ciphertext = rgf(plain, key, format='binary') 

sage: ciphertext 

'11010011000010011010110001000011101110110100110100110010011011111100011011100111110011100111010011001110110100011100000011111011' 

sage: rgf(ciphertext, key, algorithm='decrypt', format='binary') == plain 

True 

 

[DR2002]_ demonstrates an example of encryption which takes the plaintext 

'3243f6a8885a308d313198a2e0370734' and the key 

'2b7e151628aed2a6abf7158809cf4f3c' and returns the ciphertext 

'3902dc1925dc116a8409850b1dfb9732'. We can use this example to demonstrate 

the correctness of this implementation:: 

 

sage: rgf = RijndaelGF(4, 4) # change dimensions for this example 

sage: plain = '3243f6a8885a308d313198a2e0370734' 

sage: key = '2b7e151628aed2a6abf7158809cf4f3c' 

sage: expected_ciphertext = '3925841d02dc09fbdc118597196a0b32' 

sage: rgf.encrypt(plain, key) == expected_ciphertext 

True 

 

:: 

 

sage: rgf = RijndaelGF(4, 6) # revert to previous dimensions 

 

To build polynomials representing entries of the output matrix `B = \phi(A)` 

for any round component function `\phi`, each of the round component functions 

(SubBytes, ShiftRows, and MixColumns) have a ``Round_Component_Poly_Constr`` 

object associated with it for building polynomials. These objects can be 

accessed by calling their getter functions: ``rgf.sub_bytes_poly()``, 

``rgf.shift_rows_poly()``, and ``rgf.mix_columns_poly()``. Each returned 

object has a ``__call__`` method which takes an index ``i,j`` and an 

``algorithm`` flag ('encrypt' or 'decrypt') and returns a polynomial 

representing `\phi(A)_{i,j}` in terms of the entries of `A`, where `A` is an 

arbitrary state matrix and `\phi` is the round component function associated 

with that particular ``Round_Component_Poly_Constr`` object. Some of these 

objects' ``__call__`` methods also have additional keywords to modify their 

behavior, and so we describe the usage of each object below. 

 

``rgf.shift_rows_poly()`` and ``rgf.mix_columns_poly()`` do not have any 

additional keywords for their ``__call__`` methods and we can call them as 

such:: 

 

sage: sr_pc = rgf.shift_rows_poly_constr() 

sage: sr_pc(1, 2) 

a13 

sage: sr_pc(2, 3, algorithm='decrypt') 

a21 

 

:: 

 

sage: mc_pc = rgf.mix_columns_poly_constr() 

sage: mc_pc(1, 2) 

a02 + (x)*a12 + (x + 1)*a22 + a32 

sage: mc_pc(2, 3, algorithm='decrypt') 

(x^3 + x^2 + 1)*a03 + (x^3 + 1)*a13 + (x^3 + x^2 + x)*a23 + (x^3 + x + 1)*a33 

 

``rgf.sub_bytes_poly()`` has a single keyword ``no_inversion=False``, which 

when set to ``True`` returns only the affine transformation step of SubBytes. 

Below describes the usage of ``rgf.sub_bytes_poly()`` :: 

 

sage: sb_pc = rgf.sub_bytes_poly_constr() 

sage: sb_pc(1, 2) 

(x^2 + 1)*a12^254 + 

(x^3 + 1)*a12^253 + 

(x^7 + x^6 + x^5 + x^4 + x^3 + 1)*a12^251 + 

(x^5 + x^2 + 1)*a12^247 + 

(x^7 + x^6 + x^5 + x^4 + x^2)*a12^239 + 

a12^223 + 

(x^7 + x^5 + x^4 + x^2 + 1)*a12^191 + 

(x^7 + x^3 + x^2 + x + 1)*a12^127 + 

(x^6 + x^5 + x + 1) 

sage: sb_pc(2, 3, no_inversion=True) 

(x^7 + x^3 + x^2 + x + 1)*a23^128 + 

(x^7 + x^5 + x^4 + x^2 + 1)*a23^64 + 

a23^32 + 

(x^7 + x^6 + x^5 + x^4 + x^2)*a23^16 + 

(x^5 + x^2 + 1)*a23^8 + 

(x^7 + x^6 + x^5 + x^4 + x^3 + 1)*a23^4 + 

(x^3 + 1)*a23^2 + 

(x^2 + 1)*a23 + 

(x^6 + x^5 + x + 1) 

 

Because of the order of the affine transformation and the inversion step in 

SubBytes, calling ``rgf.sub_bytes_poly()(i, j, algorithm='decrypt')`` results 

in a polynomial with thousands of terms which takes a very long time to 

compute. Hence, when using the decryption version of ``rgf.sub_bytes_poly()`` 

with the intention of evaluating the polynomials it constructs, it is 

recommended to first call ``rgf.sub_bytes_poly()(i, j, algorithm='decrypt', 

no_inversion=True)`` to get a polynomial representing only the inverse affine 

transformation, evaluate this polynomial for a particular input block, then 

finally perform the inversion step after the affine transformation polynomial 

has been evaluated. :: 

 

sage: inv_affine = sb_pc(1, 2, algorithm='decrypt', 

....: no_inversion=True) 

sage: state = rgf._hex_to_GF('ff87968431d86a51645151fa773ad009') 

sage: evaluated = inv_affine(state.list()) 

sage: result = evaluated * -1 

sage: rgf._GF_to_hex(result) 

'79' 

 

We can see how the variables of these polynomials are organized in `A`:: 

 

sage: rgf.state_vrs 

[a00 a01 a02 a03] 

[a10 a11 a12 a13] 

[a20 a21 a22 a23] 

[a30 a31 a32 a33] 

 

The final ``Round_Component_Poly_Constr`` object we have not discussed yet is 

``add_round_key_poly``, which corresponds to the AddRoundKey round component 

function. This object differs from the other ``Round_Component_Poly_Constr`` 

objects in that it returns polynomials with variables being entries of an 

input state `A` as well as entries of various subkeys. Since there are `N_r` 

subkeys to choose from, ``add_round_key_poly`` has a keyword of ``round=0`` to 

select which subkey to use variables from. :: 

 

sage: ark_pc = rgf.add_round_key_poly_constr() 

sage: ark_pc(1, 2) 

a12 + k012 

sage: ark_pc(1, 2, algorithm='decrypt') 

a12 + k012 

sage: ark_pc(2, 3, round=7) 

a23 + k723 

 

We can see how key variables are organized in the original key (the key used 

to build the rest of the subkeys) below. Note that because key variables are 

subkey entries, if the key length is longer than the block length we will have 

entries from multiple subkeys in the original key matrix. :: 

 

sage: rgf.key_vrs 

[k000 k001 k002 k003 k100 k101] 

[k010 k011 k012 k013 k110 k111] 

[k020 k021 k022 k023 k120 k121] 

[k030 k031 k032 k033 k130 k131] 

 

We can evaluate any of these constructed polynomials for a particular input 

state (in essence, calculate `\phi(A)_{i,j}`) as such:: 

 

sage: rgf = RijndaelGF(4, 6) 

sage: state = rgf._hex_to_GF('fe7b5170fe7c8e93477f7e4bf6b98071') 

sage: poly = mc_pc(3, 2, algorithm='decrypt') 

sage: poly(state.list()) 

x^7 + x^6 + x^5 + x^2 + x 

 

We can use the ``apply_poly`` method to build a matrix whose `i,j` th 

entry equals the polynomial ``phi_poly(i, j)`` evaluated for a particular input 

state, where ``phi_poly`` is the ``Round_Component_Poly_Constr`` object 

associated with the round component function `\phi`. Essentially, 

``apply_poly`` calculates `\phi(A)`, where `A` is our input state. 

Calling ``apply_poly`` is equivalent to applying the round component function 

associated this ``Round_Component_Poly_Constr`` object to `A`. :: 

 

sage: state = rgf._hex_to_GF('c4cedcabe694694e4b23bfdd6fb522fa') 

sage: result = rgf.apply_poly(state, rgf.sub_bytes_poly_constr()) 

sage: rgf._GF_to_hex(result) 

'1c8b86628e22f92fb32608c1a8d5932d' 

sage: result == rgf.sub_bytes(state) 

True 

 

Alternatively, we can pass a matrix of polynomials as input to ``apply_poly``, 

which will then return another matrix of polynomials. For example, 

``rgf.state_vrs`` can be used as input to make each ``i,j`` th entry of the 

output matrix equal ``phi_poly_constr(i, j)``, where ``phi_poly_constr`` is 

our inputted ``Round_Component_Poly_Constr`` object. This matrix can then be 

passed through again and so on, demonstrating how one could potentially build 

a matrix of polynomials representing the entire cipher. :: 

 

sage: state = rgf.apply_poly(rgf.state_vrs, rgf.shift_rows_poly_constr()) 

sage: state 

[a00 a01 a02 a03] 

[a11 a12 a13 a10] 

[a22 a23 a20 a21] 

[a33 a30 a31 a32] 

sage: rgf.apply_poly(state, rgf.add_round_key_poly_constr()) 

[a00 + k000 a01 + k001 a02 + k002 a03 + k003] 

[a11 + k010 a12 + k011 a13 + k012 a10 + k013] 

[a22 + k020 a23 + k021 a20 + k022 a21 + k023] 

[a33 + k030 a30 + k031 a31 + k032 a32 + k033] 

 

For any of these ``Round_Component_Poly_Constr`` objects, we can change the 

keywords of its ``__call__`` method when ``apply_poly`` invokes it by passing 

``apply_poly`` a dictionary mapping keywords to their values. :: 

 

sage: rgf.apply_poly(rgf.state_vrs, rgf.add_round_key_poly_constr(), 

....: poly_constr_attr={'round' : 5}) 

[a00 + k500 a01 + k501 a02 + k502 a03 + k503] 

[a10 + k510 a11 + k511 a12 + k512 a13 + k513] 

[a20 + k520 a21 + k521 a22 + k522 a23 + k523] 

[a30 + k530 a31 + k531 a32 + k532 a33 + k533] 

 

We can build our own ``Round_Component_Poly_Constr`` objects which correspond 

to the composition of multiple round component functions with the ``compose`` 

method. To do this, if we pass two ``Round_Component_Poly_Constr`` objects 

to ``compose`` where the first object corresponds to the round component 

function `f` and the second to the round component function `g`, ``compose`` 

will return a new ``Round_Component_Poly_Constr`` object corresponding to the 

function `g \circ f`. This returned ``Round_Component_Poly_Constr`` object 

will have the arguments of ``__call__(row, col, algorithm='encrypt')`` and 

when passed an index ``i,j`` will return `g(f(A))_{i,j}` in terms of the 

entries of `A`. :: 

 

sage: rcpc = rgf.compose(rgf.shift_rows_poly_constr(), 

....: rgf.mix_columns_poly_constr()) 

sage: rcpc 

A polynomial constructor of a round component of Rijndael-GF block cipher with block length 4, key length 6, and 12 rounds. 

sage: rcpc(2, 1) 

a01 + a12 + (x)*a23 + (x + 1)*a30 

<BLANKLINE> 

sage: state = rgf._hex_to_GF('afb73eeb1cd1b85162280f27fb20d585') 

sage: result = rgf.apply_poly(state, rcpc) 

sage: new_state = rgf.shift_rows(state) 

sage: new_state = rgf.mix_columns(new_state) 

sage: result == new_state 

True 

<BLANKLINE> 

sage: rcpc = rgf.compose(rgf.mix_columns_poly_constr(), 

....: rgf.shift_rows_poly_constr()) 

sage: result = rgf.apply_poly(state, rcpc, algorithm='decrypt') 

sage: new_state = rgf.mix_columns(state, algorithm='decrypt') 

sage: new_state = rgf.shift_rows(new_state, algorithm='decrypt') 

sage: new_state == result 

True 

 

Alternatively, we can use ``compose`` to build the polynomial output of 

a ``Round_Component_Poly_Constr`` object corresponding to the composition of 

multiple round functions like above without having to explicitly build our 

own ``Round_Component_Poly_Constr`` object. To do this, we simply make the 

first input a ``Round_Component_Poly_Constr`` object corresponding to a 

round component function `f` and make the second input a polynomial 

representing `g(A)_{i,j}` for a round component function `g`. Given this, 

``compose`` will return a polynomial representing `g(f(A))_{i,j}` in terms 

of the entries of `A`. :: 

 

sage: poly = rgf.mix_columns_poly_constr()(0, 3) 

sage: poly 

(x)*a03 + (x + 1)*a13 + a23 + a33 

sage: rgf.compose(rgf.sub_bytes_poly_constr(), poly) 

(x^3 + x)*a03^254 + 

(x^3 + x^2 + x + 1)*a13^254 + 

(x^2 + 1)*a23^254 + 

(x^2 + 1)*a33^254 + 

(x^4 + x)*a03^253 + 

(x^4 + x^3 + x + 1)*a13^253 + 

(x^3 + 1)*a23^253 + 

(x^3 + 1)*a33^253 + 

(x^7 + x^6 + x^5 + x^3 + 1)*a03^251 + 

(x^4)*a13^251 + 

(x^7 + x^6 + x^5 + x^4 + x^3 + 1)*a23^251 + 

(x^7 + x^6 + x^5 + x^4 + x^3 + 1)*a33^251 + 

(x^6 + x^3 + x)*a03^247 + 

(x^6 + x^5 + x^3 + x^2 + x + 1)*a13^247 + 

(x^5 + x^2 + 1)*a23^247 + 

(x^5 + x^2 + 1)*a33^247 + 

(x^7 + x^6 + x^5 + x^4 + x + 1)*a03^239 + 

(x^2 + x + 1)*a13^239 + 

(x^7 + x^6 + x^5 + x^4 + x^2)*a23^239 + 

(x^7 + x^6 + x^5 + x^4 + x^2)*a33^239 + 

(x)*a03^223 + 

(x + 1)*a13^223 + 

a23^223 + 

a33^223 + 

(x^6 + x^5 + x^4 + 1)*a03^191 + 

(x^7 + x^6 + x^2)*a13^191 + 

(x^7 + x^5 + x^4 + x^2 + 1)*a23^191 + 

(x^7 + x^5 + x^4 + x^2 + 1)*a33^191 + 

(x^2 + 1)*a03^127 + 

(x^7 + x^3 + x)*a13^127 + 

(x^7 + x^3 + x^2 + x + 1)*a23^127 + 

(x^7 + x^3 + x^2 + x + 1)*a33^127 + 

(x^6 + x^5 + x + 1) 

 

If we use ``algorithm='decrypt'`` as an argument to ``compose``, then the 

value of ``algorithm`` will be passed directly to the first argument of 

``compose`` (a ``Round_Component_Poly_Constr`` object) when it is called, 

provided the second argument is a polynomial. Setting this flag does nothing 

if both arguments are ``Round_Component_Poly_Constr`` objects, since the 

returned ``Round_Component_Poly_Constr`` object's ``__call__`` method must have 

its own ``algorithm`` keyword defaulted to 'encrypt'. :: 

 

sage: poly = rgf.shift_rows_poly_constr()(2, 1) 

sage: rgf.compose(rgf.mix_columns_poly_constr(), poly, algorithm='decrypt') 

(x^3 + x^2 + 1)*a03 + (x^3 + 1)*a13 + (x^3 + x^2 + x)*a23 + (x^3 + x + 1)*a33 

<BLANKLINE> 

sage: state = rgf._hex_to_GF('80121e0776fd1d8a8d8c31bc965d1fee') 

sage: with_decrypt = rgf.compose(rgf.sub_bytes_poly_constr(), 

....: rgf.shift_rows_poly_constr(), algorithm='decrypt') 

sage: result_wd = rgf.apply_poly(state, with_decrypt) 

sage: no_decrypt = rgf.compose(rgf.sub_bytes_poly_constr(), 

....: rgf.shift_rows_poly_constr()) 

sage: result_nd = rgf.apply_poly(state, no_decrypt) 

sage: result_wd == result_nd 

True 

 

We can also pass keyword dictionaries of ``f_attr`` and ``g_attr`` to 

``compose`` to make ``f`` and ``g`` use those keywords during polynomial 

creation. :: 

 

sage: rcpc = rgf.compose(rgf.add_round_key_poly_constr(), 

....: rgf.add_round_key_poly_constr(), 

....: f_attr={'round' : 4}, g_attr={'round' : 7}) 

sage: rcpc(1, 2) 

a12 + k412 + k712 

 

In addition to building polynomial representations of state matrices, we can 

also build polynomial representations of elements of the expanded key with the 

``expand_key_poly`` method. However, since the key schedule is defined 

recursively, it is impossible to build polynomials for the key schedule in 

the same manner as we do for the round component functions. Consequently, 

``expand_round_key_poly()`` is not a ``Round_Component_Poly_Constr`` object. 

Instead, ``expand_key_poly`` is a method which takes an index ``i,j`` and a 

round number ``round``, and returns a polynomial representing the `i,j` th 

entry of the ``round`` th round key. This polynomial's variables are entries 

of the original key we built above. :: 

 

sage: rgf.expand_key_poly(1, 2, 0) 

k012 

sage: rgf.expand_key_poly(1, 1, 1) 

k111 

sage: rgf.expand_key_poly(1, 2, 1) 

(x^2 + 1)*k121^254 + 

(x^3 + 1)*k121^253 + 

(x^7 + x^6 + x^5 + x^4 + x^3 + 1)*k121^251 + 

(x^5 + x^2 + 1)*k121^247 + 

(x^7 + x^6 + x^5 + x^4 + x^2)*k121^239 + 

k121^223 + 

(x^7 + x^5 + x^4 + x^2 + 1)*k121^191 + 

(x^7 + x^3 + x^2 + x + 1)*k121^127 + 

k010 + 

(x^6 + x^5 + x) 

 

Since ``expand_key_poly`` is not actually a 

``Round_Component_Poly_Constr`` object, we cannot use it as input to 

``apply_poly`` or ``compose``. :: 

 

sage: rgf.apply_poly(state, rgf.expand_key_poly) 

Traceback (most recent call last): 

... 

TypeError: keyword 'poly_constr' must be a Round_Component_Poly_Constr 

sage: rgf.compose(rgf.expand_key_poly, rgf.sub_bytes_poly_constr()) 

Traceback (most recent call last): 

... 

TypeError: keyword 'f' must be a Round_Component_Poly_Constr 

""" 

 

#***************************************************************************** 

# Copyright (C) 2015 Thomas Gagne <thomasgagne100@gmail.com> 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 2 of the License, or 

# (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

from __future__ import print_function, division 

from six import string_types 

 

from sage.matrix.constructor import matrix 

from sage.matrix.constructor import column_matrix 

from sage.structure.element import Matrix 

from sage.rings.finite_rings.finite_field_constructor import FiniteField 

from sage.rings.integer import Integer 

from sage.structure.sage_object import SageObject 

from sage.matrix.matrix_space import MatrixSpace 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

 

class RijndaelGF(SageObject): 

 

def __init__(self, Nb, Nk, state_chr='a', key_chr='k'): 

r""" 

An algebraically generalized version of the AES cipher. 

 

INPUT: 

 

- ``Nb`` -- The block length of this instantiation. Must be between 4 

and 8. 

 

- ``Nk`` -- The key length of this instantiation. Must be between 4 and 8. 

 

- ``state_chr`` -- The variable name for polynomials representing 

elements from state matrices. 

 

- ``key_chr`` -- The variable name for polynomials representing 

elements of the key schedule. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(6, 8) 

sage: rgf 

Rijndael-GF block cipher with block length 6, key length 8, and 14 rounds. 

 

By changing ``state_chr`` we can alter the names of variables in 

polynomials representing elements from state matrices. :: 

 

sage: rgf = RijndaelGF(4, 6, state_chr='myChr') 

sage: rgf.mix_columns_poly_constr()(3, 2) 

(x + 1)*myChr02 + myChr12 + myChr22 + (x)*myChr32 

 

We can also alter the name of variables in polynomials representing 

elements from round keys by changing ``key_chr``. :: 

 

sage: rgf = RijndaelGF(4, 6, key_chr='myKeyChr') 

sage: rgf.expand_key_poly(1, 2, 1) 

(x^2 + 1)*myKeyChr121^254 + 

(x^3 + 1)*myKeyChr121^253 + 

(x^7 + x^6 + x^5 + x^4 + x^3 + 1)*myKeyChr121^251 + 

(x^5 + x^2 + 1)*myKeyChr121^247 + 

(x^7 + x^6 + x^5 + x^4 + x^2)*myKeyChr121^239 + 

myKeyChr121^223 + 

(x^7 + x^5 + x^4 + x^2 + 1)*myKeyChr121^191 + 

(x^7 + x^3 + x^2 + x + 1)*myKeyChr121^127 + 

myKeyChr010 + 

(x^6 + x^5 + x) 

""" 

if Nb not in range(4, 9): 

msg = "Block length Nb must be in the range 4 - 8, not {0}" 

raise ValueError(msg.format(Nb)) 

if Nk not in range(4, 9): 

msg = "Key length Nk must be in the range 4 - 8, not {0}" 

raise ValueError(msg.format(Nk)) 

if not isinstance(state_chr, string_types): 

msg = "state_chr must be a string, not {0}" 

raise TypeError(msg.format(state_chr)) 

if not isinstance(key_chr, string_types): 

msg = "key_chr must be a string, not {0}" 

raise TypeError(msg.format(key_chr)) 

 

self._Nb = Nb 

self._Nk = Nk 

round_num_table = matrix([[10,11,12,13,14], [11,11,12,13,14], 

[12,12,12,13,14], [13,13,13,13,14], 

[14,14,14,14,14]]) 

self._Nr = round_num_table[self._Nb - 4, self._Nk - 4] 

from sage.rings.polynomial.polynomial_ring import polygen 

 

# Build framework for polynomial creation. 

from sage.rings.finite_rings.integer_mod_ring import Integers 

pgen = polygen(Integers(2)) 

mod = pgen**8 + pgen**4 + pgen**3 + pgen + 1 

self._F = FiniteField(2**8, 'x', modulus=mod) 

state_names = [state_chr + str(i) + str(j) 

for i in range(4) for j in range(self._Nb)] 

subkey_names = [key_chr + str(r) + str(i) + str(j) 

for r in range(self._Nr + 1) for i in range(4) 

for j in range(self._Nb)] 

self._state_PR = PolynomialRing(self._F, len(state_names), state_names) 

self._all_PR = PolynomialRing(self._F, len(state_names + subkey_names), 

state_names + subkey_names) 

self.state_vrs = matrix(4, self._Nb, self._state_PR.gens()) 

self.subkey_vrs_list = list(self._all_PR.gens()[4 * self._Nb:]) 

self.subkey_vrs = [matrix(4, self._Nb, 

self.subkey_vrs_list[(4 * self._Nb)*i : 

(4 * self._Nb)*(i+1)]) 

for i in range(self._Nr)] 

self.key_vrs = column_matrix([ 

self.subkey_vrs[int(i / self._Nb)].column(i % 4) 

for i in range(self._Nk)]) 

self._shiftrows_offsets_E = matrix([[0,1,2,3], [0,1,2,3], [0,1,2,3], 

[0,1,2,4], [0,1,3,4]]) 

self._shiftrows_offsets_D = matrix([[0,-1,-2,-3], [0,-1,-2,-3], 

[0,-1,-2,-3], [0,-1,-2,-4], 

[0,-1,-3,-4]]) 

self._sb_E_coeffs = [self._F("x^2 + 1"), 

self._F("x^3 + 1"), 

self._F("x^7 + x^6 + x^5 + x^4 + x^3 + 1"), 

self._F("x^5 + x^2 + 1"), 

self._F("x^7 + x^6 + x^5 + x^4 + x^2"), 

self._F("1"), 

self._F("x^7 + x^5 + x^4 + x^2 + 1"), 

self._F("x^7 + x^3 + x^2 + x + 1")] 

self._sb_D_coeffs = [self._F("x^2 + 1"), 

self._F("x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + x"), 

self._F("x^6 + x^5 + x^4 + x^3 + x^2 + x + 1"), 

self._F("x^6 + x^4 + x^3 + x"), 

self._F("x^6 + x^5 + x^4 + x^3"), 

self._F("x^6 + x^4 + x^3 + 1"), 

self._F("x^7 + x^6 + x^4 + x^3 + x + 1"), 

self._F("x^6 + x^5 + x^3 + x^2 + x")] 

mixcols_E_row = [self._F('x'), self._F('x+1'), self._F('1'), 

self._F('1')] 

self._mixcols_E = matrix([mixcols_E_row[-i:] + mixcols_E_row[:-i] 

for i in range(4)]) 

mixcols_D_row = [self._F('x^3 + x^2 + x'), self._F('x^3 + x + 1'), 

self._F('x^3 + x^2 + 1'), self._F('x^3 + 1')] 

self._mixcols_D = matrix([mixcols_D_row[-i:] + mixcols_D_row[:-i] 

for i in range(4)]) 

# Build the Round_Component_Poly_Constr objects 

self._add_round_key_rcpc = \ 

RijndaelGF.Round_Component_Poly_Constr(self._add_round_key_pc, self, 

"Add Round Key") 

self._sub_bytes_rcpc = \ 

RijndaelGF.Round_Component_Poly_Constr(self._sub_bytes_pc, self, 

"SubBytes") 

self._mix_columns_rcpc = \ 

RijndaelGF.Round_Component_Poly_Constr(self._mix_columns_pc, self, 

"Mix Columns") 

self._shift_rows_rcpc = \ 

RijndaelGF.Round_Component_Poly_Constr(self._shift_rows_pc, self, 

"Shift Rows") 

 

def __call__(self, text, key, algorithm='encrypt', format='hex'): 

r""" 

Returns the encryption/decryption of ``text`` with key ``key``. 

 

INPUT: 

 

- ``text`` -- A plaintext to encrypt or a ciphertext to decrypt. 

 

- ``key`` -- The key to encrypt/decrypt ``text`` with. 

 

- ``algorithm`` -- Whether to encrypt or decrypt ``text``. Flag for 

encryption is "encrypt", flag for decryption is "decrypt". 

 

- ``format`` -- The format of ``text`` and ``key``, either "hex" or 

"binary" 

 

OUTPUT: 

 

- The encrypted or decrypted message ``text`` with key ``key``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: text = 'ef053f7c8b3d32fd4d2a64ad3c93071a' 

sage: key = '2d7e86a339d9393ee6570a1101904e16' 

sage: rgf(text, key) 

'84e75b142c8fd5a445312c0a9b2d6699' 

sage: rgf(text, key, algorithm='decrypt') 

'9bf83275406304f050c826ca72d035e6' 

 

We can also use binary strings for ``text`` and ``key``. :: 

 

sage: text = '11011100011010000011101111011011' * 4 

sage: key = '01000000000011000101101011011110' * 4 

sage: rgf(text, key, format='binary') 

'00011000010110010011100100010111010101001000010010100110101010101111001001100000011111011100100011010001010100110011000111110011' 

sage: rgf(text, key, algorithm='decrypt', format='binary') 

'11000110011001001110000101011101001001010101110001110010000111110000010111111101000011010101101011111100100001010010111000011010' 

""" 

 

if algorithm == 'encrypt': 

return self.encrypt(text, key, format) 

elif algorithm == 'decrypt': 

return self.decrypt(text, key, format) 

else: 

raise ValueError(("keyword 'algorithm' must be either 'encrypt' " 

"or 'decrypt'")) 

 

def __repr__(self): 

r""" 

Returns the string representation of ``self``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(5, 8) 

sage: rgf 

Rijndael-GF block cipher with block length 5, key length 8, and 14 rounds. 

""" 

 

msg = ("Rijndael-GF block cipher with block length {0}, key length " 

"{1}, and {2} rounds.") 

return msg.format(self._Nb, self._Nk, self._Nr) 

 

def block_length(self): 

r""" 

Returns the block length of this instantiation of Rijndael-GF. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 6) 

sage: rgf.block_length() 

4 

""" 

return self._Nb 

 

def key_length(self): 

r""" 

Returns the key length of this instantiation of Rijndael-GF. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 8) 

sage: rgf.key_length() 

8 

""" 

return self._Nk 

 

def number_rounds(self): 

r""" 

Returns the number of rounds used in this instantiation of Rijndael-GF. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(5, 4) 

sage: rgf.number_rounds() 

11 

""" 

return self._Nr 

 

def _hex_to_GF(self, H, matrix=True): 

r""" 

Returns a matrix/list of elements of `\GF{2^8}` corresponding to ``H``. 

 

INPUT: 

 

- ``H`` -- A hex string where every two hex characters correspond to a 

single element in `\GF{2^8}` 

 

- ``matrix`` -- (default: ``True``) Returns a list if ``False``; 

returns a state matrix if ``True``. 

 

OUTPUT: 

 

- A list of or a state matrix of elements of `\GF{2^8}` where each 

element corresponds to the appropriate hex value in ``H``. In 

particular, every element `a_7x^7 + a_6x^6 + a_5x^5 + a_4x^4 + 

a_3x^3 + a_2x^2 + a_1x^1 + a_0` in `\GF{2^8}` corresponds to the 

8-bit binary string '`a_7a_6a_5a_4a_3a_2a_1a_0`'. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: state = rgf._hex_to_GF('1147659047cf663b9b0ece8dfc0bf1f0') 

sage: output = rgf.shift_rows(state) 

sage: rgf._GF_to_hex(output) 

'11cfcef0470ef1909b0b653bfc47668d' 

 

We can output a list instead by setting ``matrix`` to ``False``. :: 

 

sage: rgf._hex_to_GF('2f', matrix=False) 

[x^5 + x^3 + x^2 + x + 1] 

sage: rgf._hex_to_GF('1a2b0f', matrix=False) 

[x^4 + x^3 + x, x^5 + x^3 + x + 1, x^3 + x^2 + x + 1] 

""" 

if not isinstance(H, string_types) or \ 

any(c not in '0123456789abcdefABCDEF' for c in H): 

raise TypeError("keyword 'H' must be a hex string") 

 

def hx_to_gf(h): 

return self._F(map(int, bin(int(h, 16))[2:].zfill(8))[::-1]) 

hexes = [H[2 * i] + H[2 * i + 1] for i in range(len(H) // 2)] 

result = [hx_to_gf(h) for h in hexes] 

if matrix: 

return column_matrix(len(result) // 4, 4, result) 

else: 

return result 

 

def _GF_to_hex(self, GF): 

r""" 

Returns the hex string representation of ``GF``. 

 

INPUT: 

 

- ``GF`` -- Either a state matrix over `\GF{2^8}`, a list of elements 

from `\GF{2^8}`, or a single element from `\GF{2^8}` 

 

OUTPUT: 

 

- A hex string representation of ``GF``, where every two characters in 

the string correspond to a single element in `\GF{2^8}`. In 

particular, every element `a_7x^7 + a_6x^6 + a_5x^5 + a_4x^4 + 

a_3x^3 + a_2x^2 + a_1x^1 + a_0` in `\GF{2^8}` corresponds to the 

8-bit binary string '`a_7a_6a_5a_4a_3a_2a_1a_0`'. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4,4) 

sage: F.<a> = GF(2^8) 

sage: els = [a^7 + a^5 + a + 1, a^7 + a^6 + a^4 + a^2] 

sage: rgf._GF_to_hex(els) 

'a3d4' 

<BLANKLINE> 

sage: h = '8fb999c973b26839c7f9d89d85c68c72' 

sage: h == rgf._GF_to_hex(rgf._hex_to_GF(h)) 

True 

 

We can use this to get concise output from round functions. :: 

 

sage: plain = rgf._hex_to_GF('72b86c7c0f0d52d3e0d0da104055036b') 

sage: key = rgf._hex_to_GF('93faa123c2903f4743e4dd83431692de') 

sage: output = rgf.add_round_key(plain, key) 

sage: rgf._GF_to_hex(output) 

'e142cd5fcd9d6d94a3340793034391b5' 

""" 

from sage.rings.finite_rings.element_base import is_FiniteFieldElement 

if not isinstance(GF, Matrix) and \ 

not isinstance(GF, list) and \ 

not is_FiniteFieldElement(GF): 

msg = ("keyword 'GF' must be a matrix over {0}, a list of " 

"elements from {0}, or a single element from {0}") 

raise TypeError(msg.format(self._F)) 

 

if isinstance(GF, Matrix): 

if not GF.base_ring().is_field() or \ 

not GF.base_ring().is_finite() or \ 

not GF.base_ring().order() == 2**8: 

msg = "The elements of keyword 'GF' must all be from {0}" 

raise TypeError(msg.format(self._F)) 

return ''.join([self._GF_to_hex(el) 

for col in GF.columns() for el in col]) 

elif isinstance(GF, list): 

if not all([g.parent().is_field() and g.parent().is_finite() and 

g.parent().order() == 2**8 for g in GF]): 

msg = "The elements of keyword 'GF' must all be from {0}" 

raise TypeError(msg.format(self._F)) 

return ''.join([self._GF_to_hex(el) for el in GF]) 

else: 

if not GF.parent().is_field() or \ 

not GF.parent().is_finite() or \ 

not GF.parent().order() == 2**8: 

msg = "keyword 'GF' must be in" 

raise TypeError(msg.format(self._F)) 

return hex(GF.integer_representation())[2:].zfill(2) 

 

def _bin_to_GF(self, B, matrix=True): 

r""" 

Returns a matrix/list of elements of `\GF{2^8}` corresponding to ``B``. 

 

INPUT: 

 

- ``B`` -- A binary string where every eight bits correspond to a 

single element in `\GF{2^8}` 

 

- ``matrix`` -- (default: ``True``) Returns a list if ``False``. 

Returns a state matrix over `\GF{2^8}` if ``True``. 

 

OUTPUT: 

 

- A list of or a state matrix of elements of `\GF{2^8}` where each 

element corresponds to the appropriate 8-bit binary string in ``B``. 

In particular, every element `a_7x^7 + a_6x^6 + a_5x^5 + a_4x^4 + 

a_3x^3 + a_2x^2 + a_1x^1 + a_0` in `\GF{2^8}` corresponds to the 

8-bit binary string '`a_7a_6a_5a_4a_3a_2a_1a_0`'. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: bs = '11101011100111110000000111001100' * 4 

sage: len(bs) 

128 

sage: state = rgf._bin_to_GF(bs) 

sage: output = rgf.sub_bytes(state) 

sage: rgf._GF_to_bin(output) 

'11101001110110110111110001001011111010011101101101111100010010111110100111011011011111000100101111101001110110110111110001001011' 

 

We can make this method output a list by setting ``matrix`` to 

``False``. :: 

 

sage: bs = '01010011' 

sage: rgf._bin_to_GF(bs, matrix=False) 

[x^6 + x^4 + x + 1] 

sage: bs = '000100000111001000110101110001101101011100110101' 

sage: rgf._bin_to_GF(bs, matrix=False) 

[x^4, 

x^6 + x^5 + x^4 + x, 

x^5 + x^4 + x^2 + 1, 

x^7 + x^6 + x^2 + x, 

x^7 + x^6 + x^4 + x^2 + x + 1, 

x^5 + x^4 + x^2 + 1] 

""" 

if not isinstance(B, string_types) or any(c not in '01' for c in B): 

raise TypeError("keyword 'B' must be a binary string") 

 

def bn_to_gf(b): 

return self._F(map(int, b)[::-1]) 

bins = [B[8 * i : 8 * (i + 1)] for i in range(len(B) // 8)] 

result = [bn_to_gf(b) for b in bins] 

if matrix: 

return column_matrix(len(result) // 4, 4, result) 

else: 

return result 

 

def _GF_to_bin(self, GF): 

r""" 

Returns the binary string representation of ``GF``. 

 

INPUT: 

 

- ``GF`` -- Either a state matrix over `\GF{2^8}`, a list of elements 

from `\GF{2^8}`, or a single element from `\GF{2^8}` 

 

OUTPUT: 

 

- A binary string representation of ``GF``, where every eight 

characters in the string corresponds to a single element in 

`\GF{2^8}`. In particular, every element `a_7x^7 + a_6x^6 + a_5x^5 + 

a_4x^4 + a_3x^3 + a_2x^2 + a_1x^1 + a_0` in `\GF{2^8}` corresponds 

to the binary string '`a_7a_6a_5a_4a_3a_2a_1a_0`'. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: F.<a> = GF(2^8) 

sage: els = [a^7 + a^5 + a + 1, a^7 + a^6 + a^4 + a^2] 

sage: rgf._GF_to_bin(els) 

'1010001111010100' 

 

We can use this to get clearer output from the round functions. :: 

 

sage: plain = '11101011100111110000000111001100' * 4 

sage: plain_state = rgf._bin_to_GF(plain) 

sage: key = '00110011100000001111100111010111' * 4 

sage: key_state = rgf._bin_to_GF(key) 

sage: output = rgf.add_round_key(plain_state, key_state) 

sage: rgf._GF_to_bin(output) 

'11011000000111111111100000011011110110000001111111111000000110111101100000011111111110000001101111011000000111111111100000011011' 

""" 

from sage.rings.finite_rings.element_base import is_FiniteFieldElement 

if not isinstance(GF, Matrix) and \ 

not isinstance(GF, list) and \ 

not is_FiniteFieldElement(GF): 

msg = ("keyword 'GF' must be a matrix over {0}, a list of " 

"elements from {0}, or a single element from {0}") 

raise TypeError(msg.format(self)) 

 

if isinstance(GF, Matrix): 

if not GF.base_ring().is_field() or \ 

not GF.base_ring().is_finite() or \ 

not GF.base_ring().order() == 2**8: 

msg = "The elements of keyword 'GF' must all be from {0}" 

raise TypeError(msg.format(self._F)) 

return ''.join([self._GF_to_bin(el) 

for col in GF.columns() for el in col]) 

elif isinstance(GF, list): 

if not all([g.parent().is_field() and g.parent().is_finite() and 

g.parent().order() == 2**8 for g in GF]): 

msg = "The elements of keyword 'GF' must all be from {0}" 

raise TypeError(msg.format(self._F)) 

return ''.join([self._GF_to_bin(el) for el in GF]) 

else: 

if not GF.parent().is_field() or \ 

not GF.parent().is_finite() or \ 

not GF.parent().order() == 2**8: 

msg = "keyword 'GF' must be in" 

raise TypeError(msg.format(self._F)) 

return bin(GF.integer_representation())[2:].zfill(8) 

 

def encrypt(self, plain, key, format='hex'): 

r""" 

Returns the plaintext ``plain`` encrypted with the key ``key``. 

 

INPUT: 

 

- ``plain`` -- The plaintext to be encrypted. 

 

- ``key`` -- The key to encrypt ``plain`` with. 

 

- ``format`` -- (default: ``hex``) The string format of ``key`` and 

``plain``, either "hex" or "binary". 

 

OUTPUT: 

 

- A string of the plaintext ``plain`` encrypted with the key ``key``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: key = 'c81677bc9b7ac93b25027992b0261996' 

sage: plain = 'fde3bad205e5d0d73547964ef1fe37f1' 

sage: expected_ciphertext = 'e767290ddfc6414e3c50a444bec081f0' 

sage: rgf.encrypt(plain, key) == expected_ciphertext 

True 

 

We can encrypt binary strings as well. :: 

 

sage: key = '10010111110000011111011011010001' * 4 

sage: plain = '00000000101000000000000001111011' * 4 

sage: expected_ciphertext = ('11010111100100001010001011110010111' 

....: '1110011000000011111100100011011100101000000001000111000010' 

....: '00100111011011001000111101111110100') 

sage: result = rgf.encrypt(plain, key, format='binary') 

sage: result == expected_ciphertext 

True 

""" 

if format == 'hex': 

if not isinstance(plain, string_types) or \ 

any(c not in '0123456789abcdefABCDEF' for c in plain): 

raise TypeError("'plain' keyword must be a hex string") 

if len(plain) != 8 * self._Nb: 

msg = "'plain' keyword\'s length must be {0}, not{1}" 

raise ValueError(msg.format(8 * self._Nb, len(plain))) 

if not isinstance(key, string_types) or \ 

any(c not in '0123456789abcdefABCDEF' for c in key): 

raise TypeError("'key' keyword must be a hex string") 

if len(key) != 8 * self._Nk: 

msg = "'key' keyword's length must be {0}, not {1}" 

raise ValueError(msg.format(8 * self._Nk, len(key))) 

state = self._hex_to_GF(plain) 

key_state = self._hex_to_GF(key) 

roundKeys = self.expand_key(key_state) 

elif format == 'binary': 

if not isinstance(plain, string_types) or \ 

any(c not in '01' for c in plain): 

raise TypeError("'plain' keyword must be a binary string") 

if len(plain) != 32 * self._Nb: 

msg = "'plain' keyword's length must be {0}, not {1}" 

raise ValueError(msg.format(32 * self._Nb, len(plain))) 

if not isinstance(key, string_types) or \ 

any(c not in '01' for c in key): 

raise TypeError("'key' keyword must be a binary string") 

if len(key) != 32 * self._Nk: 

msg = "'key' keyword's length must be {0}, not {1}" 

raise ValueError(msg.format(32 * self._Nk, len(key))) 

state = self._bin_to_GF(plain) 

key_state = self._bin_to_GF(key) 

roundKeys = self.expand_key(key_state) 

else: 

raise ValueError(("'format' keyword must be either 'hex' or " 

"'binary'")) 

 

state = self.add_round_key(state, roundKeys[0]) 

for r in range(self._Nr-1): 

state = self.sub_bytes(state, algorithm='encrypt') 

state = self.shift_rows(state, algorithm='encrypt') 

state = self.mix_columns(state, algorithm='encrypt') 

state = self.add_round_key(state, roundKeys[r+1]) 

state = self.sub_bytes(state, algorithm='encrypt') 

state = self.shift_rows(state, algorithm='encrypt') 

state = self.add_round_key(state, roundKeys[self._Nr]) 

 

if format == 'hex': 

return self._GF_to_hex(state) 

else: 

return self._GF_to_bin(state) 

 

def decrypt(self, ciphertext, key, format='hex'): 

r""" 

Returns the ciphertext ``ciphertext`` decrypted with the key ``key``. 

 

INPUT: 

 

- ``ciphertext`` -- The ciphertext to be decrypted. 

 

- ``key`` -- The key to decrypt ``ciphertext`` with. 

 

- ``format`` -- (default: ``hex``) The string format that both 

``ciphertext`` and ``key`` must be in, either "hex" or "binary". 

 

OUTPUT: 

 

- A string in the format ``format`` of ``ciphertext`` decrypted with 

key ``key``. 

 

EXAMPLES :: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: key = '2dfb02343f6d12dd09337ec75b36e3f0' 

sage: ciphertext = '54d990a16ba09ab596bbf40ea111702f' 

sage: expected_plaintext = '1e1d913b7274ad9b5a4ab1a5f9133b93' 

sage: rgf.decrypt(ciphertext, key) == expected_plaintext 

True 

 

We can also decrypt messages using binary strings. :: 

 

sage: key = '00011010000011100011000000111101' * 4 

sage: ciphertext = '00110010001110000111110110000001' * 4 

sage: expected_plaintext = ('101111111010011100111100101010100111' 

....: '1111010000101101100001101000000000000000010000000100111011' 

....: '0100001111100011010001101101001011') 

sage: result = rgf.decrypt(ciphertext, key, format='binary') 

sage: result == expected_plaintext 

True 

""" 

if format == 'hex': 

if not isinstance(ciphertext, string_types) or \ 

any(c not in '0123456789abcdefABCDEF' for c in ciphertext): 

raise TypeError("'ciphertext' keyword must be a hex string") 

if len(ciphertext) != 8 * self._Nb: 

msg = "'ciphertext' keyword's length must be {0}, not{1}" 

raise ValueError(msg.format(8 * self._Nb, len(ciphertext))) 

if not isinstance(key, string_types) or \ 

any(c not in '0123456789abcdefABCDEF' for c in key): 

raise TypeError("'key' keyword must be a hex string") 

if len(key) != 8 * self._Nk: 

msg = "'key' keyword's length must be {0}, not {1}" 

raise ValueError(msg.format(8 * self._Nk, len(key))) 

state = self._hex_to_GF(ciphertext) 

key_state = self._hex_to_GF(key) 

roundKeys = self.expand_key(key_state) 

elif format == 'binary': 

if not isinstance(ciphertext, string_types) or \ 

any(c not in '01' for c in ciphertext): 

raise TypeError(("'ciphertext' keyword must be a binary " 

"string")) 

if len(ciphertext) != 32 * self._Nb: 

msg = "'ciphertext' keyword's length must be {0}, not {1}" 

raise ValueError(msg.format(32 * self._Nb, len(ciphertext))) 

if not isinstance(key, string_types) or \ 

any(c not in '01' for c in key): 

raise TypeError("'key' keyword must be a binary string") 

if len(key) != 32 * self._Nk: 

msg = "'key' keyword\'s length must be {0}, not {1}" 

raise ValueError(msg.format(32 * self._Nk, len(key))) 

state = self._bin_to_GF(ciphertext) 

key_state = self._bin_to_GF(key) 

roundKeys = self.expand_key(key_state) 

else: 

raise ValueError(("'format' keyword must be either \'hex\' or " 

"'binary'")) 

 

state = self.add_round_key(state, roundKeys[self._Nr]) 

state = self.shift_rows(state, algorithm='decrypt') 

state = self.sub_bytes(state, algorithm='decrypt') 

for r in range(self._Nr-1): 

state = self.add_round_key(state, roundKeys[self._Nr - r - 1]) 

state = self.mix_columns(state, algorithm='decrypt') 

state = self.shift_rows(state, algorithm='decrypt') 

state = self.sub_bytes(state, algorithm='decrypt') 

state = self.add_round_key(state, roundKeys[0]) 

 

if format == 'hex': 

return self._GF_to_hex(state) 

else: 

return self._GF_to_bin(state) 

 

def _check_valid_PRmatrix(self, PRm, keyword): 

r""" 

Raises an error if ``PRm`` is not a valid input matrix over ``F``. 

 

INPUT: 

 

- ``PRm`` -- If ``PRm`` is a `4 \times Nb` matrix with entries from 

the multivariate PolynomialRing ``_all_PR``, this method does nothing 

`\GF{2^8}`, this method does nothing. Otherwise, this method raises 

an error. Note that a matrix of elements from `\GF{2^8}` is regarded 

as a matrix with entries from ``_all_PR`` and will pass this test. 

 

- ``keyword`` -- The name of the keyword ``PRm`` from where this 

method was called, for the potential error message. For example, if 

called from ``sub_bytes``, ``keyword`` would be "state". 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: good_state = rgf._hex_to_GF('0'*32) 

sage: rgf._check_valid_PRmatrix(good_state, 'state') 

sage: rgf._check_valid_PRmatrix(rgf.state_vrs, 'state') 

sage: rgf._check_valid_PRmatrix(5, 'state') 

Traceback (most recent call last): 

... 

TypeError: keyword 'state' must be a 4 x 4 matrix with entries from a multivariate PolynomialRing over Finite Field in x of size 2^8 

<BLANKLINE> 

sage: entries = [rgf._F.random_element() for i in range(24)] 

sage: wrong_dimensions = matrix(4, 6, entries) 

sage: rgf._check_valid_PRmatrix(wrong_dimensions, 'state') 

Traceback (most recent call last): 

... 

TypeError: keyword 'state' must be a 4 x 4 matrix with entries from a multivariate PolynomialRing over Finite Field in x of size 2^8 

<BLANKLINE> 

sage: F.<a> = GF(3^4) 

sage: entries = [F.random_element() for i in range(16)] 

sage: wrong_base = matrix(4, 4, entries) 

sage: rgf._check_valid_PRmatrix(wrong_base, 'state') 

Traceback (most recent call last): 

... 

TypeError: keyword 'state' must be a 4 x 4 matrix with entries from a multivariate PolynomialRing over Finite Field in x of size 2^8 

""" 

from sage.rings.polynomial.multi_polynomial_ring_generic import \ 

MPolynomialRing_generic 

msg = ("keyword '{0}' must be a {1} x {2} matrix with entries from a " 

"multivariate PolynomialRing over {3}") 

msg = msg.format(keyword, 4, self._Nb, self._F) 

if (not isinstance(PRm, Matrix) or \ 

not (PRm.base_ring().is_field() and \ 

PRm.base_ring().is_finite() and \ 

PRm.base_ring().order() == 256 and \ 

PRm.dimensions() == (4, self._Nb))) and \ 

(not isinstance(PRm, Matrix) or \ 

not isinstance(PRm.base_ring(), MPolynomialRing_generic) or \ 

not (PRm.base_ring().base_ring().is_field() and \ 

PRm.base_ring().base_ring().is_finite() and \ 

PRm.base_ring().base_ring().order() == 256) or \ 

not PRm.dimensions() == (4, self._Nb)): 

raise TypeError(msg) 

 

def expand_key(self, key): 

r""" 

Returns the expanded key schedule from ``key``. 

 

INPUT: 

 

- ``key`` -- The key to build a key schedule from. Must be a matrix 

over `\GF{2^8}` of dimensions `4 \times N_k`. 

 

OUTPUT: 

 

- A length `Nr` list of `4 \times N_b` matrices corresponding to the 

expanded key. The `n` th entry of the list corresponds to the matrix 

used in the ``add_round_key`` step of the `n` th round. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 6) 

sage: key = '331D0084B176C3FB59CAA0EDA271B565BB5D9A2D1E4B2892' 

sage: key_state = rgf._hex_to_GF(key) 

sage: key_schedule = rgf.expand_key(key_state) 

sage: rgf._GF_to_hex(key_schedule[0]) 

'331d0084b176c3fb59caa0eda271b565' 

sage: rgf._GF_to_hex(key_schedule[6]) 

'5c5d51c4121f018d0f4f3e408ae9f78c' 

""" 

msg = "keyword '{0}' must be a {1} x {2} matrix over GF({3})" 

msg = msg.format(key, 4, self._Nk, self._F.order()) 

if not isinstance(key, Matrix) or \ 

not (key.base_ring().is_field() and \ 

key.base_ring().is_finite() and \ 

key.base_ring().order() == self._F.order()) or \ 

not key.dimensions() == (4, self._Nk): 

raise TypeError(msg) 

 

def add_cols(col1, col2): 

return [x + y for x, y in zip(col1, col2)] 

 

key_cols = [] 

for i in range(self._Nb * (self._Nr + 1)): 

key_cols.append([]) 

 

# Copy columns from ``key``, then build the rest of the columns 

for j in range(self._Nk): 

key_cols[j] = list(key.columns()[j]) 

for j in range(self._Nk, self._Nb * (self._Nr + 1)): 

if j % self._Nk == 0: 

# Apply non-linear function to k[j - 1] 

add_key = map(self._srd, key_cols[j - 1]) 

add_key = add_key[1:] + add_key[:1] 

add_key[0] += self._F.gen() ** (int(j / self._Nk) - 1) 

key_cols[j] = add_cols(key_cols[j - self._Nk], add_key) 

else: 

add_key = key_cols[j - 1] 

if self._Nk > 6 and j % self._Nk == 4: 

add_key = map(self._srd, add_key) 

key_cols[j] = add_cols(key_cols[j - self._Nk], add_key) 

 

# Copy the expanded columns into 4xNb blocks 

round_keys = [] 

for r in range(self._Nr + 1): 

rk = column_matrix([key_cols[r*self._Nb + i] 

for i in range(self._Nb)]) 

round_keys.append(rk) 

return round_keys 

 

def expand_key_poly(self, row, col, round): 

r""" 

Returns a polynomial representing the ``row,col`` th entry of the 

``round`` th round key. 

 

INPUT: 

 

- ``row`` -- The row position of the element represented by this 

polynomial. 

 

- ``col`` -- The column position of the element represented by this 

polynomial. 

 

OUTPUT: 

 

- A polynomial representing the ``row,col`` th entry of the ``round`` 

th round key in terms of entries of the input key. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: rgf.expand_key_poly(1, 2, 0) 

k012 

sage: rgf.expand_key_poly(1, 2, 1) 

(x^2 + 1)*k023^254 + 

(x^3 + 1)*k023^253 + 

(x^7 + x^6 + x^5 + x^4 + x^3 + 1)*k023^251 + 

(x^5 + x^2 + 1)*k023^247 + 

(x^7 + x^6 + x^5 + x^4 + x^2)*k023^239 + 

k023^223 + 

(x^7 + x^5 + x^4 + x^2 + 1)*k023^191 + 

(x^7 + x^3 + x^2 + x + 1)*k023^127 + 

k010 + 

k011 + 

k012 + 

(x^6 + x^5 + x) 

 

It should be noted that ``expand_key_poly`` cannot be used with 

``apply_poly`` or ``compose``, since ``expand_key_poly`` is not a 

``Round_Component_Poly_Constr`` object. :: 

 

sage: rgf.compose(rgf.sub_bytes_poly_constr(), rgf.expand_key_poly) 

Traceback (most recent call last): 

... 

TypeError: keyword 'g' must be a Round_Component_Poly_Constr or a polynomial over Finite Field in x of size 2^8 

<BLANKLINE> 

sage: state = rgf._hex_to_GF('00000000000000000000000000000000') 

sage: rgf.apply_poly(state, rgf.expand_key_poly) 

Traceback (most recent call last): 

... 

TypeError: keyword 'poly_constr' must be a Round_Component_Poly_Constr 

""" 

if row not in range(4): 

raise ValueError("keyword 'row' must be between 0 and 4") 

if col not in range(self._Nb): 

msg = "keyword 'col' must be between 0 and {0}" 

raise ValueError(msg.format(self._Nb)) 

if round not in range(self._Nr + 1): 

msg = "keyword 'r' must be between 0 and {0}" 

raise ValueError(msg.format(self._Nr)) 

 

key_col = round * self._Nb + col 

if key_col < self._Nk: 

return self.key_vrs[row, key_col] 

else: 

if key_col % self._Nk == 0 or \ 

(self._Nk > 6 and col % self._Nk == 4): 

# Apply non-linear transformation to key_col - 1 

recur_r = int((key_col - 1)/self._Nb) 

recur_j = (key_col - 1) - (recur_r * self._Nb) 

non_linear = self.expand_key_poly((row+1) % 4, 

recur_j, recur_r) 

non_linear = self._srd(non_linear) 

non_linear += self._F.gen() ** (int(key_col / self._Nk) - 1) 

# Identify key_col - Nk 

recur_r = int((key_col - self._Nk)/self._Nb) 

recur_j = (key_col - self._Nk) - (recur_r * self._Nb) 

return self.expand_key_poly(row, recur_j, recur_r) + non_linear 

else: 

# Identify key_col - Nk 

recur_r = int((key_col - self._Nk)/self._Nb) 

recur_j = (key_col - self._Nk) - (recur_r * self._Nb) 

result = self.expand_key_poly(row, recur_j, recur_r) 

# Identify key_col - 1 

recur_r = int((key_col- 1)/self._Nb) 

recur_j = (key_col - 1) - (recur_r * self._Nb) 

return result + \ 

self.expand_key_poly(row, recur_j, recur_r) 

 

def apply_poly(self, state, poly_constr, algorithm='encrypt', keys=None, 

poly_constr_attr=None): 

r""" 

Returns a state matrix where ``poly_method`` is applied to each entry. 

 

INPUT: 

 

- ``state`` -- The state matrix over `\GF{2^8}` to which 

``poly_method`` is applied to. 

 

- ``poly_constr`` -- The ``Round_Component_Poly_Constr`` object to 

build polynomials during evaluation. 

 

- ``algorithm`` -- (default: "encrypt") Passed directly to 

``rcpc`` to select encryption or decryption. The 

encryption flag is "encrypt" and the decrypt flag is "decrypt". 

 

- ``keys`` -- (default: None) An array of `N_r` subkey matrices to 

replace any key variables in any polynomials returned by 

``poly_method``. Must be identical to the format returned by 

``expand_key``. If any polynomials have key variables and ``keys`` 

is not supplied, the key variables will remain as-is. 

 

- ``poly_constr_attr`` -- (default:None) A dictionary of keyword 

attributes to pass to ``rcpc`` when it is called. 

 

OUTPUT: 

 

- A state matrix in `\GF{2^8}` whose `i,j` th entry equals the 

polynomial ``poly_constr(i, j, algorithm, **poly_constr_attr)`` 

evaluated by setting its variables equal to the corresponding 

entries of ``state``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: state = rgf._hex_to_GF('3b59cb73fcd90ee05774222dc067fb68') 

sage: result = rgf.apply_poly(state, rgf.shift_rows_poly_constr()) 

sage: rgf._GF_to_hex(result) 

'3bd92268fc74fb735767cbe0c0590e2d' 

 

Calling ``apply_poly`` with the ``Round_Component_Poly_Constr`` object 

of a round component (e.g. ``sub_bytes_poly``) is identical to 

calling that round component function itself. :: 

 

sage: state = rgf._hex_to_GF('4915598f55e5d7a0daca94fa1f0a63f7') 

sage: apply_poly_result = rgf.apply_poly(state, 

....: rgf.sub_bytes_poly_constr()) 

sage: direct_result = rgf.sub_bytes(state) 

sage: direct_result == apply_poly_result 

True 

 

If the ``Round_Component_Poly_Constr`` object's ``__call__`` method 

returns a polynomial with state variables as well as key variables, we 

can supply a list of `N_r` round keys ``keys`` whose elements are 

evaluated as the key variables. If this is not provided, the key 

variables will remain as is.:: 

 

sage: state = rgf._hex_to_GF('14f9701ae35fe28c440adf4d4ea9c026') 

sage: key = rgf._hex_to_GF('54d990a16ba09ab596bbf40ea111702f') 

sage: keys = rgf.expand_key(key) 

sage: result = rgf.apply_poly(state, 

....: rgf.add_round_key_poly_constr(), keys=keys) 

sage: result == rgf.add_round_key(state, key) 

True 

<BLANKLINE> 

sage: rgf.apply_poly(state, rgf.add_round_key_poly_constr())[0,0] 

k000 + (x^4 + x^2) 

 

We can change the value of the keywords of ``poly_constr`` 's 

``__call__`` method when ``apply_poly`` calls it by passing in a 

dictionary ``poly_constr_attr`` mapping keywords to their values. :: 

 

sage: rgf.apply_poly(rgf.state_vrs, 

....: rgf.add_round_key_poly_constr(), 

....: poly_constr_attr={'round' : 5}) 

[a00 + k500 a01 + k501 a02 + k502 a03 + k503] 

[a10 + k510 a11 + k511 a12 + k512 a13 + k513] 

[a20 + k520 a21 + k521 a22 + k522 a23 + k523] 

[a30 + k530 a31 + k531 a32 + k532 a33 + k533] 

""" 

self._check_valid_PRmatrix(state, 'state') 

if not isinstance(poly_constr, RijndaelGF.Round_Component_Poly_Constr): 

msg = "keyword 'poly_constr' must be a Round_Component_Poly_Constr" 

raise TypeError(msg) 

if keys is not None and (not isinstance(keys, list) or \ 

len(keys) != self._Nr + 1 or \ 

not all([isinstance(k, Matrix) for k in keys]) or \ 

not all([k.dimensions() == (4, self._Nb) for k in keys]) or \ 

not all([k.base_ring().is_finite() and k.base_ring().is_field() 

and k.base_ring().order() == 256 for k in keys]) ): 

msg = ("keys must be a length {0} array of 4 by {1} matrices" 

" over {2}") 

raise TypeError(msg.format(self._Nr, self._Nb, self._F)) 

 

output = [] 

if keys is not None: 

key_list = [el for inner in keys for el in inner.list()] 

for i in range(4): 

for j in range(self._Nb): 

# this is to combat a major performance issue caused by 

# subbytes' inversion transformation. 

if poly_constr == self.sub_bytes_poly_constr() and \ 

algorithm == 'decrypt': 

p = poly_constr(i, j, algorithm, no_inversion=True) 

p = p(state.list()) ** 254 

else: 

if poly_constr_attr is None: 

p = poly_constr(i, j, algorithm) 

else: 

p = poly_constr(i, j, algorithm, **poly_constr_attr) 

# If there are key variables in the polynomial 

if len(p.args()) > 4 * self._Nb: 

if keys is not None: 

p = p(state.list() + key_list) 

else: 

p = p(state.list() + self.subkey_vrs_list) 

else: 

p = p(state.list()) 

output.append(p) 

return matrix(4, 4, output) 

 

def compose(self, f, g, algorithm='encrypt', f_attr=None, g_attr=None): 

r""" 

Return a ``Round_Component_Poly_Constr`` object corresponding to 

`g \circ f` or the polynomial output of this object's ``__call__`` 

method. 

 

INPUT: 

 

- ``f`` -- A ``Round_Component_Poly_Constr`` object corresponding to 

a round component function `f`. 

 

- ``g`` -- A ``Round_Component_Poly_Constr`` object corresponding to 

a round component function `g` or a polynomial output of this 

object's ``__call__`` method. 

 

- ``algorithm`` -- (default: "encrypt") Whether ``f`` and ``g`` 

should use their encryption transformations or their decryption 

transformations. Does nothing if ``g`` is a 

``Round_Component_Poly_Constr`` object. The encryption flag is 

"encrypt" and the decryption flag is "decrypt". 

 

- ``f_attr`` -- (default: None) A dictionary of keyword attributes to 

pass to ``f`` when it is called. 

 

- ``g_attr`` -- (default: None) A dictionary of keyword attributes to 

pass to ``g`` when it is called. Does nothing if ``g`` is a 

polynomial. 

 

OUTPUT: 

 

- If ``g`` is a ``Round_Component_Poly_Constr`` object corresponding 

to a round component function `g`, then ``compose`` returns a 

``Round_Component_Poly_Constr`` corresponding to the round 

component function `g \circ f`, where `f` is the round component 

function corresponding to the first argument ``f``. On the other 

hand, if ``g`` `= g(A)_{i,j}` for a round component function `g`, 

then ``compose`` returns `g(f(A))_{i,j}`, where `A` is an 

arbitrary input state matrix. 

 

EXAMPLES 

 

This function allows us to determine the polynomial representations 

of entries across multiple round functions. For example, if we 

wanted a polynomial representing the ``1,3`` entry of a matrix after 

we first apply ShiftRows and then MixColumns to that matrix, we do:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: mcp = rgf.mix_columns_poly_constr()(1, 3); mcp 

a03 + (x)*a13 + (x + 1)*a23 + a33 

sage: result = rgf.compose(rgf.shift_rows_poly_constr(), mcp) 

sage: result 

a03 + (x)*a10 + (x + 1)*a21 + a32 

 

We can test the correctness of this:: 

 

sage: state = rgf._hex_to_GF('fa636a2825b339c940668a3157244d17') 

sage: new_state = rgf.shift_rows(state) 

sage: new_state = rgf.mix_columns(new_state) 

sage: result(state.list()) == new_state[1,3] 

True 

 

We can also use ``compose`` to build a new 

``Round_Component_Poly_Constr`` object corresponding to the composition 

of multiple round functions as such:: 

 

sage: fn = rgf.compose(rgf.shift_rows_poly_constr(), 

....: rgf.mix_columns_poly_constr()) 

sage: fn(1, 3) 

a03 + (x)*a10 + (x + 1)*a21 + a32 

 

If we use ``compose`` to make a new ``Round_Component_Poly_Constr`` 

object, we can use that object as input to ``apply_poly`` and 

``compose``:: 

 

sage: state = rgf._hex_to_GF('36400926f9336d2d9fb59d23c42c3950') 

sage: result = rgf.apply_poly(state, fn) 

sage: rgf._GF_to_hex(result) 

'f4bcd45432e554d075f1d6c51dd03b3c' 

<BLANKLINE> 

sage: new_state = rgf.shift_rows(state) 

sage: new_state = rgf.mix_columns(new_state) 

sage: result == new_state 

True 

 

:: 

 

sage: fn2 = rgf.compose(rgf.sub_bytes_poly_constr(), fn) 

 

If the second argument is a polynomial, then the value of ``algorithm`` 

is passed directly to the first argument `f` during evaluation. 

However, if the second argument is a ``Round_Component_Poly_Constr`` 

object, changing ``algorithm`` does nothing since the returned object 

has its own ``algorithm='encrypt'`` keyword. :: 

 

sage: f = rgf.compose(rgf.sub_bytes_poly_constr(), 

....: rgf.mix_columns_poly_constr(), algorithm='decrypt') 

sage: g = rgf.compose(rgf.sub_bytes_poly_constr(), 

....: rgf.mix_columns_poly_constr()) 

sage: all([f(i,j) == g(i,j) for i in range(4) for j in range(4)]) 

True 

 

We can change the keyword attributes of the ``__call__`` methods of 

``f`` and ``g`` by passing dictionaries ``f_attr`` and ``g_attr`` to 

``compose``. :: 

 

sage: fn = rgf.compose(rgf.add_round_key_poly_constr(), 

....: rgf.add_round_key_poly_constr(), 

....: f_attr={'round' : 4}, g_attr={'round' : 7}) 

sage: fn(1, 2) 

a12 + k412 + k712 

""" 

if not isinstance(f, RijndaelGF.Round_Component_Poly_Constr): 

msg = "keyword 'f' must be a Round_Component_Poly_Constr" 

raise TypeError(msg) 

from sage.rings.polynomial.multi_polynomial import is_MPolynomial 

if not isinstance(g, RijndaelGF.Round_Component_Poly_Constr) and \ 

not is_MPolynomial(g): 

msg = ("keyword 'g' must be a Round_Component_Poly_Constr or a " 

"polynomial over {0}") 

raise TypeError(msg.format(self._F)) 

if f_attr is not None and not isinstance(f_attr, dict): 

raise TypeError("f_attr must be a dictionary of keywords for f") 

if g_attr is not None and not isinstance(g_attr, dict): 

raise TypeError("g_attr must be a dictionary of keywords for g") 

 

if g in self._all_PR: 

if isinstance(f_attr, dict): 

f_vals = [f(i, j, algorithm, **f_attr) 

for i in range(4) for j in range(self._Nb)] 

else: 

f_vals = [f(i, j, algorithm) 

for i in range(4) for j in range(self._Nb)] 

if g in self._state_PR: 

return g(f_vals) 

else: 

return g(f_vals + self.subkey_vrs_list) 

else: 

if isinstance(g_attr, dict): 

lm = lambda i, j, alg='encrypt' : \ 

self.compose(f, g(i, j, alg, **g_attr), alg, f_attr, g_attr) 

else: 

lm = lambda i, j, alg='encrypt' : \ 

self.compose(f, g(i, j, alg), alg, f_attr, g_attr) 

return RijndaelGF.Round_Component_Poly_Constr(lm, self) 

 

def add_round_key_poly_constr(self): 

r""" 

Return the ``Round_Component_Poly_Constr`` object corresponding to 

AddRoundKey. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: ark_pc = rgf.add_round_key_poly_constr() 

sage: ark_pc 

A polynomial constructor for the function 'Add Round Key' of Rijndael-GF block cipher with block length 4, key length 4, and 10 rounds. 

sage: ark_pc(0, 1) 

a01 + k001 

 

When invoking the returned object's ``__call__`` method, changing the 

value of ``algorithm='encrypt'`` does nothing, since the AddRoundKey 

round component function is its own inverse. :: 

 

sage: with_encrypt = ark_pc(1, 1, algorithm='encrypt') 

sage: with_decrypt = ark_pc(1, 1, algorithm='decrypt') 

sage: with_encrypt == with_decrypt 

True 

 

When invoking the returned object's ``__call__`` method, one can change 

the round subkey used in the returned polynomial by changing the 

``round=0`` keyword. :: 

 

sage: ark_pc(2, 1, round=7) 

a21 + k721 

 

When passing the returned object to methods such as ``apply_poly`` and 

``compose``, we can make these methods use a non-default value for 

``round=0`` by passing in a dictionary mapping ``round`` to a different 

value. :: 

 

sage: rgf.apply_poly(rgf.state_vrs, ark_pc, 

....: poly_constr_attr={'round' : 6}) 

[a00 + k600 a01 + k601 a02 + k602 a03 + k603] 

[a10 + k610 a11 + k611 a12 + k612 a13 + k613] 

[a20 + k620 a21 + k621 a22 + k622 a23 + k623] 

[a30 + k630 a31 + k631 a32 + k632 a33 + k633] 

 

:: 

 

sage: rcpc = rgf.compose(ark_pc, ark_pc, 

....: f_attr={'round' : 3}, g_attr={'round' : 5}) 

sage: rcpc(3, 1) 

a31 + k331 + k531 

""" 

return self._add_round_key_rcpc 

 

def _add_round_key_pc(self, row, col, algorithm='encrypt', round=0): 

r""" 

Returns a polynomial representing an element of a round-key addition. 

 

INPUT: 

 

- ``row`` -- The row number of the entry represented by this method's 

output. 

 

- ``col`` -- The column number of the entry represented by this 

method's output. 

 

- ``algorithm`` -- (default: "encrypt") Whether to return the 

polynomial as an encryption or as a decryption. The encryption flag 

is "encrypt" and the decryption flag is "decrypt". 

 

- ``round`` -- (default: 0) The round number of the entry represented 

by this method's output. 

 

OUTPUT: 

 

- A polynomial representing the ``row,col`` th entry of a state matrix 

after a round-key addition in terms of entries of the input state 

matrix and entries of the ``round`` th round key. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: rgf._add_round_key_pc(1, 2, round=7) 

a12 + k712 

 

As expected, since the encryption and decryption transformations are 

identical, changing ``algorithm`` has no effect. 

 

sage: with_encrypt = rgf._add_round_key_pc(3, 2, 

....: 'encrypt') 

sage: with_decrypt = rgf._add_round_key_pc(3, 2, 

....: 'decrypt') 

sage: with_encrypt == with_decrypt 

True 

""" 

if round not in range(self._Nr): 

msg = "keyword 'round' must be between 0 and {0}" 

raise ValueError(msg.format(self._Nr)) 

state_var = self.state_vrs[row, col] 

key_var = self.subkey_vrs[round][row, col] 

return state_var + key_var 

 

def add_round_key(self, state, round_key): 

r""" 

Returns the round-key addition of matrices ``state`` and ``round_key``. 

 

INPUT: 

 

- ``state`` -- The state matrix to have ``round_key`` added to. 

 

- ``round_key`` -- The round key to add to ``state``. 

 

OUTPUT: 

 

- A state matrix which is the round key addition of ``state`` and 

``round_key``. This transformation is simply the entrywise addition 

of these two matrices. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: state = rgf._hex_to_GF('36339d50f9b539269f2c092dc4406d23') 

sage: key = rgf._hex_to_GF('7CC78D0E22754E667E24573F454A6531') 

sage: key_schedule = rgf.expand_key(key) 

sage: result = rgf.add_round_key(state, key_schedule[0]) 

sage: rgf._GF_to_hex(result) 

'4af4105edbc07740e1085e12810a0812' 

""" 

self._check_valid_PRmatrix(state, 'state') 

self._check_valid_PRmatrix(round_key, 'round_key') 

# We don't use apply_poly here since that would require giving this 

# method an extra argument of a round number 

return state + round_key 

 

def sub_bytes_poly_constr(self): 

r""" 

Return the ``Round_Component_Poly_Constr`` object corresponding to 

SubBytes. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: sb_pc = rgf.sub_bytes_poly_constr() 

sage: sb_pc 

A polynomial constructor for the function 'SubBytes' of Rijndael-GF block cipher with block length 4, key length 4, and 10 rounds. 

sage: sb_pc(2, 3) 

(x^2 + 1)*a23^254 + 

(x^3 + 1)*a23^253 + 

(x^7 + x^6 + x^5 + x^4 + x^3 + 1)*a23^251 + 

(x^5 + x^2 + 1)*a23^247 + 

(x^7 + x^6 + x^5 + x^4 + x^2)*a23^239 + 

a23^223 + 

(x^7 + x^5 + x^4 + x^2 + 1)*a23^191 + 

(x^7 + x^3 + x^2 + x + 1)*a23^127 + 

(x^6 + x^5 + x + 1) 

 

The returned object's ``__call__`` method has an additional keyword 

of ``no_inversion=False``, which causes the returned polynomial to 

represent only the affine transformation step of SubBytes. :: 

 

sage: sb_pc(1, 0, no_inversion=True) 

(x^7 + x^3 + x^2 + x + 1)*a10^128 + 

(x^7 + x^5 + x^4 + x^2 + 1)*a10^64 + 

a10^32 + 

(x^7 + x^6 + x^5 + x^4 + x^2)*a10^16 + 

(x^5 + x^2 + 1)*a10^8 + 

(x^7 + x^6 + x^5 + x^4 + x^3 + 1)*a10^4 + 

(x^3 + 1)*a10^2 + 

(x^2 + 1)*a10 + 

(x^6 + x^5 + x + 1) 

 

We can build a polynomial representing the inverse transformation 

by setting the keyword ``algorithm='decrypt'``. However, the order of 

the affine transformation and the inversion step in SubBytes means that 

this polynomial has thousands of terms and is very slow to compute. 

Hence, if one wishes to build the decryption polynomial with the 

intention of evaluating that polynomial for a particular input, it is 

strongly recommended to first call 

``sb_pc(i, j, algorithm='decrypt', no_inversion=True)`` to build a 

polynomial representing only the inverse affine transformation, 

evaluate this polynomial for your intended input, then finally 

calculate the inverse of the result. :: 

 

sage: poly = sb_pc(1, 2, algorithm='decrypt', no_inversion=True) 

sage: state = rgf._hex_to_GF('39daee38f4f1a82aaf432410c36d45b9') 

sage: result = poly(state.list()) 

sage: rgf._GF_to_hex(result * -1) 

'49' 

 

When passing the returned object to ``apply_poly`` and ``compose``, we 

can make those methods change the keyword ``no_inversion`` of this 

object's ``__call__`` method by passing the dictionary 

``{'no_inversion' : True}`` to them. :: 

 

sage: result = rgf.apply_poly(state, sb_pc, 

....: poly_constr_attr={'no_inversion' : True}) 

sage: rgf._GF_to_hex(result) 

'961c72894526f746aa85fc920adcc719' 

 

:: 

 

sage: rcpc = rgf.compose(sb_pc, rgf.shift_rows_poly_constr(), 

....: f_attr={'no_inversion' : True}) 

 

Note that if we set ``algorithm='decrypt'`` for ``apply_poly``, it 

will perform the necessary performance enhancement described above 

automatically. The structure of ``compose``, however, unfortunately 

does not allow this enhancement to be employed. 

""" 

return self._sub_bytes_rcpc 

 

def _sub_bytes_pc(self, row, col, algorithm='encrypt', no_inversion=False): 

r""" 

Returns a polynomial representing `SubBytes(A)_{\textit{row, col}}`. 

 

INPUT: 

 

- ``row`` -- The row number of the entry represented by this method's 

output. 

 

- ``col`` -- The column number of the entry represented by this 

method's output. 

 

- ``algorithm`` -- (default: "encrypt") Whether to return the 

polynomial as an encryption or as a decryption. The encryption flag 

is "encrypt" and the decryption flag is "decrypt". 

 

- ``no_inversion`` -- (default: ``False``) Don't perform the inversion 

step, only perform the affine transformation. Primarily intended 

to increase performance during decryption, as is shown in the 

below example. 

 

OUTPUT: 

 

- A polynomial representing the ``row,col`` th entry of a state matrix 

after the SubBytes method has been applied to it. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: rgf._sub_bytes_pc(2, 3) 

(x^2 + 1)*a23^254 + (x^3 + 1)*a23^253 + (x^7 + x^6 + x^5 + x^4 + x^3 + 1)*a23^251 + (x^5 + x^2 + 1)*a23^247 + (x^7 + x^6 + x^5 + x^4 + x^2)*a23^239 + a23^223 + (x^7 + x^5 + x^4 + x^2 + 1)*a23^191 + (x^7 + x^3 + x^2 + x + 1)*a23^127 + (x^6 + x^5 + x + 1) 

 

We can use this polynomial to calculate individual entries of the 

output matrix for any given state as such:: 

 

sage: state = rgf._hex_to_GF('6385b79ffc538df997be478e7547d691') 

sage: poly = rgf._sub_bytes_pc(2, 3) 

sage: poly(state.list()) 

x^7 + x^6 + x^5 + x^4 + x^2 + x 

 

We can set ``no_inversion`` to ``True`` to get a polynomial 

representation of solely the affine transformation. :: 

 

sage: rgf._sub_bytes_pc(0, 2, no_inversion=True) 

(x^7 + x^3 + x^2 + x + 1)*a02^128 + (x^7 + x^5 + x^4 + x^2 + 1)*a02^64 + a02^32 + (x^7 + x^6 + x^5 + x^4 + x^2)*a02^16 + (x^5 + x^2 + 1)*a02^8 + (x^7 + x^6 + x^5 + x^4 + x^3 + 1)*a02^4 + (x^3 + 1)*a02^2 + (x^2 + 1)*a02 + (x^6 + x^5 + x + 1) 

 

When generating a decryption polynomial, calculating the inverse of 

the polynomial representing the affine transformation can be a very 

slow process. In order to speed up decryption when applying 

``sub_bytes_poly`` to a state matrix, it is recommended to calculate 

the decryption polynomial with ``no_inversion=True``, evaluate the 

arguments, then perform the inversion after this result has been 

calculated. :: 

 

sage: poly = rgf._sub_bytes_pc(0, 0, 

....: algorithm='decrypt', no_inversion=True) 

sage: state = rgf._hex_to_GF('b415f8016858552e4bb6124c5f998a4c') 

sage: poly(state.list()) ^ -1 

x^7 + x^6 + x^2 + x 

""" 

if algorithm == 'encrypt': 

var = self.state_vrs[row, col] 

coeffs = self._sb_E_coeffs 

if no_inversion: 

return sum([coeffs[i] * (var**(2**i)) 

for i in range(8)]) + self._F("x^6 + x^5 + x + 1") 

else: 

return sum([coeffs[i] * (var**(255 - 2**i)) 

for i in range(8)]) + self._F("x^6 + x^5 + x + 1") 

elif algorithm == 'decrypt': 

var = self.state_vrs[row, col] 

coeffs = self._sb_D_coeffs 

result = (sum([coeffs[i] * var**(2**i) for i in range(8)]) + \ 

self._F("x^2 + 1")) 

if no_inversion: 

return result 

else: 

return result ** 254 

else: 

raise ValueError(("keyword 'algorithm' must be either 'encrypt' " 

"or 'decrypt'")) 

 

def _srd(self, el, algorithm='encrypt'): 

r""" 

Returns the application of SubBytes (`S_{RD}`) to ``el``. 

 

INPUT: 

 

- ``el`` -- An element of `\GF{2^8}`. 

 

- ``algorithm`` -- (default: "encrypt") Whether to perform the 

encryption transformation or the decryption transformation. 

The encryption flag is "encrypt" and the decryption flag is 

"decrypt". 

 

OUTPUT: 

 

- The result of the application of the non-linear transformation 

SubBytes to ``el``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: el = rgf._hex_to_GF('2A', matrix=False)[0] 

sage: rgf._srd(el) 

x^7 + x^6 + x^5 + x^2 + 1 

""" 

if algorithm == 'encrypt': 

p = self._sub_bytes_rcpc(0, 0, algorithm) 

state = [el] + [self._F.zero()]*((4 * self._Nb)-1) 

return p(state) 

elif algorithm == 'decrypt': 

p = self._sub_bytes_rcpc(0, 0, algorithm, no_inversion=True) 

state = [el] + [self._F.zero()]*((4 * self._Nb)-1) 

return p(state) ** 254 

else: 

raise ValueError(("keyword 'algorithm' must be either 'encrypt' " 

"or 'decrypt'")) 

 

def sub_bytes(self, state, algorithm='encrypt'): 

r""" 

Returns the application of SubBytes to the state matrix ``state``. 

 

INPUT: 

 

- ``state`` -- The state matrix to apply SubBytes to. 

 

- ``algorithm`` -- (default: "encrypt") Whether to apply the 

encryption step of SubBytes or its decryption inverse. The encryption 

flag is "encrypt" and the decryption flag is "decrypt". 

 

OUTPUT: 

 

- The state matrix over `\GF{2^8}` where SubBytes has been applied 

to every entry of ``state``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: state = rgf._hex_to_GF('d1c4941f7955f40fb46f6c0ad68730ad') 

sage: result = rgf.sub_bytes(state) 

sage: rgf._GF_to_hex(result) 

'3e1c22c0b6fcbf768da85067f6170495' 

sage: decryption = rgf.sub_bytes(result, algorithm='decrypt') 

sage: decryption == state 

True 

""" 

self._check_valid_PRmatrix(state, 'state') 

return self.apply_poly(state, self._sub_bytes_rcpc, algorithm) 

 

def mix_columns_poly_constr(self): 

r""" 

Return a ``Round_Component_Poly_Constr`` object corresponding to 

MixColumns. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: mc_pc = rgf.mix_columns_poly_constr() 

sage: mc_pc 

A polynomial constructor for the function 'Mix Columns' of Rijndael-GF block cipher with block length 4, key length 4, and 10 rounds. 

sage: mc_pc(1, 2) 

a02 + (x)*a12 + (x + 1)*a22 + a32 

sage: mc_pc(1, 0, algorithm='decrypt') 

(x^3 + 1)*a00 + (x^3 + x^2 + x)*a10 + (x^3 + x + 1)*a20 + (x^3 + x^2 + 1)*a30 

 

The returned object's ``__call__`` method has no additional keywords, 

unlike ``sub_bytes_poly_constr()`` and ``add_round_key_poly_constr()``. 

""" 

return self._mix_columns_rcpc 

 

def _mix_columns_pc(self, row, col, algorithm='encrypt'): 

r""" 

Returns a polynomial representing `MixColumns(A)_{\textit{row, col}}`. 

 

INPUT: 

 

- ``row`` -- The row number of the entry represented by this method's 

output. 

 

- ``col`` -- The column number of the entry represented by this 

method's output. 

 

- ``algorithm`` -- (default: "encrypt") Whether to perform the 

encryption transformation or the decryption transformation. The 

encryption flag is "encrypt" and the decryption flag is "decrypt". 

 

OUTPUT: 

 

- A polynomial in terms of entries of the input state matrix which 

represents the ``row,col`` th entry of the output matrix after 

MixColumns has been applied to it. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: rgf._mix_columns_pc(3, 1) 

(x + 1)*a01 + a11 + a21 + (x)*a31 

 

We can use this to calculate individual entries of a state matrix after 

the decryption version of MixColumns has been applied to it as such:: 

 

sage: poly = rgf._mix_columns_pc(2, 2, algorithm='decrypt') 

sage: state = rgf._hex_to_GF('a761ca9b97be8b45d8ad1a611fc97369') 

sage: result = poly(state.list()) 

sage: rgf._GF_to_hex(result) 

'b7' 

sage: output = rgf.mix_columns(state, algorithm='decrypt') 

sage: output[2,2] == result 

True 

""" 

if algorithm == 'encrypt': 

coeffs = self._mixcols_E 

elif algorithm == 'decrypt': 

coeffs = self._mixcols_D 

else: 

raise ValueError(("keyword 'algorithm' must be either 'encrypt' " 

"or 'decrypt'")) 

return sum([coeffs[row,k] * self.state_vrs[k,col] for k in range(4)]) 

 

def mix_columns(self, state, algorithm='encrypt'): 

r""" 

Returns the application of MixColumns to the state matrix ``state``. 

 

INPUT: 

 

- ``state`` -- The state matrix to apply MixColumns to. 

 

- ``algorithm`` -- (default: "encrypt") Whether to perform the 

encryption version of MixColumns, or its decryption inverse. The 

encryption flag is "encrypt" and the decryption flag is "decrypt". 

 

OUTPUT: 

 

- The state matrix over `\GF{2^8}` which is the result of applying 

MixColumns to ``state``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: state = rgf._hex_to_GF('cd54c7283864c0c55d4c727e90c9a465') 

sage: result = rgf.mix_columns(state) 

sage: rgf._GF_to_hex(result) 

'921f748fd96e937d622d7725ba8ba50c' 

sage: decryption = rgf.mix_columns(result, algorithm='decrypt') 

sage: decryption == state 

True 

""" 

self._check_valid_PRmatrix(state, 'state') 

return self.apply_poly(state, self._mix_columns_rcpc, algorithm) 

 

def shift_rows_poly_constr(self): 

r""" 

Return a ``Round_Component_Poly_Constr`` object corresponding to 

ShiftRows. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: sr_pc = rgf.shift_rows_poly_constr() 

sage: sr_pc(3, 0) 

a33 

sage: sr_pc(2, 1, algorithm='decrypt') 

a23 

 

The returned object's ``__call__`` method has no additional keywords, 

unlike ``sub_bytes_poly_constr()`` and ``add_round_key_poly_constr``. 

""" 

return self._shift_rows_rcpc 

 

def _shift_rows_pc(self, row, col, algorithm='encrypt'): 

r""" 

Returns a polynomial representing `ShiftRows(A)_{\textit{row,col}}`. 

 

INPUT: 

 

- ``row`` -- The row number of the entry represented by this method's 

output. 

 

- ``col`` -- The column number of the entry represented by this 

method's output. 

 

- ``algorithm`` -- (default: "encrypt") Whether to perform ShiftRows' 

encryption step or its decryption inverse. The encryption flag is 

"encrypt" and the decryption flag is "decrypt". 

 

OUTPUT: 

 

- A polynomial in terms of entries of the input state matrix which 

represents the ``row,col`` th entry of the output matrix after 

ShiftRows has been applied to it. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: rgf._shift_rows_pc(2, 3) 

a21 

 

We can use this to calculate individual entries of a state matrix 

after the decryption version of ShiftRows has been applied to it as 

such:: 

 

sage: poly = rgf._shift_rows_pc(2, 3, algorithm='decrypt') 

sage: state = rgf._hex_to_GF('78c4f708318d3cd69655b701bfc093cf') 

sage: result = poly(state.list()) 

sage: rgf._GF_to_hex(result) 

'3c' 

sage: output = rgf.shift_rows(state, algorithm='decrypt') 

sage: output[2,3] == result 

True 

""" 

if algorithm == 'encrypt': 

offs = self._shiftrows_offsets_E 

elif algorithm == 'decrypt': 

offs = self._shiftrows_offsets_D 

else: 

raise ValueError(("keyword 'algorithm' must be either 'encrypt' " 

"or 'decrypt'")) 

return self.state_vrs[row, (col + offs[4 - self._Nb][row]) % 4] 

 

def shift_rows(self, state, algorithm='encrypt'): 

r""" 

Returns the application of ShiftRows to the state matrix ``state``. 

 

INPUT: 

 

- ``state`` -- A state matrix over `\GF{2^8}` to which ShiftRows is 

applied to. 

 

- ``algorithm`` -- (default: "encrypt") Whether to perform the 

encryption version of ShiftRows or its decryption inverse. The 

encryption flag is "encrypt" and the decryption flag is "decrypt". 

 

OUTPUT: 

 

- A state matrix over `\GF{2^8}` which is the application of ShiftRows 

to ``state``. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: state = rgf._hex_to_GF('adcb0f257e9c63e0bc557e951c15ef01') 

sage: result = rgf.shift_rows(state) 

sage: rgf._GF_to_hex(result) 

'ad9c7e017e55ef25bc150fe01ccb6395' 

sage: decryption = rgf.shift_rows(result, algorithm='decrypt') 

sage: decryption == state 

True 

""" 

self._check_valid_PRmatrix(state, 'state') 

return self.apply_poly(state, self._shift_rows_rcpc, algorithm) 

 

class Round_Component_Poly_Constr(SageObject): 

 

def __init__(self, polynomial_constr, rgf, round_component_name=None): 

r""" 

An object which constructs polynomials representing round 

component functions of a RijndaelGF object. 

 

INPUT: 

 

- ``polynomial_constr`` -- A function which takes an index 

``row,col`` and returns a polynomial representing the ``row,col`` 

th entry of a matrix after a specific round component function 

has been applied to it. This polynomial must be in terms of 

entries of the input matrix to that round component function and 

of entries of various subkeys. ``polynomial_constr`` must have 

arguments of the form ``polynomial_constr(row, col, 

algorithm='encrypt', **kwargs)`` and must be able to be called 

as ``polynomial_constr(row, col)``. 

 

- ``rgf`` -- The RijndaelGF object whose state entries are 

represented by polynomials returned from ``polynomial_constr``. 

 

- ``round_component_name`` -- The name of the round component 

function this object corresponds to as a string. Used solely 

for display purposes. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import \ 

....: RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: rcpc = RijndaelGF.Round_Component_Poly_Constr( 

....: rgf._shift_rows_pc, rgf, "Shift Rows") 

sage: rcpc 

A polynomial constructor for the function 'Shift Rows' of Rijndael-GF block cipher with block length 4, key length 4, and 10 rounds. 

 

If `\phi` is the round component function to which this object 

corresponds to, then ``__call__(i,j)`` `= \phi(A)_{i,j}`, where 

`A` is an arbitrary input matrix. Note that the polynomial returned 

by ``__call__(i,j)`` will be in terms of the entries of `A`. :: 

 

sage: rcpc = RijndaelGF.Round_Component_Poly_Constr( 

....: rgf._mix_columns_pc, rgf, "Mix Columns") 

sage: poly = rcpc(1, 2); poly 

a02 + (x)*a12 + (x + 1)*a22 + a32 

sage: state = rgf._hex_to_GF('d1876c0f79c4300ab45594add66ff41f') 

sage: result = rgf.mix_columns(state) 

sage: result[1,2] == poly(state.list()) 

True 

 

Invoking this objects ``__call__`` method passes its arguments 

directly to ``polynomial_constr`` and returns the result. In a 

sense, ``Round_Component_Poly_Constr`` acts as a wrapper for 

the ``polynomial_constr`` method and helps ensure that each 

``Round_Component_Poly_Constr`` object will act similarly. :: 

 

sage: all([rgf._mix_columns_pc(i, j) == rcpc(i, j) 

....: for i in range(4) for j in range(4)]) 

True 

 

Since all keyword arguments of ``polynomial_constr`` must have a 

default value except for ``row`` and ``col``, we can always call 

a ``Round_Component_Poly_Constr`` object by ``__call__(row, col)``. 

Because of this, methods such as ``apply_poly`` and ``compose`` 

will only call ``__call__(row, col)`` when passed a 

``Round_Component_Poly_Constr`` object. In order to change this 

object's behavior and force methods such as ``apply_poly`` to use 

non-default values for keywords we can pass dictionaries mapping 

keywords to non-default values as input to ``apply_poly`` and 

``compose``. :: 

 

sage: rgf.apply_poly(rgf.state_vrs, 

....: rgf.add_round_key_poly_constr(), 

....: poly_constr_attr={'round' : 9}) 

[a00 + k900 a01 + k901 a02 + k902 a03 + k903] 

[a10 + k910 a11 + k911 a12 + k912 a13 + k913] 

[a20 + k920 a21 + k921 a22 + k922 a23 + k923] 

[a30 + k930 a31 + k931 a32 + k932 a33 + k933] 

 

:: 

 

sage: fn = rgf.compose(rgf.add_round_key_poly_constr(), 

....: rgf.add_round_key_poly_constr(), 

....: f_attr={'round' : 3}, g_attr={'round' : 7}) 

sage: fn(2, 3) 

a23 + k323 + k723 

 

Because all ``Round_Component_Poly_Constr`` objects are callable 

as ``__call__(row, col, algorithm)``, ``__call__`` will check 

the validity of these three arguments automatically. Any other 

keywords, however, must be checked in ``polynomial_constr``. :: 

 

sage: def my_poly_constr(row, col, algorithm='encrypt'): 

....: return x * rgf._F.one() # example body with no checks 

....: 

sage: rcpc = RijndaelGF.Round_Component_Poly_Constr( 

....: my_poly_constr, rgf, "My Poly Constr") 

sage: rcpc(-1, 2) 

Traceback (most recent call last): 

... 

ValueError: keyword 'row' must be in range 0 - 3 

sage: rcpc(1, 2, algorithm=5) 

Traceback (most recent call last): 

... 

ValueError: keyword 'algorithm' must be either 'encrypt' or 'decrypt' 

""" 

from inspect import getargspec 

pc_args = getargspec(polynomial_constr) 

if pc_args[0][0] == 'self': 

# Check number of defaulted arguments 

if len(pc_args[3]) != len(pc_args[0]) - 3: 

msg = ("keyword 'polynomial_constr' must be callable as: " 

"polynomial_constr(row, col, algorithm='encrypt')") 

raise TypeError(msg) 

else: 

if len(pc_args[3]) != len(pc_args[0]) - 2: 

msg = ("keyword 'polynomial_constr' must be callable as: " 

"polynomial_constr(row, col, algorithm='encrypt')") 

raise TypeError(msg) 

self._polynomial_constr = polynomial_constr 

self._Nb = rgf.block_length() 

self._rgf_name = rgf.__repr__() 

if round_component_name is not None and \ 

not isinstance(round_component_name, str): 

msg = "round_component_name must be None or a string" 

raise TypeError(msg) 

self._rc_name = round_component_name 

 

def __call__(self, row, col, algorithm='encrypt', **kwargs): 

r""" 

Returns ``polynomial_constr(row, col, algorithm, **attr_dict)``. 

 

INPUT: 

 

- ``row`` -- The row number to pass to ``polynomial_constr``. 

 

- ``col`` -- The column number to pass to ``polynomial_constr``. 

 

- ``algorithm`` -- (default: 'encrypt') The algorithm keyword 

to pass to ``polynomial_constr``. 

 

- ``**kwargs`` -- Keyword arguments to pass to 

``polynomial_constr``. Keyword arguments will vary depending 

on ``polynomial_constr``. 

 

OUTPUT: 

 

- The output of ``polynomial_constr(row, col, algorithm, 

** attr_dict)``. This is required to be a polynomial over 

`\GF{2^8}`. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import \ 

....: RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: rcpc = RijndaelGF.Round_Component_Poly_Constr( 

....: rgf._shift_rows_pc, rgf, "Shift Rows") 

sage: rcpc(1, 2) 

a13 

sage: all([rcpc(i, j) == rgf._shift_rows_pc(i, j) 

....: for i in range(4) for j in range(4)]) 

True 

""" 

if row not in range(4): 

raise ValueError("keyword 'row' must be in range 0 - 3") 

if col not in range(self._Nb): 

msg = "keyword 'col' must be in range 0 - {0}" 

raise ValueError(msg.format(self._Nb-1)) 

if algorithm not in ['encrypt', 'decrypt']: 

msg = ("keyword 'algorithm' must be either 'encrypt' or " 

"'decrypt'") 

print(algorithm) 

raise ValueError(msg) 

return self._polynomial_constr(row, col, algorithm, **kwargs) 

 

def __repr__(self): 

r""" 

Returns a string representation of this object. 

 

EXAMPLES:: 

 

sage: from sage.crypto.mq.rijndael_gf import \ 

....: RijndaelGF 

sage: rgf = RijndaelGF(4, 4) 

sage: RijndaelGF.Round_Component_Poly_Constr( 

....: rgf._shift_rows_pc, rgf, "Shift Rows") 

A polynomial constructor for the function 'Shift Rows' of Rijndael-GF block cipher with block length 4, key length 4, and 10 rounds. 

sage: RijndaelGF.Round_Component_Poly_Constr( 

....: rgf._shift_rows_pc, rgf) 

A polynomial constructor of a round component of Rijndael-GF block cipher with block length 4, key length 4, and 10 rounds. 

""" 

if self._rc_name is None: 

msg = "A polynomial constructor of a round component of {0}" 

return msg.format(self._rgf_name) 

else: 

msg = "A polynomial constructor for the function '{0}' of {1}" 

return msg.format(self._rc_name, self._rgf_name)