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

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

r""" 

Classical Cryptosystems 

 

A convenient user interface to various classical ciphers. These include: 

 

- affine cipher; see :class:`AffineCryptosystem` 

- Hill or matrix cipher; see :class:`HillCryptosystem` 

- shift cipher; see :class:`ShiftCryptosystem` 

- substitution cipher; see :class:`SubstitutionCryptosystem` 

- transposition cipher; see :class:`TranspositionCryptosystem` 

- Vigenere cipher; see :class:`VigenereCryptosystem` 

 

These classical cryptosystems support alphabets such as: 

 

- the capital letters of the English alphabet; see 

:func:`AlphabeticStrings() <sage.monoids.string_monoid.AlphabeticStrings>` 

- the hexadecimal number system; see 

:func:`HexadecimalStrings() <sage.monoids.string_monoid.HexadecimalStrings>` 

- the binary number system; see 

:func:`BinaryStrings() <sage.monoids.string_monoid.BinaryStrings>` 

- the octal number system; see 

:func:`OctalStrings() <sage.monoids.string_monoid.OctalStrings>` 

- the radix-64 number system; see 

:func:`Radix64Strings() <sage.monoids.string_monoid.Radix64Strings>` 

 

AUTHORS: 

 

- David Kohel (2007): initial version with the Hill, substitution, 

transposition, and Vigenere cryptosystems. 

 

- Minh Van Nguyen (2009-08): shift cipher, affine cipher 

""" 

 

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

# Copyright (C) 2007 David Kohel <kohel@maths.usyd.edu.au> 

# 

# 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 

from __future__ import absolute_import 

from six.moves import range 

 

# TODO: check off this todo list: 

# - methods to cryptanalyze the Hill, substitution, transposition, and 

# Vigenere ciphers 

 

from sage.monoids.string_monoid import ( 

StringMonoid_class, 

AlphabeticStringMonoid) 

from sage.monoids.string_monoid_element import StringMonoidElement 

from sage.monoids.string_ops import strip_encoding 

from sage.groups.perm_gps.permgroup_named import SymmetricGroup 

from sage.groups.perm_gps.permgroup_element import PermutationGroupElement 

from sage.rings.integer import Integer 

from sage.rings.integer_ring import ZZ 

from sage.rings.finite_rings.integer_mod_ring import IntegerModRing 

from sage.arith.all import xgcd, gcd, inverse_mod 

from random import randint 

from sage.matrix.matrix_space import MatrixSpace 

 

from .cryptosystem import SymmetricKeyCryptosystem 

from .classical_cipher import ( 

AffineCipher, 

HillCipher, 

ShiftCipher, 

SubstitutionCipher, 

TranspositionCipher, 

VigenereCipher) 

 

class AffineCryptosystem(SymmetricKeyCryptosystem): 

r""" 

Create an affine cryptosystem. 

 

Let `A = \{ a_0, a_1, a_2, \dots, a_{n-1} \}` be a non-empty alphabet 

consisting of `n` unique elements. Define a mapping 

`f : A \longrightarrow \ZZ / n\ZZ` from the alphabet `A` to 

the set `\ZZ / n\ZZ` of integers modulo `n`, given by 

`f(a_i) = i`. Thus we can identify each element of the alphabet `A` 

with a unique integer `0 \leq i < n`. A key of the affine cipher is an 

ordered pair of integers `(a, b) \in \ZZ / n\ZZ \times \ZZ / n\ZZ` such 

that `\gcd(a, n) = 1`. Therefore the key space is 

`\ZZ / n\ZZ \times \ZZ / n\ZZ`. Since we assume that `A` does not have 

repeated elements, the mapping `f : A \longrightarrow \ZZ/ n\ZZ` is 

bijective. Encryption and decryption functions are both affine functions. 

Let `(a,b)` be a secret key, i.e. an element of the key space, and let 

`p` be a plaintext character and consequently `p \in \ZZ / n\ZZ`. Then 

the ciphertext character `c` corresponding to `p` is given by 

 

.. MATH:: 

 

c \equiv ap + b \pmod{n} 

 

Similarly, given a ciphertext character `c \in \ZZ / n\ZZ` and a secret 

key `(a,b)`, we can recover the corresponding plaintext character as 

follows: 

 

.. MATH:: 

 

p \equiv a^{-1} (c - b) \pmod{n} 

 

where `a^{-1}` is the inverse of `a` modulo `n`. Use the bijection 

`f : A \longrightarrow \ZZ / n\ZZ` to convert `c` and `p` back to 

elements of the alphabet `A`. Currently, only the following alphabet is 

supported for the affine cipher: 

 

- capital letters of the English alphabet as implemented in 

:func:`AlphabeticStrings() 

<sage.monoids.string_monoid.AlphabeticStrings>` 

 

EXAMPLES: 

 

Encryption and decryption over the capital letters of the English 

alphabet:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()); A 

Affine cryptosystem on Free alphabetic string monoid on A-Z 

sage: P = A.encoding("The affine cryptosystem generalizes the shift cipher.") 

sage: P 

THEAFFINECRYPTOSYSTEMGENERALIZESTHESHIFTCIPHER 

sage: a, b = (9, 13) 

sage: C = A.enciphering(a, b, P); C 

CYXNGGHAXFKVSCJTVTCXRPXAXKNIHEXTCYXTYHGCFHSYXK 

sage: A.deciphering(a, b, C) 

THEAFFINECRYPTOSYSTEMGENERALIZESTHESHIFTCIPHER 

sage: A.deciphering(a, b, C) == P 

True 

 

We can also use functional notation to work through the previous 

example:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()); A 

Affine cryptosystem on Free alphabetic string monoid on A-Z 

sage: P = A.encoding("The affine cryptosystem generalizes the shift cipher.") 

sage: P 

THEAFFINECRYPTOSYSTEMGENERALIZESTHESHIFTCIPHER 

sage: a, b = (9, 13) 

sage: E = A(a, b); E 

Affine cipher on Free alphabetic string monoid on A-Z 

sage: C = E(P); C 

CYXNGGHAXFKVSCJTVTCXRPXAXKNIHEXTCYXTYHGCFHSYXK 

sage: aInv, bInv = A.inverse_key(a, b) 

sage: D = A(aInv, bInv); D 

Affine cipher on Free alphabetic string monoid on A-Z 

sage: D(C) 

THEAFFINECRYPTOSYSTEMGENERALIZESTHESHIFTCIPHER 

sage: D(C) == P 

True 

sage: D(C) == P == D(E(P)) 

True 

 

Encrypting the ciphertext with the inverse key also produces the 

plaintext:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: P = A.encoding("Encrypt with inverse key.") 

sage: a, b = (11, 8) 

sage: C = A.enciphering(a, b, P) 

sage: P; C 

ENCRYPTWITHINVERSEKEY 

AVENMRJQSJHSVFANYAOAM 

sage: aInv, bInv = A.inverse_key(a, b) 

sage: A.enciphering(aInv, bInv, C) 

ENCRYPTWITHINVERSEKEY 

sage: A.enciphering(aInv, bInv, C) == P 

True 

 

For a secret key `(a,b) \in \ZZ/n\ZZ \times \ZZ/n\ZZ`, if `a = 1` then 

any affine cryptosystem with key `(1, b)` for any `b \in \ZZ/n\ZZ` is 

a shift cryptosystem. Here is how we can create a Caesar cipher using 

an affine cipher:: 

 

sage: caesar = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (1, 3) 

sage: P = caesar.encoding("abcdef"); P 

ABCDEF 

sage: C = caesar.enciphering(a, b, P); C 

DEFGHI 

sage: caesar.deciphering(a, b, C) == P 

True 

 

Any affine cipher with keys of the form 

`(a,0) \in \ZZ/n\ZZ \times \ZZ/n\ZZ` is called a decimation cipher on 

the Roman alphabet, or decimation cipher for short:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: P = A.encoding("A decimation cipher is a specialized affine cipher.") 

sage: a, b = (17, 0) 

sage: C = A.enciphering(a, b, P) 

sage: P; C 

ADECIMATIONCIPHERISASPECIALIZEDAFFINECIPHER 

AZQIGWALGENIGVPQDGUAUVQIGAFGJQZAHHGNQIGVPQD 

sage: A.deciphering(a, b, C) == P 

True 

 

Generate a random key for encryption and decryption:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: P = A.encoding("An affine cipher with a random key.") 

sage: a, b = A.random_key() 

sage: C = A.enciphering(a, b, P) 

sage: A.deciphering(a, b, C) == P 

True 

 

TESTS: 

 

The binary number system is currently not a supported alphabet of 

this affine cryptosystem:: 

 

sage: AffineCryptosystem(BinaryStrings()) 

Traceback (most recent call last): 

... 

TypeError: A (= Free binary string monoid) is not supported as a cipher domain of this affine cryptosystem. 

 

Nor are the octal, hexadecimal, and radix-64 number systems supported:: 

 

sage: AffineCryptosystem(OctalStrings()) 

Traceback (most recent call last): 

... 

TypeError: A (= Free octal string monoid) is not supported as a cipher domain of this affine cryptosystem. 

sage: AffineCryptosystem(HexadecimalStrings()) 

Traceback (most recent call last): 

... 

TypeError: A (= Free hexadecimal string monoid) is not supported as a cipher domain of this affine cryptosystem. 

sage: AffineCryptosystem(Radix64Strings()) 

Traceback (most recent call last): 

... 

TypeError: A (= Free radix 64 string monoid) is not supported as a cipher domain of this affine cryptosystem. 

 

A secret key `(a,b)` must be an element of `\ZZ/n\ZZ \times \ZZ/n\ZZ` with 

`\gcd(a,n) = 1`. This rules out the case `a = 0` irrespective of the 

value of `b`. For the upper-case letters of the English alphabet, where 

the alphabet size is `n = 26`, `a` cannot take on any even value:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: A(0, 1) 

Traceback (most recent call last): 

... 

ValueError: (a, b) = (0, 1) is outside the range of acceptable values for a key of this affine cryptosystem. 

sage: A(2, 1) 

Traceback (most recent call last): 

... 

ValueError: (a, b) = (2, 1) is outside the range of acceptable values for a key of this affine cryptosystem. 

 

REFERENCES: 

 

- [Sti2006]_ 

""" 

 

def __init__(self, A): 

r""" 

See ``AffineCryptosystem`` for full documentation. 

 

INPUT: 

 

- ``A`` -- a string monoid over some alphabet; this is the non-empty 

alphabet over which the plaintext and ciphertext spaces 

are defined. 

 

OUTPUT: 

 

- An affine cryptosystem over the alphabet ``A``. 

 

EXAMPLES: 

 

Testing of dumping and loading objects:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: A == loads(dumps(A)) 

True 

""" 

# sanity check 

if not isinstance(A, AlphabeticStringMonoid): 

raise TypeError("A (= %s) is not supported as a cipher domain of this affine cryptosystem." % A) 

# List L of invertible linear coefficients modulo n, where n is the 

# alphabet size. Each e in L satisfies gcd(e, n) = 1. 

n = A.ngens() 

self._invertible_A = [i for i in range(n) if gcd(i, n) == 1] 

# Initialize the affine cryptosystem with the plaintext, ciphertext, 

# and key spaces. 

SymmetricKeyCryptosystem.__init__( 

self, A, A, 

key_space=(IntegerModRing(A.ngens()), IntegerModRing(A.ngens()))) 

 

def __call__(self, a, b): 

r""" 

Create an affine cipher with secret key ``(a,b)``. 

 

INPUT: 

 

- ``(a,b)`` -- a secret key; this key is used for both encryption and 

decryption. For the affine cryptosystem whose plaintext and 

ciphertext spaces are `A`, a key is an ordered pair 

`(a,b) \in \ZZ / n\ZZ \times \ZZ / n\ZZ` where `n` is the size or 

cardinality of the set `A` and `\gcd(a,n) = 1`. 

 

OUTPUT: 

 

- An affine cipher with secret key ``(a,b)``. 

 

EXAMPLES:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: P = A.encoding("Fine here, fine there."); P 

FINEHEREFINETHERE 

sage: a, b = (17, 3) 

sage: E = A(a, b); E 

Affine cipher on Free alphabetic string monoid on A-Z 

sage: E(P) 

KJQTSTGTKJQTOSTGT 

sage: C = E(P) 

sage: C 

KJQTSTGTKJQTOSTGT 

sage: aInv, bInv = A.inverse_key(a, b) 

sage: D = A(aInv, bInv); D 

Affine cipher on Free alphabetic string monoid on A-Z 

sage: P == D(C) 

True 

sage: D(E(P)) 

FINEHEREFINETHERE 

 

TESTS: 

 

The key must be an ordered pair 

`(a,b) \in \ZZ/n\ZZ \times \ZZ/n\ZZ` with `n` being the size of the 

plaintext and ciphertext spaces. Furthermore, `a` must be 

relatively prime to `n`, i.e. `\gcd(a,n) = 1`:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: A(2, 3) 

Traceback (most recent call last): 

... 

ValueError: (a, b) = (2, 3) is outside the range of acceptable values for a key of this affine cryptosystem. 

""" 

# Sanity check: the key K = (a,b) must be an element of 

# ZZ/nZZ x ZZ/nZZ where n is the size of the plaintext and ciphertext 

# spaces. For the affine cryptosystem, these two spaces are the 

# same alphabet. 

try: 

n = self.alphabet_size() 

# If a is an element of the multiplicative group G of ZZ/nZZ, then 

# gcd(a,n) = 1. So here we don't need to explicitly test that 

# a is coprime to n since we assume that the list 

# self._invertible_A contains all the elements of G. 

if (a in self._invertible_A) and (0 <= b < n): 

return AffineCipher(self, key=(a,b)) 

else: 

raise ValueError 

except Exception: 

raise ValueError("(a, b) = (%s, %s) is outside the range of acceptable values for a key of this affine cryptosystem." % (a, b)) 

 

def _repr_(self): 

r""" 

Return the string representation of ``self``. 

 

EXAMPLES:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()); A 

Affine cryptosystem on Free alphabetic string monoid on A-Z 

""" 

# The affine cipher has the plaintext and ciphertext spaces defined 

# over the same non-empty alphabet. The cipher domain is the same 

# as the alphabet used for the plaintext and ciphertext spaces. 

return "Affine cryptosystem on %s" % self.cipher_domain() 

 

def rank_by_chi_square(self, C, pdict): 

r""" 

Use the chi-square statistic to rank all possible keys. Currently, 

this method only applies to the capital letters of the English 

alphabet. 

 

ALGORITHM: 

 

Consider a non-empty alphabet `A` consisting of `n` 

elements, and let `C` be a ciphertext encoded using elements of 

`A`. The plaintext `P` corresponding to `C` is also encoded using 

elements of `A`. Let `M` be a candidate decipherment of `C`, 

i.e. `M` is the result of attempting to decrypt `C` using a key 

`(a,b)` which is not necessarily the same key used to encrypt `P`. 

Suppose `F_A(e)` is the characteristic frequency probability of 

`e \in A` and let `F_M(e)` be the message frequency probability with 

respect to `M`. The characteristic frequency probability 

distribution of an alphabet is the expected frequency probability 

distribution for that alphabet. The message frequency probability 

distribution of `M` provides a distribution of the ratio of character 

occurrences over message length. One can interpret the 

characteristic frequency probability `F_A(e)` as the expected 

probability, while the message frequency probability `F_M(e)` is 

the observed probability. If `M` is of length `L`, then the observed 

frequency of `e \in A` is 

 

.. MATH:: 

 

O_M(e) 

= 

F_M(e) \cdot L 

 

and the expected frequency of `e \in A` is 

 

.. MATH:: 

 

E_A(e) 

= 

F_A(e) \cdot L 

 

The chi-square rank `R_{\chi^2}(M)` of `M` corresponding to a key 

`(a,b) \in \ZZ/n\ZZ \times \ZZ/n\ZZ` is given by 

 

.. MATH:: 

 

R_{\chi^2}(M) 

= 

\sum_{e \in A} \frac {\big( O_M(e) - E_A(e) \big)^2} 

{E_A(e)} 

 

Cryptanalysis by exhaustive key search produces a candidate 

decipherment `M_{a,b}` for each possible key `(a,b)`. For a set 

`D = \big\{M_{a_1,b_1}, M_{a_2,b_2}, \dots, M_{a_k,b_k} \big\}` 

of all candidate decipherments corresponding to a ciphertext `C`, 

the smaller is the rank `R_{\chi^2}(M_{a_i,b_i})` the more likely 

that `(a_i,b_i)` is the secret key. This key ranking method is 

based on the Pearson chi-square test [PearsonTest]_. 

 

INPUT: 

 

- ``C`` -- The ciphertext, a non-empty string. The ciphertext 

must be encoded using the upper-case letters of the English 

alphabet. 

 

- ``pdict`` -- A dictionary of key, possible plaintext 

pairs. This should be the output of :func:`brute_force` with 

``ranking="none"``. 

 

OUTPUT: 

 

- A list ranking the most likely keys first. Each element of the 

list is a tuple of key, possible plaintext pairs. 

 

EXAMPLES: 

 

Use the chi-square statistic to rank all possible keys and their 

corresponding decipherment:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (3, 7) 

sage: P = A.encoding("Line.") 

sage: C = A.enciphering(a, b, P) 

sage: Plist = A.brute_force(C) 

sage: Rank = A.rank_by_chi_square(C, Plist) 

sage: Rank[:10] # display only the top 10 candidate keys 

<BLANKLINE> 

[((1, 1), NETS), 

((3, 7), LINE), 

((17, 20), STAD), 

((5, 2), SLOT), 

((5, 5), HADI), 

((9, 25), TSLI), 

((17, 15), DELO), 

((15, 6), ETUN), 

((21, 8), ELID), 

((7, 17), HCTE)] 

 

As more ciphertext is available, the reliability of the chi-square 

ranking function increases:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (11, 24) 

sage: P = A.encoding("Longer message is more information for cryptanalysis.") 

sage: C = A.enciphering(a, b, P) 

sage: Plist = A.brute_force(C) 

sage: Rank = A.rank_by_chi_square(C, Plist) 

sage: Rank[:10] # display only the top 10 candidate keys 

<BLANKLINE> 

[((11, 24), LONGERMESSAGEISMOREINFORMATIONFORCRYPTANALYSIS), 

((17, 9), INURFSBFLLHRFDLBNSFDUYNSBHEDNUYNSTSVGEHUHIVLDL), 

((9, 18), RMFIUHYUOOSIUWOYMHUWFBMHYSVWMFBMHGHETVSFSREOWO), 

((15, 12), VSTACPUCOOGACYOUSPCYTBSPUGNYSTBSPEPIRNGTGVIOYO), 

((3, 22), PAFOYLKYGGSOYEGKALYEFTALKSBEAFTALILCVBSFSPCGEG), 

((25, 3), OHSRNADNPPFRNVPDHANVSCHADFEVHSCHAJABWEFSFOBPVP), 

((7, 25), GHYNVIPVRRLNVFRPHIVFYEHIPLAFHYEHIDITQALYLGTRFR), 

((5, 2), NEHCIVKISSUCIWSKEVIWHFEVKUPWEHFEVOVABPUHUNASWS), 

((15, 25), IFGNPCHPBBTNPLBHFCPLGOFCHTALFGOFCRCVEATGTIVBLB), 

((9, 6), BWPSERIEYYCSEGYIWREGPLWRICFGWPLWRQRODFCPCBOYGY)] 

 

TESTS: 

 

The ciphertext cannot be an empty string:: 

 

sage: A.rank_by_chi_square("", Plist) 

Traceback (most recent call last): 

... 

AttributeError: 'str' object has no attribute 'parent' 

sage: A.rank_by_chi_square(A.encoding(""), Plist) 

Traceback (most recent call last): 

... 

ValueError: The ciphertext must be a non-empty string. 

sage: A.rank_by_chi_square(A.encoding(" "), Plist) 

Traceback (most recent call last): 

... 

ValueError: The ciphertext must be a non-empty string. 

 

The ciphertext must be encoded using the capital letters of the 

English alphabet as implemented in 

:func:`AlphabeticStrings() 

<sage.monoids.string_monoid.AlphabeticStrings>`:: 

 

sage: H = HexadecimalStrings() 

sage: A.rank_by_chi_square(H.encoding("shift"), Plist) 

Traceback (most recent call last): 

... 

TypeError: The ciphertext must be capital letters of the English alphabet. 

sage: B = BinaryStrings() 

sage: A.rank_by_chi_square(B.encoding("shift"), Plist) 

Traceback (most recent call last): 

... 

TypeError: The ciphertext must be capital letters of the English alphabet. 

 

The dictionary ``pdict`` cannot be empty:: 

 

sage: A.rank_by_chi_square(C, {}) 

Traceback (most recent call last): 

... 

KeyError: (1, 0) 

""" 

# NOTE: the code here is very similar to that in the method 

# rank_by_chi_square() of the class ShiftCryptosystem. The most 

# significant change in the code below is in how the secret key (a,b) 

# is processed. 

 

# sanity check 

from sage.monoids.string_monoid import AlphabeticStrings 

if not isinstance(C.parent(), AlphabeticStringMonoid): 

raise TypeError("The ciphertext must be capital letters of the English alphabet.") 

if str(C) == "": 

raise ValueError("The ciphertext must be a non-empty string.") 

 

# compute the rank of each key 

AS = AlphabeticStrings() 

# the alphabet in question 

Alph = self.encoding("".join([str(e) for e in AS.gens()])) 

StrAlph = str(Alph) 

# message length 

L = len(C) 

# expected frequency tally 

EA = AS.characteristic_frequency() 

for e in EA: 

EA[e] *= L 

# Compute the rank R_{chi^2}(M) of M with secret key (a,b). 

Rank = [] 

for a in self._invertible_A: 

for b in range(self.alphabet_size()): 

# observed frequency tally 

OM = pdict[(a, b)].frequency_distribution().function() 

for e in Alph: 

if e in OM: 

OM[e] *= L 

else: 

OM.setdefault(e, 0.0) 

# the rank R_{chi^2}(M) of M with secret key (a,b) 

RMab = [(OM[AS(e)] - EA[e])**2 / EA[e] for e in StrAlph] 

Rank.append((sum(RMab), (a, b))) 

# Sort in non-decreasing order of chi-square statistic. It's 

# possible that two different keys share the same chi-square 

# statistic. 

Rank = sorted(Rank) 

RankedList = [] 

# NOTE: each secret key is a tuple (a,b). So key[0] indexes a, 

# and key[1] indexes b. The value of val is not used at all, making 

# it redundant to access val in the first place. The following line 

# of code is written with readability in mind. 

[RankedList.append((key, pdict[(key[0], key[1])])) 

for val, key in Rank] 

return RankedList 

 

def rank_by_squared_differences(self, C, pdict): 

r""" 

Use the squared-differences measure to rank all possible keys. 

Currently, this method only applies to the capital letters of 

the English alphabet. 

 

ALGORITHM: 

 

Consider a non-empty alphabet `A` consisting of `n` 

elements, and let `C` be a ciphertext encoded using elements of 

`A`. The plaintext `P` corresponding to `C` is also encoded using 

elements of `A`. Let `M` be a candidate decipherment of `C`, 

i.e. `M` is the result of attempting to decrypt `C` using a key 

`(a,b)` which is not necessarily the same key used to encrypt `P`. 

Suppose `F_A(e)` is the characteristic frequency probability of 

`e \in A` and let `F_M(e)` be the message frequency probability with 

respect to `M`. The characteristic frequency probability 

distribution of an alphabet is the expected frequency probability 

distribution for that alphabet. The message frequency probability 

distribution of `M` provides a distribution of the ratio of character 

occurrences over message length. One can interpret the 

characteristic frequency probability `F_A(e)` as the expected 

probability, while the message frequency probability `F_M(e)` is 

the observed probability. If `M` is of length `L`, then the observed 

frequency of `e \in A` is 

 

.. MATH:: 

 

O_M(e) 

= 

F_M(e) \cdot L 

 

and the expected frequency of `e \in A` is 

 

.. MATH:: 

 

E_A(e) 

= 

F_A(e) \cdot L 

 

The squared-differences, or residual sum of squares, rank 

`R_{RSS}(M)` of `M` corresponding to a key 

`(a,b) \in \ZZ/n\ZZ \times \ZZ/n\ZZ` is given by 

 

.. MATH:: 

 

R_{RSS}(M) 

= 

\sum_{e \in A} \big( O_M(e) - E_A(e) \big)^2 

 

Cryptanalysis by exhaustive key search produces a candidate 

decipherment `M_{a,b}` for each possible key `(a,b)`. For a set 

`D = \big\{M_{a_1,b_1}, M_{a_2,b_2}, \dots, M_{a_k,b_k} \big\}` 

of all candidate decipherments corresponding to a ciphertext `C`, 

the smaller is the rank `R_{RSS}(M_{a_i,b_i})` the more likely 

that `(a_i,b_i)` is the secret key. This key ranking method is 

based on the residual sum of squares measure [RSS]_. 

 

INPUT: 

 

- ``C`` -- The ciphertext, a non-empty string. The ciphertext 

must be encoded using the upper-case letters of the English 

alphabet. 

 

- ``pdict`` -- A dictionary of key, possible plaintext 

pairs. This should be the output of :func:`brute_force` with 

``ranking="none"``. 

 

OUTPUT: 

 

- A list ranking the most likely keys first. Each element of the 

list is a tuple of key, possible plaintext pairs. 

 

EXAMPLES: 

 

Use the method of squared differences to rank all possible keys 

and their corresponding decipherment:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (3, 7) 

sage: P = A.encoding("Line.") 

sage: C = A.enciphering(a, b, P) 

sage: Plist = A.brute_force(C) 

sage: Rank = A.rank_by_squared_differences(C, Plist) 

sage: Rank[:10] # display only the top 10 candidate keys 

<BLANKLINE> 

[((1, 1), NETS), 

((15, 6), ETUN), 

((7, 17), HCTE), 

((3, 7), LINE), 

((17, 15), DELO), 

((9, 4), EDWT), 

((9, 9), POHE), 

((21, 8), ELID), 

((17, 20), STAD), 

((7, 18), SNEP)] 

 

As more ciphertext is available, the reliability of the 

squared-differences ranking function increases:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (11, 24) 

sage: P = A.encoding("Longer message is more information for cryptanalysis.") 

sage: C = A.enciphering(a, b, P) 

sage: Plist = A.brute_force(C) 

sage: Rank = A.rank_by_squared_differences(C, Plist) 

sage: Rank[:10] # display only the top 10 candidate keys 

<BLANKLINE> 

[((11, 24), LONGERMESSAGEISMOREINFORMATIONFORCRYPTANALYSIS), 

((9, 14), DYRUGTKGAAEUGIAKYTGIRNYTKEHIYRNYTSTQFHEREDQAIA), 

((23, 24), DSNEUHIUMMAEUOMISHUONZSHIAROSNZSHKHQXRANADQMOM), 

((23, 1), ETOFVIJVNNBFVPNJTIVPOATIJBSPTOATILIRYSBOBERNPN), 

((21, 16), VEBGANYAQQOGAMQYENAMBDENYOTMEBDENUNIHTOBOVIQMQ), 

((7, 12), TULAIVCIEEYAISECUVISLRUVCYNSULRUVQVGDNYLYTGESE), 

((5, 20), ZQTOUHWUEEGOUIEWQHUITRQHWGBIQTRQHAHMNBGTGZMEIE), 

((21, 8), JSPUOBMOEECUOAEMSBOAPRSBMCHASPRSBIBWVHCPCJWEAE), 

((25, 7), SLWVREHRTTJVRZTHLERZWGLEHJIZLWGLENEFAIJWJSFTZT), 

((25, 15), ATEDZMPZBBRDZHBPTMZHEOTMPRQHTEOTMVMNIQRERANBHB)] 

 

TESTS: 

 

The ciphertext cannot be an empty string:: 

 

sage: A.rank_by_squared_differences("", Plist) 

Traceback (most recent call last): 

... 

AttributeError: 'str' object has no attribute 'parent' 

sage: A.rank_by_squared_differences(A.encoding(""), Plist) 

Traceback (most recent call last): 

... 

ValueError: The ciphertext must be a non-empty string. 

sage: A.rank_by_squared_differences(A.encoding(" "), Plist) 

Traceback (most recent call last): 

... 

ValueError: The ciphertext must be a non-empty string. 

 

The ciphertext must be encoded using the capital letters of the 

English alphabet as implemented in 

:func:`AlphabeticStrings() 

<sage.monoids.string_monoid.AlphabeticStrings>`:: 

 

sage: H = HexadecimalStrings() 

sage: A.rank_by_squared_differences(H.encoding("line"), Plist) 

Traceback (most recent call last): 

... 

TypeError: The ciphertext must be capital letters of the English alphabet. 

sage: B = BinaryStrings() 

sage: A.rank_by_squared_differences(B.encoding("line"), Plist) 

Traceback (most recent call last): 

... 

TypeError: The ciphertext must be capital letters of the English alphabet. 

 

The dictionary ``pdict`` cannot be empty:: 

 

sage: A.rank_by_squared_differences(C, {}) 

Traceback (most recent call last): 

... 

KeyError: (1, 0) 

""" 

# NOTE: the code here is very similar to that in the method 

# rank_by_squared_differences() of the class ShiftCryptosystem. 

# The most significant change in the code below is in how the 

# secret key (a,b) is processed. 

 

# sanity check 

from sage.monoids.string_monoid import AlphabeticStrings 

if not isinstance(C.parent(), AlphabeticStringMonoid): 

raise TypeError("The ciphertext must be capital letters of the English alphabet.") 

if str(C) == "": 

raise ValueError("The ciphertext must be a non-empty string.") 

 

# compute the rank of each key 

AS = AlphabeticStrings() 

# the alphabet in question 

Alph = self.encoding("".join([str(e) for e in AS.gens()])) 

StrAlph = str(Alph) 

# message length 

L = len(C) 

# expected frequency tally 

EA = AS.characteristic_frequency() 

for e in EA: 

EA[e] *= L 

# Compute the rank R_{RSS}(M) of M with secret key (a,b). 

Rank = [] 

for a in self._invertible_A: 

for b in range(self.alphabet_size()): 

# observed frequency tally 

OM = pdict[(a, b)].frequency_distribution().function() 

for e in Alph: 

if e in OM: 

OM[e] *= L 

else: 

OM.setdefault(e, 0.0) 

# the rank R_{RSS}(M) of M with secret key (a,b) 

RMab = [(OM[AS(e)] - EA[e])**2 for e in StrAlph] 

Rank.append((sum(RMab), (a, b))) 

# Sort in non-decreasing order of squared-differences statistic. It's 

# possible that two different keys share the same squared-differences 

# statistic. 

Rank = sorted(Rank) 

RankedList = [] 

# NOTE: each secret key is a tuple (a,b). So key[0] indexes a, 

# and key[1] indexes b. The value of val is not used at all, making 

# it redundant to access val in the first place. The following line 

# of code is written with readability in mind. 

[RankedList.append((key, pdict[(key[0], key[1])])) 

for val, key in Rank] 

return RankedList 

 

def brute_force(self, C, ranking="none"): 

r""" 

Attempt a brute force cryptanalysis of the ciphertext ``C``. 

 

INPUT: 

 

- ``C`` -- A ciphertext over one of the supported alphabets of this 

affine cryptosystem. See the class :class:`AffineCryptosystem` for 

documentation on the supported alphabets. 

 

- ``ranking`` -- (default ``"none"``) the method to use for 

ranking all possible keys. If ``ranking="none"``, then do not 

use any ranking function. The following ranking functions are 

supported: 

 

- ``"chi_square"`` -- the chi-square ranking function 

as implemented in the method :func:`rank_by_chi_square`. 

 

- ``"squared_differences"`` -- the squared differences ranking 

function as implemented in the method 

:func:`rank_by_squared_differences`. 

 

OUTPUT: 

 

- All the possible plaintext sequences corresponding to the 

ciphertext ``C``. This method effectively uses all the possible 

keys in this affine cryptosystem to decrypt ``C``. The method is 

also referred to as exhaustive key search. The output is a 

dictionary of key, candidate decipherment pairs. 

 

EXAMPLES: 

 

Cryptanalyze using all possible keys with the option 

``ranking="none"``:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (3, 7) 

sage: P = A.encoding("Linear"); P 

LINEAR 

sage: C = A.enciphering(a, b, P) 

sage: L = A.brute_force(C) 

sage: sorted(L.items())[:26] # display 26 candidate decipherments 

<BLANKLINE> 

[((1, 0), OFUTHG), 

((1, 1), NETSGF), 

((1, 2), MDSRFE), 

((1, 3), LCRQED), 

((1, 4), KBQPDC), 

((1, 5), JAPOCB), 

((1, 6), IZONBA), 

((1, 7), HYNMAZ), 

((1, 8), GXMLZY), 

((1, 9), FWLKYX), 

((1, 10), EVKJXW), 

((1, 11), DUJIWV), 

((1, 12), CTIHVU), 

((1, 13), BSHGUT), 

((1, 14), ARGFTS), 

((1, 15), ZQFESR), 

((1, 16), YPEDRQ), 

((1, 17), XODCQP), 

((1, 18), WNCBPO), 

((1, 19), VMBAON), 

((1, 20), ULAZNM), 

((1, 21), TKZYML), 

((1, 22), SJYXLK), 

((1, 23), RIXWKJ), 

((1, 24), QHWVJI), 

((1, 25), PGVUIH)] 

 

Use the chi-square ranking function, i.e. ``ranking="chisquare"``:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (3, 7) 

sage: P = A.encoding("Linear functions for encrypting and decrypting."); P 

LINEARFUNCTIONSFORENCRYPTINGANDDECRYPTING 

sage: C = A.enciphering(a, b, P) 

sage: Rank = A.brute_force(C, ranking="chisquare") 

sage: Rank[:10] # display only the top 10 candidate keys 

<BLANKLINE> 

[((3, 7), LINEARFUNCTIONSFORENCRYPTINGANDDECRYPTING), 

((23, 25), VYTCGPBMTENYSTOBSPCTEPIRNYTAGTDDCEPIRNYTA), 

((1, 12), CTIHVUKDIBATLIXKLUHIBUPOATINVIEEHBUPOATIN), 

((11, 15), HSRYELDAROVSWRQDWLYROLUBVSRIERTTYOLUBVSRI), 

((25, 1), NWHIUVFMHOPWEHSFEVIHOVABPWHCUHLLIOVABPWHC), 

((25, 7), TCNOABLSNUVCKNYLKBONUBGHVCNIANRROUBGHVCNI), 

((15, 4), SHIBVOWZILEHDIJWDOBILOFYEHIRVIGGBLOFYEHIR), 

((15, 23), PEFYSLTWFIBEAFGTALYFILCVBEFOSFDDYILCVBEFO), 

((7, 10), IDUFHSYXUTEDNULYNSFUTSVGEDURHUMMFTSVGEDUR), 

((19, 22), QVETRGABEFUVLENALGTEFGDSUVEHREMMTFGDSUVEH)] 

 

Use the squared differences ranking function, i.e. 

``ranking="squared_differences"``:: 

 

sage: Rank = A.brute_force(C, ranking="squared_differences") 

sage: Rank[:10] # display only the top 10 candidate keys 

<BLANKLINE> 

[((3, 7), LINEARFUNCTIONSFORENCRYPTINGANDDECRYPTING), 

((23, 6), GJENRAMXEPYJDEZMDANEPATCYJELREOONPATCYJEL), 

((23, 25), VYTCGPBMTENYSTOBSPCTEPIRNYTAGTDDCEPIRNYTA), 

((19, 22), QVETRGABEFUVLENALGTEFGDSUVEHREMMTFGDSUVEH), 

((19, 9), DIRGETNORSHIYRANYTGRSTQFHIRUERZZGSTQFHIRU), 

((23, 18), KNIRVEQBITCNHIDQHERITEXGCNIPVISSRTEXGCNIP), 

((17, 16), GHORBEIDOJMHFOVIFEROJETWMHOZBOAARJETWMHOZ), 

((21, 14), AHEZRMOFEVQHTEBOTMZEVMNIQHEDREKKZVMNIQHED), 

((1, 12), CTIHVUKDIBATLIXKLUHIBUPOATINVIEEHBUPOATIN), 

((7, 18), SNEPRCIHEDONXEVIXCPEDCFQONEBREWWPDCFQONEB)] 

 

TESTS: 

 

Currently, the binary number system is not supported as an 

alphabet of this affine cryptosystem:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: BinStr = BinaryStrings() 

sage: C = BinStr.encoding("abc") 

sage: A.brute_force(C) 

Traceback (most recent call last): 

... 

TypeError: Ciphertext must be encoded using one of the supported cipher domains of this affine cryptosystem. 

 

Nor are the octal, hexadecimal, and radix-64 number systems 

supported:: 

 

sage: OctStr = OctalStrings() 

sage: C = OctStr([1, 2, 3]) 

sage: A.brute_force(C) 

Traceback (most recent call last): 

... 

TypeError: Ciphertext must be encoded using one of the supported cipher domains of this affine cryptosystem. 

sage: HexStr = HexadecimalStrings() 

sage: C = HexStr.encoding("abc") 

sage: A.brute_force(C) 

Traceback (most recent call last): 

... 

TypeError: Ciphertext must be encoded using one of the supported cipher domains of this affine cryptosystem. 

sage: RadStr = Radix64Strings() 

sage: C = RadStr([1, 2, 3]) 

sage: A.brute_force(C) 

Traceback (most recent call last): 

... 

TypeError: Ciphertext must be encoded using one of the supported cipher domains of this affine cryptosystem. 

 

Only the chi-square and squared-differences ranking functions are 

currently supported. The keyword ``ranking`` must take on either 

of the values ``"none"``, ``"chisquare"`` or 

``"squared_differences"``:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (3, 7) 

sage: P = A.encoding("Linear") 

sage: C = A.enciphering(a, b, P) 

sage: A.brute_force(C, ranking="chi") 

Traceback (most recent call last): 

... 

ValueError: Keyword 'ranking' must be either 'none', 'chisquare', or 'squared_differences'. 

sage: A.brute_force(C, ranking="") 

Traceback (most recent call last): 

... 

ValueError: Keyword 'ranking' must be either 'none', 'chisquare', or 'squared_differences'. 

""" 

# Sanity check: ensure that C is encoded using one of the 

# supported alphabets of this affine cryptosystem. 

if not isinstance(C.parent(), AlphabeticStringMonoid): 

raise TypeError("Ciphertext must be encoded using one of the supported cipher domains of this affine cryptosystem.") 

ranking_functions = ["none", "chisquare", "squared_differences"] 

if ranking not in ranking_functions: 

raise ValueError("Keyword 'ranking' must be either 'none', 'chisquare', or 'squared_differences'.") 

 

# Now do the actual task of cryptanalysis by means of exhaustive 

# key search, also known as the brute force method. Let D be a 

# dictionary of key/plaintext pairs. 

D = {} 

 

# NOTE: This is a good candidate for loop unrolling and 

# further optimization. Unless we can justify that this block of 

# code is a bottleneck on the runtime of the method, we should 

# leave it as is. 

[D.setdefault((a, b), self.deciphering(a, b, C)) 

for a in self._invertible_A 

for b in range(self.alphabet_size())] 

 

if ranking == "none": 

return D 

if ranking == "chisquare": 

return self.rank_by_chi_square(C, D) 

if ranking == "squared_differences": 

return self.rank_by_squared_differences(C, D) 

 

def deciphering(self, a, b, C): 

r""" 

Decrypt the ciphertext ``C`` with the key ``(a, b)`` using affine 

cipher decryption. 

 

INPUT: 

 

- ``a, b`` -- a secret key belonging to the key space of this affine 

cipher. This key must be an element of 

`\ZZ/n\ZZ \times \ZZ/n\ZZ` such that `\gcd(a,n) = 1` with `n` 

being the size of the ciphertext and plaintext spaces. 

 

- ``C`` -- a string of ciphertext; possibly an empty string. 

Characters in this string must be encoded using one of the 

supported alphabets. See the method :func:`encoding()` for more 

information. 

 

OUTPUT: 

 

- The plaintext corresponding to the ciphertext ``C``. 

 

EXAMPLES: 

 

Decryption over the capital letters of the English alphabet:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (5, 2) 

sage: P = A.encoding("Affine functions are linear functions.") 

sage: C = A.enciphering(a, b, P); C 

CBBQPWBYPMTQUPOCJWFQPWCJBYPMTQUPO 

sage: P == A.deciphering(a, b, C) 

True 

 

The previous example can also be worked through using functional 

notation:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (5, 2) 

sage: P = A.encoding("Affine functions are linear functions.") 

sage: E = A(a, b); E 

Affine cipher on Free alphabetic string monoid on A-Z 

sage: C = E(P); C 

CBBQPWBYPMTQUPOCJWFQPWCJBYPMTQUPO 

sage: aInv, bInv = A.inverse_key(a, b) 

sage: D = A(aInv, bInv); D 

Affine cipher on Free alphabetic string monoid on A-Z 

sage: D(C) == P 

True 

 

If the ciphertext is an empty string, then the plaintext is also 

an empty string regardless of the value of the secret key:: 

 

sage: a, b = A.random_key() 

sage: A.deciphering(a, b, A.encoding("")) 

<BLANKLINE> 

sage: A.deciphering(a, b, A.encoding(" ")) 

<BLANKLINE> 

 

TESTS: 

 

The key must be an ordered pair 

`(a,b) \in \ZZ/n\ZZ \times \ZZ/n\ZZ` with `n` being the size of the 

plaintext and ciphertext spaces. Furthermore, `a` must be 

relatively prime to `n`, i.e. `\gcd(a,n) = 1`:: 

 

sage: A.deciphering(2, 6, P) 

Traceback (most recent call last): 

... 

ValueError: (a, b) = (2, 6) is outside the range of acceptable values for a key of this affine cipher. 

""" 

aInv, bInv = self.inverse_key(a, b) 

D = self(aInv, bInv) 

return D(C) 

 

def enciphering(self, a, b, P): 

r""" 

Encrypt the plaintext ``P`` with the key ``(a, b)`` using affine cipher 

encryption. 

 

INPUT: 

 

- ``a, b`` -- a secret key belonging to the key space of this affine 

cipher. This key must be an element of 

`\ZZ/n\ZZ \times \ZZ/n\ZZ` such that `\gcd(a,n) = 1` with `n` 

being the size of the ciphertext and plaintext spaces. 

 

- ``P`` -- a string of plaintext; possibly an empty string. 

Characters in this string must be encoded using one of the 

supported alphabets. See the method :func:`encoding()` for more 

information. 

 

OUTPUT: 

 

- The ciphertext corresponding to the plaintext ``P``. 

 

EXAMPLES: 

 

Encryption over the capital letters of the English alphabet:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (3, 6) 

sage: P = A.encoding("Affine ciphers work with linear functions.") 

sage: A.enciphering(a, b, P) 

GVVETSMEZBSFIUWFKUELBNETSGFVOTMLEWTI 

 

Now work through the previous example using functional notation:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (3, 6) 

sage: P = A.encoding("Affine ciphers work with linear functions.") 

sage: E = A(a, b); E 

Affine cipher on Free alphabetic string monoid on A-Z 

sage: E(P) 

GVVETSMEZBSFIUWFKUELBNETSGFVOTMLEWTI 

 

If the plaintext is an empty string, then the ciphertext is also 

an empty string regardless of the value of the secret key:: 

 

sage: a, b = A.random_key() 

sage: A.enciphering(a, b, A.encoding("")) 

<BLANKLINE> 

sage: A.enciphering(a, b, A.encoding(" ")) 

<BLANKLINE> 

 

TESTS: 

 

The key must be an ordered pair 

`(a,b) \in \ZZ/n\ZZ \times \ZZ/n\ZZ` with `n` being the size of the 

plaintext and ciphertext spaces. Furthermore, `a` must be 

relatively prime to `n`, i.e. `\gcd(a,n) = 1`:: 

 

sage: A.enciphering(2, 6, P) 

Traceback (most recent call last): 

... 

ValueError: (a, b) = (2, 6) is outside the range of acceptable values for a key of this affine cryptosystem. 

""" 

E = self(a, b) 

return E(P) 

 

def encoding(self, S): 

r""" 

The encoding of the string ``S`` over the string monoid of this 

affine cipher. For example, if the string monoid of this cryptosystem 

is 

:class:`AlphabeticStringMonoid <sage.monoids.string_monoid.AlphabeticStringMonoid>`, 

then the encoding of ``S`` would be its upper-case equivalent 

stripped of all non-alphabetic characters. Only the following alphabet 

is supported for the affine cipher: 

 

- capital letters of the English alphabet as implemented in 

:func:`AlphabeticStrings() <sage.monoids.string_monoid.AlphabeticStrings>` 

 

INPUT: 

 

- ``S`` -- a string, possibly empty. 

 

OUTPUT: 

 

- The encoding of ``S`` over the string monoid of this cryptosystem. 

If ``S`` is an empty string, return an empty string. 

 

EXAMPLES: 

 

Encoding over the upper-case letters of the English alphabet:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: A.encoding("Affine cipher over capital letters of the English alphabet.") 

AFFINECIPHEROVERCAPITALLETTERSOFTHEENGLISHALPHABET 

 

The argument ``S`` can be an empty string, in which case an empty 

string is returned:: 

 

sage: AffineCryptosystem(AlphabeticStrings()).encoding("") 

<BLANKLINE> 

""" 

D = self.cipher_domain() 

if isinstance(D, AlphabeticStringMonoid): 

return D(strip_encoding(S)) 

try: 

return D.encoding(S) 

except Exception: 

raise TypeError("Argument S = %s does not encode in the cipher domain" % S) 

 

def inverse_key(self, a, b): 

r""" 

The inverse key corresponding to the secret key `(a,b)`. If `p` is 

a plaintext character so that `p \in \ZZ/n\ZZ` and `n` is the 

alphabet size, then the ciphertext `c` corresponding to `p` is 

 

.. MATH:: 

 

c \equiv ap + b \pmod{n} 

 

As `(a,b)` is a key, then the multiplicative inverse `a^{-1}` 

exists and the original plaintext can be recovered as follows 

 

.. MATH:: 

 

p \equiv a^{-1} (c - b) \pmod{n} 

\equiv a^{-1}c + a^{-1}(-b) \pmod{n} 

 

Therefore the ordered pair `(a^{-1}, -ba^{-1})` is the inverse key 

corresponding to `(a,b)`. 

 

INPUT: 

 

- ``a, b`` -- a secret key for this affine cipher. The ordered pair 

`(a,b)` must be an element of `\ZZ/n\ZZ \times \ZZ/n\ZZ` such that 

`\gcd(a,n) = 1`. 

 

OUTPUT: 

 

- The inverse key `(a^{-1}, -ba^{-1})` corresponding to `(a,b)`. 

 

EXAMPLES:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: a, b = (1, 2) 

sage: A.inverse_key(a, b) 

(1, 24) 

sage: A.inverse_key(3, 2) 

(9, 8) 

 

Suppose that the plaintext and ciphertext spaces are the capital 

letters of the English alphabet so that `n = 26`. If `\varphi(n)` 

is the Euler phi function of `n`, then there are `\varphi(n)` 

integers `0 \leq a < n` that are relatively prime to `n`. For the 

capital letters of the English alphabet, there are 12 such integers 

relatively prime to `n`:: 

 

sage: euler_phi(A.alphabet_size()) 

12 

 

And here is a list of those integers:: 

 

sage: n = A.alphabet_size() 

sage: L = [i for i in range(n) if gcd(i, n) == 1]; L 

[1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25] 

 

Then a secret key `(a,b)` of this shift cryptosystem is 

such that `a` is an element of the list ``L`` in the last example. 

Any inverse key `(A, B)` corresponding to `(a,b)` is such that 

`A` is also in the list ``L`` above:: 

 

sage: a, b = (3, 9) 

sage: a in L 

True 

sage: aInv, bInv = A.inverse_key(a, b) 

sage: aInv, bInv 

(9, 23) 

sage: aInv in L 

True 

 

TESTS: 

 

Any ordered pair of the form `(0, b)` for any integer `b` cannot be 

a secret key of this affine cipher. Hence `(0, b)` does not have 

a corresponding inverse key:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: A.inverse_key(0, 1) 

Traceback (most recent call last): 

... 

ValueError: (a, b) = (0, 1) is outside the range of acceptable values for a key of this affine cipher. 

""" 

try: 

from sage.rings.finite_rings.integer_mod import Mod 

n = self.alphabet_size() 

aInv = inverse_mod(a, n) 

bInv = Mod(-b * aInv, n).lift() 

return (aInv, bInv) 

except Exception: 

raise ValueError("(a, b) = (%s, %s) is outside the range of acceptable values for a key of this affine cipher." % (a, b)) 

 

def random_key(self): 

r""" 

Generate a random key within the key space of this affine cipher. 

The generated secret key is an ordered pair 

`(a, b) \in \ZZ/n\ZZ \times \ZZ/n\ZZ` with `n` being the size of 

the cipher domain and `\gcd(a, n) = 1`. Let `\varphi(n)` denote 

the Euler phi function of `n`. Then the affine cipher has 

`n \cdot \varphi(n)` possible keys (see page 10 of [Sti2006]_). 

 

OUTPUT: 

 

- A random key within the key space of this affine cryptosystem. 

The output key is an ordered pair `(a,b)`. 

 

EXAMPLES:: 

 

sage: A = AffineCryptosystem(AlphabeticStrings()) 

sage: A.random_key() # random 

(17, 25) 

 

If `(a,b)` is a secret key and `n` is the size of the plaintext and 

ciphertext alphabets, then `\gcd(a, n) = 1`:: 

 

sage: a, b = A.random_key() 

sage: n = A.alphabet_size() 

sage: gcd(a, n) 

1 

""" 

# Return a random element in ZZ/nZZ x ZZ/nZZ where n is the number 

# of elements in the plaintext/ciphertext alphabet. 

from sage.misc.prandom import randint 

n = self.alphabet_size() 

L = len(self._invertible_A) 

a = Integer(self._invertible_A[randint(0, L - 1)]) 

b = Integer(randint(0, n - 1)) 

return (a, b) 

 

class HillCryptosystem(SymmetricKeyCryptosystem): 

""" 

Create a Hill cryptosystem defined by the `m` x `m` matrix space 

over `\ZZ / N \ZZ`, where `N` is the alphabet size of 

the string monoid ``S``. 

 

INPUT: 

 

- ``S`` - a string monoid over some alphabet 

 

- ``m`` - integer `> 0`; the block length of matrices that specify 

block permutations 

 

OUTPUT: 

 

- A Hill cryptosystem of block length ``m`` over the alphabet ``S``. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = HillCryptosystem(S,3) 

sage: E 

Hill cryptosystem on Free alphabetic string monoid on A-Z of block length 3 

sage: R = IntegerModRing(26) 

sage: M = MatrixSpace(R,3,3) 

sage: A = M([[1,0,1],[0,1,1],[2,2,3]]) 

sage: A 

[1 0 1] 

[0 1 1] 

[2 2 3] 

sage: e = E(A) 

sage: e 

Hill cipher on Free alphabetic string monoid on A-Z of block length 3 

sage: e(S("LAMAISONBLANCHE")) 

JYVKSKQPELAYKPV 

 

TESTS:: 

 

sage: S = AlphabeticStrings() 

sage: E = HillCryptosystem(S,3) 

sage: E == loads(dumps(E)) 

True 

""" 

 

def __init__(self, S, m): 

""" 

See ``HillCryptosystem`` for full documentation. 

 

Create a Hill cryptosystem defined by the `m` x `m` matrix space 

over `\ZZ / N \ZZ`, where `N` is the alphabet size of 

the string monoid ``S``. 

 

INPUT: 

 

- ``S`` - a string monoid over some alphabet 

 

- ``m`` - integer `> 0`; the block length of matrices that specify 

block permutations 

 

OUTPUT: 

 

- A Hill cryptosystem of block length ``m`` over the alphabet ``S``. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = HillCryptosystem(S,3) 

sage: E 

Hill cryptosystem on Free alphabetic string monoid on A-Z of block length 3 

""" 

if not isinstance(S, StringMonoid_class): 

raise TypeError("S (= %s) must be a string monoid." % S) 

R = IntegerModRing(S.ngens()) 

M = MatrixSpace(R, m, m) 

SymmetricKeyCryptosystem.__init__(self, S, S, M, block_length=m) 

 

def __call__(self, A): 

""" 

Create a Hill cipher. 

 

INPUT: 

 

- ``A`` - a matrix which specifies a block permutation 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = HillCryptosystem(S,3) 

sage: E 

Hill cryptosystem on Free alphabetic string monoid on A-Z of block length 3 

sage: M = E.key_space() 

sage: A = M([[1,0,1],[0,1,1],[2,2,3]]) 

sage: A 

[1 0 1] 

[0 1 1] 

[2 2 3] 

sage: e = E(A) 

sage: e 

Hill cipher on Free alphabetic string monoid on A-Z of block length 3 

sage: m = S("LAMAISONBLANCHE") 

sage: e(m) 

JYVKSKQPELAYKPV 

sage: c = e.inverse() 

sage: c(e(m)) 

LAMAISONBLANCHE 

""" 

M = self.key_space() 

m = self.block_length() 

if isinstance(A, list): 

try: 

A = M(A) 

except Exception: 

raise TypeError("A (= %s) must specify a square matrix of degree %s." % (A, m)) 

return HillCipher(self, A) 

 

def _repr_(self): 

""" 

Return a string representation of self. 

 

EXAMPLES:: 

 

sage: A = AlphabeticStrings() 

sage: H = HillCryptosystem(A, 3) 

sage: H 

Hill cryptosystem on Free alphabetic string monoid on A-Z of block length 3 

sage: H._repr_() 

'Hill cryptosystem on Free alphabetic string monoid on A-Z of block length 3' 

""" 

return "Hill cryptosystem on %s of block length %s" % ( 

self.cipher_domain(), self.block_length()) 

 

def block_length(self): 

""" 

The row or column dimension of a matrix specifying a block 

permutation. Encryption and decryption keys of a Hill cipher are 

square matrices, i.e. the row and column dimensions of an encryption 

or decryption key are the same. This row/column dimension is referred 

to as the *block length*. 

 

OUTPUT: 

 

- The block length of an encryption/decryption key. 

 

EXAMPLES:: 

 

sage: A = AlphabeticStrings() 

sage: n = randint(1, A.ngens() - 1) 

sage: H = HillCryptosystem(A, n) 

sage: H.block_length() == n 

True 

""" 

return self.key_space().nrows() 

 

def random_key(self): 

""" 

A random key within the key space of this Hill cipher. That is, 

generate a random `m` x `m` matrix to be used as a block 

permutation, where `m` is the block length of this Hill cipher. If 

`n` is the size of the cryptosystem alphabet, then there are 

`n^{m^2}` possible keys. However the number of valid keys, 

i.e. invertible `m` x `m` square matrices, is smaller than 

`n^{m^2}`. 

 

OUTPUT: 

 

- A random key within the key space of this Hill cipher. 

 

EXAMPLES:: 

 

sage: A = AlphabeticStrings() 

sage: n = 3 

sage: H = HillCryptosystem(A, n) 

sage: K = H.random_key() 

sage: Ki = H.inverse_key(K) 

sage: M = "LAMAISONBLANCHE" 

sage: e = H(K) 

sage: d = H(Ki) 

sage: d(e(A(M))) == A(M) 

True 

""" 

M = self.key_space() 

R = M.base_ring() 

m = M.nrows() 

N = Integer(self.cipher_domain().ngens()) 

while True: 

A = M([ randint(0, N-1) for i in range(m**2) ]) 

if N.gcd(A.det().lift()) == 1: 

break 

return A 

 

def inverse_key(self, A): 

""" 

The inverse key corresponding to the key ``A``. 

 

INPUT: 

 

- ``A`` - an invertible matrix of the key space of this Hill cipher 

 

OUTPUT: 

 

- The inverse matrix of ``A``. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = HillCryptosystem(S,3) 

sage: A = E.random_key() 

sage: B = E.inverse_key(A) 

sage: M = S("LAMAISONBLANCHE") 

sage: e = E(A) 

sage: c = E(B) 

sage: c(e(M)) 

LAMAISONBLANCHE 

""" 

S = self.plaintext_space() 

M = self.key_space() 

if not A in M: 

raise TypeError("A (= %s) must be a matrix in the key space of %s." % (A, self)) 

m = self.block_length() 

MatZZ = MatrixSpace(ZZ, m) 

AZ = MatZZ([ [ A[i, j].lift() for j in range(m) ] for i in range(m) ]) 

AZ_adj = AZ.adjoint() 

u, r, s = xgcd(A.det().lift(), S.ngens()) 

if u != 1: 

raise ValueError("Argument:\n\n%s\n\nis not invertible." % (A)) 

return r * A.parent()(AZ_adj) 

 

def encoding(self, M): 

""" 

The encoding of the string ``M`` over the string monoid of this 

Hill cipher. For example, if the string monoid of this Hill cipher 

is :class:`AlphabeticStringMonoid`, then the encoding of ``M`` would 

be its upper-case equivalent stripped of all non-alphabetic 

characters. 

 

INPUT: 

 

- ``M`` - a string, possibly empty 

 

OUTPUT: 

 

- The encoding of ``M`` over the string monoid of this Hill cipher. 

 

EXAMPLES:: 

 

sage: M = "The matrix cipher by Lester S. Hill." 

sage: A = AlphabeticStrings() 

sage: H = HillCryptosystem(A, 7) 

sage: H.encoding(M) == A.encoding(M) 

True 

""" 

S = self.cipher_domain() 

if isinstance(S, AlphabeticStringMonoid): 

return S(strip_encoding(M)) 

try: 

return S.encoding(M) 

except Exception: 

raise TypeError("Argument M = %s does not encode in the cipher domain" % M) 

 

def deciphering(self, A, C): 

""" 

Decrypt the ciphertext ``C`` using the key ``A``. 

 

INPUT: 

 

- ``A`` - a key within the key space of this Hill cipher 

 

- ``C`` - a string (possibly empty) over the string monoid of this 

Hill cipher 

 

OUTPUT: 

 

- The plaintext corresponding to the ciphertext ``C``. 

 

EXAMPLES:: 

 

sage: H = HillCryptosystem(AlphabeticStrings(), 3) 

sage: K = H.random_key() 

sage: M = H.encoding("Good day, mate! How ya going?") 

sage: H.deciphering(K, H.enciphering(K, M)) == M 

True 

""" 

# TODO: some type checking that A is invertible hence a valid key 

i = self(self.inverse_key(A)) 

return i(C) 

 

def enciphering(self, A, M): 

""" 

Encrypt the plaintext ``M`` using the key ``A``. 

 

INPUT: 

 

- ``A`` - a key within the key space of this Hill cipher 

 

- ``M`` - a string (possibly empty) over the string monoid of this 

Hill cipher. 

 

OUTPUT: 

 

- The ciphertext corresponding to the plaintext ``M``. 

 

EXAMPLES:: 

 

sage: H = HillCryptosystem(AlphabeticStrings(), 3) 

sage: K = H.random_key() 

sage: M = H.encoding("Good day, mate! How ya going?") 

sage: H.deciphering(K, H.enciphering(K, M)) == M 

True 

""" 

# TODO: some type checking that A is invertible hence a valid key 

e = self(A) 

return e(M) 

 

class ShiftCryptosystem(SymmetricKeyCryptosystem): 

r""" 

Create a shift cryptosystem. 

 

Let `A = \{ a_0, a_1, a_2, \dots, a_{n-1} \}` be a non-empty alphabet 

consisting of `n` unique elements. Define a mapping 

`f : A \longrightarrow \ZZ/ n\ZZ` from the alphabet `A` to 

the set `\ZZ / n\ZZ` of integers modulo `n`, given by 

`f(a_i) = i`. Thus we can identify each element of the alphabet `A` 

with a unique integer `0 \leq i < n`. A key of the shift cipher is an 

integer `0 \leq k < n`. Therefore the key space is `\ZZ / n\ZZ`. Since 

we assume that `A` does not have repeated elements, the mapping 

`f : A \longrightarrow \ZZ/ n\ZZ` is bijective. 

Encryption works by moving along the alphabet by `k` positions, with 

wrap around. Decryption reverses the process by moving backwards by 

`k` positions, with wrap around. More generally, let `k` be a secret key, 

i.e. an element of the key space, and let `p` be a plaintext 

character and consequently `p \in \ZZ / n\ZZ`. Then the ciphertext 

character `c` corresponding to `p` is given by 

 

.. MATH:: 

 

c \equiv p + k \pmod{n} 

 

Similarly, given a ciphertext character `c \in \ZZ / n\ZZ` and a secret 

key `k`, we can recover the corresponding plaintext character as follows: 

 

.. MATH:: 

 

p \equiv c - k \pmod{n} 

 

Use the bijection `f : A \longrightarrow \ZZ/ n\ZZ` to convert `c` 

and `p` back to elements of the alphabet `A`. Currently, the following 

alphabets are supported for the shift cipher: 

 

- capital letters of the English alphabet as implemented in 

:func:`AlphabeticStrings() 

<sage.monoids.string_monoid.AlphabeticStrings>` 

 

- the alphabet consisting of the hexadecimal number system as 

implemented in 

:func:`HexadecimalStrings() 

<sage.monoids.string_monoid.HexadecimalStrings>` 

 

- the alphabet consisting of the binary number system as implemented in 

:func:`BinaryStrings() <sage.monoids.string_monoid.BinaryStrings>` 

 

EXAMPLES: 

 

Some examples illustrating encryption and decryption over various 

alphabets. Here is an example over the upper-case letters of the English 

alphabet:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()); S 

Shift cryptosystem on Free alphabetic string monoid on A-Z 

sage: P = S.encoding("The shift cryptosystem generalizes the Caesar cipher.") 

sage: P 

THESHIFTCRYPTOSYSTEMGENERALIZESTHECAESARCIPHER 

sage: K = 7 

sage: C = S.enciphering(K, P); C 

AOLZOPMAJYFWAVZFZALTNLULYHSPGLZAOLJHLZHYJPWOLY 

sage: S.deciphering(K, C) 

THESHIFTCRYPTOSYSTEMGENERALIZESTHECAESARCIPHER 

sage: S.deciphering(K, C) == P 

True 

 

The previous example can also be done as follows:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: P = S.encoding("The shift cryptosystem generalizes the Caesar cipher.") 

sage: K = 7 

sage: E = S(K); E 

Shift cipher on Free alphabetic string monoid on A-Z 

sage: C = E(P); C 

AOLZOPMAJYFWAVZFZALTNLULYHSPGLZAOLJHLZHYJPWOLY 

sage: D = S(S.inverse_key(K)); D 

Shift cipher on Free alphabetic string monoid on A-Z 

sage: D(C) == P 

True 

sage: D(C) == P == D(E(P)) 

True 

 

Over the hexadecimal number system:: 

 

sage: S = ShiftCryptosystem(HexadecimalStrings()); S 

Shift cryptosystem on Free hexadecimal string monoid 

sage: P = S.encoding("Encryption & decryption shifts along the alphabet."); P 

456e6372797074696f6e20262064656372797074696f6e2073686966747320616c6f6e672074686520616c7068616265742e 

sage: K = 5 

sage: C = S.enciphering(K, P); C 

9ab3b8c7cec5c9beb4b3757b75b9bab8c7cec5c9beb4b375c8bdbebbc9c875b6b1b4b3bc75c9bdba75b6b1c5bdb6b7bac973 

sage: S.deciphering(K, C) 

456e6372797074696f6e20262064656372797074696f6e2073686966747320616c6f6e672074686520616c7068616265742e 

sage: S.deciphering(K, C) == P 

True 

 

And over the binary number system:: 

 

sage: S = ShiftCryptosystem(BinaryStrings()); S 

Shift cryptosystem on Free binary string monoid 

sage: P = S.encoding("The binary alphabet is very insecure."); P 

01010100011010000110010100100000011000100110100101101110011000010111001001111001001000000110000101101100011100000110100001100001011000100110010101110100001000000110100101110011001000000111011001100101011100100111100100100000011010010110111001110011011001010110001101110101011100100110010100101110 

sage: K = 1 

sage: C = S.enciphering(K, P); C 

10101011100101111001101011011111100111011001011010010001100111101000110110000110110111111001111010010011100011111001011110011110100111011001101010001011110111111001011010001100110111111000100110011010100011011000011011011111100101101001000110001100100110101001110010001010100011011001101011010001 

sage: S.deciphering(K, C) 

01010100011010000110010100100000011000100110100101101110011000010111001001111001001000000110000101101100011100000110100001100001011000100110010101110100001000000110100101110011001000000111011001100101011100100111100100100000011010010110111001110011011001010110001101110101011100100110010100101110 

sage: S.deciphering(K, C) == P 

True 

 

A shift cryptosystem with key `k = 3` is commonly referred to as the 

Caesar cipher. Create a Caesar cipher over the upper-case letters of the 

English alphabet:: 

 

sage: caesar = ShiftCryptosystem(AlphabeticStrings()) 

sage: K = 3 

sage: P = caesar.encoding("abcdef"); P 

ABCDEF 

sage: C = caesar.enciphering(K, P); C 

DEFGHI 

sage: caesar.deciphering(K, C) == P 

True 

 

Generate a random key for encryption and decryption:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: P = S.encoding("Shift cipher with a random key.") 

sage: K = S.random_key() 

sage: C = S.enciphering(K, P) 

sage: S.deciphering(K, C) == P 

True 

 

Decrypting with the key ``K`` is equivalent to encrypting with its 

corresponding inverse key:: 

 

sage: S.enciphering(S.inverse_key(K), C) == P 

True 

 

TESTS: 

 

Currently, the octal number system is not supported as an alphabet for 

this shift cryptosystem:: 

 

sage: ShiftCryptosystem(OctalStrings()) 

Traceback (most recent call last): 

... 

TypeError: A (= Free octal string monoid) is not supported as a cipher domain of this shift cryptosystem. 

 

Nor is the radix-64 number system supported:: 

 

sage: ShiftCryptosystem(Radix64Strings()) 

Traceback (most recent call last): 

... 

TypeError: A (= Free radix 64 string monoid) is not supported as a cipher domain of this shift cryptosystem. 

 

Testing of dumping and loading objects:: 

 

sage: SA = ShiftCryptosystem(AlphabeticStrings()) 

sage: SA == loads(dumps(SA)) 

True 

sage: SH = ShiftCryptosystem(HexadecimalStrings()) 

sage: SH == loads(dumps(SH)) 

True 

sage: SB = ShiftCryptosystem(BinaryStrings()) 

sage: SB == loads(dumps(SB)) 

True 

 

The key ``K`` must satisfy the inequality `0 \leq K < n` with `n` 

being the size of the plaintext, ciphertext, and key spaces. For the 

shift cryptosystem, all these spaces are the same alphabet. This 

inequality must be satisfied for each of the supported alphabets. 

The capital letters of the English alphabet:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: S(2 + S.alphabet_size()) 

Traceback (most recent call last): 

... 

ValueError: K (=28) is outside the range of acceptable values for a key of this shift cryptosystem. 

sage: S(-2) 

Traceback (most recent call last): 

... 

ValueError: K (=-2) is outside the range of acceptable values for a key of this shift cryptosystem. 

 

The hexadecimal number system:: 

 

sage: S = ShiftCryptosystem(HexadecimalStrings()) 

sage: S(1 + S.alphabet_size()) 

Traceback (most recent call last): 

... 

ValueError: K (=17) is outside the range of acceptable values for a key of this shift cryptosystem. 

sage: S(-1) 

Traceback (most recent call last): 

... 

ValueError: K (=-1) is outside the range of acceptable values for a key of this shift cryptosystem. 

 

The binary number system:: 

 

sage: S = ShiftCryptosystem(BinaryStrings()) 

sage: S(1 + S.alphabet_size()) 

Traceback (most recent call last): 

... 

ValueError: K (=3) is outside the range of acceptable values for a key of this shift cryptosystem. 

sage: S(-2) 

Traceback (most recent call last): 

... 

ValueError: K (=-2) is outside the range of acceptable values for a key of this shift cryptosystem. 

""" 

 

def __init__(self, A): 

r""" 

See ``ShiftCryptosystem`` for full documentation. 

 

Create a shift cryptosystem defined over the alphabet ``A``. 

 

INPUT: 

 

- ``A`` -- a string monoid over some alphabet; this is the non-empty 

alphabet over which the plaintext and ciphertext spaces 

are defined. 

 

OUTPUT: 

 

- A shift cryptosystem over the alphabet ``A``. 

 

EXAMPLES:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()); S 

Shift cryptosystem on Free alphabetic string monoid on A-Z 

sage: P = S.encoding("The shift cryptosystem generalizes the Caesar cipher.") 

sage: P 

THESHIFTCRYPTOSYSTEMGENERALIZESTHECAESARCIPHER 

sage: K = 7 

sage: C = S.enciphering(K, P); C 

AOLZOPMAJYFWAVZFZALTNLULYHSPGLZAOLJHLZHYJPWOLY 

sage: S.deciphering(K, C) 

THESHIFTCRYPTOSYSTEMGENERALIZESTHECAESARCIPHER 

sage: S.deciphering(K, C) == P 

True 

""" 

# NOTE: the code here is very similar to that in the method 

# rank_by_chi_square() of the class AffineCryptosystem. The most 

# significant change in the code below is in how the secret key k 

# is processed. 

 

# sanity check 

from sage.monoids.string_monoid import ( 

AlphabeticStringMonoid, 

BinaryStringMonoid, 

HexadecimalStringMonoid) 

if not isinstance(A, ( AlphabeticStringMonoid, 

BinaryStringMonoid, 

HexadecimalStringMonoid )): 

raise TypeError("A (= %s) is not supported as a cipher domain of this shift cryptosystem." % A) 

# Initialize the shift cryptosystem with the plaintext, ciphertext, 

# and key spaces. 

SymmetricKeyCryptosystem.__init__(self, A, A, IntegerModRing(A.ngens())) 

 

def __call__(self, K): 

r""" 

Create a shift cipher with key ``K``. 

 

INPUT: 

 

- ``K`` -- a secret key; this key is used for both encryption and 

decryption. For the shift cryptosystem whose plaintext and 

ciphertext spaces are `A`, a key is any integer `k` such that 

`0 \leq k < n` where `n` is the size or cardinality of the set 

`A`. 

 

OUTPUT: 

 

- A shift cipher with secret key ``K``. 

 

EXAMPLES:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: P = S.encoding("Shifting sand."); P 

SHIFTINGSAND 

sage: K = 3 

sage: E = S(K); E 

Shift cipher on Free alphabetic string monoid on A-Z 

sage: E(P) 

VKLIWLQJVDQG 

sage: D = S(S.inverse_key(K)); D 

Shift cipher on Free alphabetic string monoid on A-Z 

sage: D(E(P)) 

SHIFTINGSAND 

 

TESTS: 

 

The key ``K`` must satisfy the inequality `0 \leq K < n` with `n` 

being the size of the plaintext, ciphertext, and key spaces. For the 

shift cryptosystem, all these spaces are the same alphabet. This 

inequality must be satisfied for each of the supported alphabets. 

The capital letters of the English alphabet:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: S(2 + S.alphabet_size()) 

Traceback (most recent call last): 

... 

ValueError: K (=28) is outside the range of acceptable values for a key of this shift cryptosystem. 

sage: S(-2) 

Traceback (most recent call last): 

... 

ValueError: K (=-2) is outside the range of acceptable values for a key of this shift cryptosystem. 

 

The hexadecimal number system:: 

 

sage: S = ShiftCryptosystem(HexadecimalStrings()) 

sage: S(1 + S.alphabet_size()) 

Traceback (most recent call last): 

... 

ValueError: K (=17) is outside the range of acceptable values for a key of this shift cryptosystem. 

sage: S(-1) 

Traceback (most recent call last): 

... 

ValueError: K (=-1) is outside the range of acceptable values for a key of this shift cryptosystem. 

 

The binary number system:: 

 

sage: S = ShiftCryptosystem(BinaryStrings()) 

sage: S(1 + S.alphabet_size()) 

Traceback (most recent call last): 

... 

ValueError: K (=3) is outside the range of acceptable values for a key of this shift cryptosystem. 

sage: S(-2) 

Traceback (most recent call last): 

... 

ValueError: K (=-2) is outside the range of acceptable values for a key of this shift cryptosystem. 

""" 

# Sanity check: the key K must satisfy the inequality 

# 0 <= K < n with n being the size of the plaintext, ciphertext, and 

# key spaces. For the shift cryptosystem, all these spaces are the 

# same alphabet. 

if 0 <= K < self.alphabet_size(): 

return ShiftCipher(self, K) 

# from sage.rings.finite_rings.integer_mod import Mod 

# return ShiftCipher(self, Mod(K, self.alphabet_size()).lift()) 

else: 

raise ValueError("K (=%s) is outside the range of acceptable values for a key of this shift cryptosystem." % K) 

 

def _repr_(self): 

r""" 

Return the string representation of ``self``. 

 

EXAMPLES:: 

 

sage: ShiftCryptosystem(AlphabeticStrings()) 

Shift cryptosystem on Free alphabetic string monoid on A-Z 

sage: ShiftCryptosystem(HexadecimalStrings()) 

Shift cryptosystem on Free hexadecimal string monoid 

sage: ShiftCryptosystem(BinaryStrings()) 

Shift cryptosystem on Free binary string monoid 

""" 

# The shift cipher has the plaintext and ciphertext spaces defined 

# over the same non-empty alphabet. The cipher domain is the same 

# as the alphabet used for the plaintext and ciphertext spaces. 

return "Shift cryptosystem on %s" % self.cipher_domain() 

 

def rank_by_chi_square(self, C, pdict): 

r""" 

Use the chi-square statistic to rank all possible keys. Currently, 

this method only applies to the capital letters of the English 

alphabet. 

 

ALGORITHM: 

 

Consider a non-empty alphabet `A` consisting of `n` 

elements, and let `C` be a ciphertext encoded using elements of 

`A`. The plaintext `P` corresponding to `C` is also encoded using 

elements of `A`. Let `M` be a candidate decipherment of `C`, 

i.e. `M` is the result of attempting to decrypt `C` using a key 

`k \in \ZZ/n\ZZ` which is not necessarily the same key used to 

encrypt `P`. Suppose `F_A(e)` is the characteristic frequency 

probability of `e \in A` and let `F_M(e)` be the message frequency 

probability with respect to `M`. The characteristic frequency 

probability distribution of an alphabet is the expected frequency 

probability distribution for that alphabet. The message frequency 

probability distribution of `M` provides a distribution of the ratio 

of character occurrences over message length. One can interpret the 

characteristic frequency probability `F_A(e)` as the expected 

probability, while the message frequency probability `F_M(e)` is 

the observed probability. If `M` is of length `L`, then the observed 

frequency of `e \in A` is 

 

.. MATH:: 

 

O_M(e) 

= 

F_M(e) \cdot L 

 

and the expected frequency of `e \in A` is 

 

.. MATH:: 

 

E_A(e) 

= 

F_A(e) \cdot L 

 

The chi-square rank `R_{\chi^2}(M)` of `M` corresponding to a key 

`k \in \ZZ/n\ZZ` is given by 

 

.. MATH:: 

 

R_{\chi^2}(M) 

= 

\sum_{e \in A} \frac {\big( O_M(e) - E_A(e) \big)^2} 

{E_A(e)} 

 

Cryptanalysis by exhaustive key search produces a candidate 

decipherment `M_{k}` for each possible key `k \in \ZZ/n\ZZ`. For 

a set 

`D = \big\{M_{k_1}, M_{k_2}, \dots, M_{k_r} \big\}` 

of all candidate decipherments corresponding to a ciphertext `C`, 

the smaller is the rank `R_{\chi^2}(M_{k_i})` the more likely 

that `k_i` is the secret key. This key ranking method is based on 

the Pearson chi-square test [PearsonTest]_. 

 

INPUT: 

 

- ``C`` -- The ciphertext, a non-empty string. The ciphertext 

must be encoded using the upper-case letters of the English 

alphabet. 

 

- ``pdict`` -- A dictionary of key, possible plaintext pairs. 

This should be the output of :func:`brute_force` with 

``ranking="none"``. 

 

OUTPUT: 

 

- A list ranking the most likely keys first. Each element of the 

list is a tuple of key, possible plaintext pairs. 

 

EXAMPLES: 

 

Use the chi-square statistic to rank all possible keys and their 

corresponding decipherment:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: P = S.encoding("Shi."); P 

SHI 

sage: K = 5 

sage: C = S.enciphering(K, P) 

sage: Pdict = S.brute_force(C) 

sage: S.rank_by_chi_square(C, Pdict) 

<BLANKLINE> 

[(9, ODE), 

(5, SHI), 

(20, DST), 

(19, ETU), 

(21, CRS), 

(10, NCD), 

(25, YNO), 

(6, RGH), 

(12, LAB), 

(8, PEF), 

(1, WLM), 

(11, MBC), 

(18, FUV), 

(17, GVW), 

(2, VKL), 

(4, TIJ), 

(3, UJK), 

(0, XMN), 

(16, HWX), 

(15, IXY), 

(23, APQ), 

(24, ZOP), 

(22, BQR), 

(7, QFG), 

(13, KZA), 

(14, JYZ)] 

 

As more ciphertext is available, the reliability of the chi-square 

ranking function increases:: 

 

sage: P = S.encoding("Shift cipher."); P 

SHIFTCIPHER 

sage: C = S.enciphering(K, P) 

sage: Pdict = S.brute_force(C) 

sage: S.rank_by_chi_square(C, Pdict) 

<BLANKLINE> 

[(5, SHIFTCIPHER), 

(9, ODEBPYELDAN), 

(18, FUVSGPVCURE), 

(2, VKLIWFLSKHU), 

(20, DSTQENTASPC), 

(19, ETURFOUBTQD), 

(21, CRSPDMSZROB), 

(6, RGHESBHOGDQ), 

(7, QFGDRAGNFCP), 

(12, LABYMVBIAXK), 

(17, GVWTHQWDVSF), 

(24, ZOPMAJPWOLY), 

(1, WLMJXGMTLIV), 

(0, XMNKYHNUMJW), 

(11, MBCZNWCJBYL), 

(8, PEFCQZFMEBO), 

(25, YNOLZIOVNKX), 

(10, NCDAOXDKCZM), 

(3, UJKHVEKRJGT), 

(4, TIJGUDJQIFS), 

(22, BQROCLRYQNA), 

(16, HWXUIRXEWTG), 

(15, IXYVJSYFXUH), 

(14, JYZWKTZGYVI), 

(13, KZAXLUAHZWJ), 

(23, APQNBKQXPMZ)] 

 

TESTS: 

 

The ciphertext cannot be an empty string:: 

 

sage: S.rank_by_chi_square("", Pdict) 

Traceback (most recent call last): 

... 

AttributeError: 'str' object has no attribute 'parent' 

sage: S.rank_by_chi_square(S.encoding(""), Pdict) 

Traceback (most recent call last): 

... 

ValueError: The ciphertext must be a non-empty string. 

sage: S.rank_by_chi_square(S.encoding(" "), Pdict) 

Traceback (most recent call last): 

... 

ValueError: The ciphertext must be a non-empty string. 

 

The ciphertext must be encoded using the capital letters of the 

English alphabet as implemented in 

:func:`AlphabeticStrings() 

<sage.monoids.string_monoid.AlphabeticStrings>`:: 

 

sage: H = HexadecimalStrings() 

sage: S.rank_by_chi_square(H.encoding("shift"), Pdict) 

Traceback (most recent call last): 

... 

TypeError: The ciphertext must be capital letters of the English alphabet. 

sage: B = BinaryStrings() 

sage: S.rank_by_chi_square(B.encoding("shift"), Pdict) 

Traceback (most recent call last): 

... 

TypeError: The ciphertext must be capital letters of the English alphabet. 

 

The dictionary ``pdict`` cannot be empty:: 

 

sage: S.rank_by_chi_square(C, {}) 

Traceback (most recent call last): 

... 

KeyError: 0 

""" 

# NOTE: the code here is very similar to that in the method 

# rank_by_chi_square() of the class AffineCryptosystem. The most 

# significant change in the code below is in how the secret key k 

# is processed. 

 

# sanity check 

from sage.monoids.string_monoid import AlphabeticStrings 

if not isinstance(C.parent(), AlphabeticStringMonoid): 

raise TypeError("The ciphertext must be capital letters of the English alphabet.") 

if str(C) == "": 

raise ValueError("The ciphertext must be a non-empty string.") 

 

# compute the rank of each key 

AS = AlphabeticStrings() 

# the alphabet in question 

Alph = self.encoding("".join([str(e) for e in AS.gens()])) 

StrAlph = str(Alph) 

# message length 

L = len(C) 

# expected frequency tally 

EA = AS.characteristic_frequency() 

for e in EA: 

EA[e] *= L 

# the rank R(M, k) of M for each key 

Rank = [] 

for key in range(self.alphabet_size()): 

# observed frequency tally 

OM = pdict[key].frequency_distribution().function() 

for e in Alph: 

if e in OM: 

OM[e] *= L 

else: 

OM.setdefault(e, 0.0) 

# the rank R(M, K) of M with shift key k 

RMk = [(OM[AS(e)] - EA[e])**2 / EA[e] for e in StrAlph] 

Rank.append((sum(RMk), key)) 

# Sort in non-decreasing order of squared-differences statistic. It's 

# possible that two different keys share the same squared-differences 

# statistic. 

Rank = sorted(Rank) 

RankedList = [] 

# In the following line, the value of val is not used at all, making 

# it redundant to access val in the first place. This line 

# of code is written with readability in mind. 

[RankedList.append((key, pdict[key])) for val, key in Rank] 

return RankedList 

 

def rank_by_squared_differences(self, C, pdict): 

r""" 

Use the squared-differences measure to rank all possible keys. 

Currently, this method only applies to the capital letters of 

the English alphabet. 

 

ALGORITHM: 

 

Consider a non-empty alphabet `A` consisting of `n` 

elements, and let `C` be a ciphertext encoded using elements of 

`A`. The plaintext `P` corresponding to `C` is also encoded using 

elements of `A`. Let `M` be a candidate decipherment of `C`, 

i.e. `M` is the result of attempting to decrypt `C` using a key 

`k \in \ZZ/n\ZZ` which is not necessarily the same key used to 

encrypt `P`. Suppose `F_A(e)` is the characteristic frequency 

probability of `e \in A` and let `F_M(e)` be the message 

frequency probability with respect to `M`. The characteristic 

frequency probability distribution of an alphabet is the expected 

frequency probability distribution for that alphabet. The message 

frequency probability distribution of `M` provides a distribution 

of the ratio of character occurrences over message length. One can 

interpret the characteristic frequency probability `F_A(e)` as the 

expected probability, while the message frequency probability 

`F_M(e)` is the observed probability. If `M` is of length `L`, then 

the observed frequency of `e \in A` is 

 

.. MATH:: 

 

O_M(e) 

= 

F_M(e) \cdot L 

 

and the expected frequency of `e \in A` is 

 

.. MATH:: 

 

E_A(e) 

= 

F_A(e) \cdot L 

 

The squared-differences, or residual sum of squares, rank 

`R_{RSS}(M)` of `M` corresponding to a key 

`k \in \ZZ/n\ZZ` is given by 

 

.. MATH:: 

 

R_{RSS}(M) 

= 

\sum_{e \in A} \big( O_M(e) - E_A(e) \big)^2 

 

Cryptanalysis by exhaustive key search produces a candidate 

decipherment `M_{k}` for each possible key `k \in \ZZ/n\ZZ`. For 

a set 

`D = \big\{M_{k_1}, M_{k_2}, \dots, M_{k_r} \big\}` 

of all candidate decipherments corresponding to a ciphertext `C`, 

the smaller is the rank `R_{RSS}(M_{k_i})` the more likely 

that `k_i` is the secret key. This key ranking method is based 

on the residual sum of squares measure [RSS]_. 

 

INPUT: 

 

- ``C`` -- The ciphertext, a non-empty string. The ciphertext 

must be encoded using the upper-case letters of the English 

alphabet. 

 

- ``pdict`` -- A dictionary of key, possible plaintext pairs. 

This should be the output of :func:`brute_force` with 

``ranking="none"``. 

 

OUTPUT: 

 

- A list ranking the most likely keys first. Each element of the 

list is a tuple of key, possible plaintext pairs. 

 

EXAMPLES: 

 

Use the method of squared differences to rank all possible keys 

and their corresponding decipherment:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: P = S.encoding("Shi."); P 

SHI 

sage: K = 5 

sage: C = S.enciphering(K, P) 

sage: Pdict = S.brute_force(C) 

sage: S.rank_by_squared_differences(C, Pdict) 

<BLANKLINE> 

[(19, ETU), 

(9, ODE), 

(20, DST), 

(5, SHI), 

(8, PEF), 

(4, TIJ), 

(25, YNO), 

(21, CRS), 

(6, RGH), 

(10, NCD), 

(12, LAB), 

(23, APQ), 

(24, ZOP), 

(0, XMN), 

(13, KZA), 

(15, IXY), 

(1, WLM), 

(16, HWX), 

(22, BQR), 

(11, MBC), 

(18, FUV), 

(2, VKL), 

(17, GVW), 

(7, QFG), 

(3, UJK), 

(14, JYZ)] 

 

As more ciphertext is available, the reliability of the squared 

differences ranking function increases:: 

 

sage: P = S.encoding("Shift cipher."); P 

SHIFTCIPHER 

sage: C = S.enciphering(K, P) 

sage: Pdict = S.brute_force(C) 

sage: S.rank_by_squared_differences(C, Pdict) 

<BLANKLINE> 

[(20, DSTQENTASPC), 

(5, SHIFTCIPHER), 

(9, ODEBPYELDAN), 

(19, ETURFOUBTQD), 

(6, RGHESBHOGDQ), 

(16, HWXUIRXEWTG), 

(8, PEFCQZFMEBO), 

(21, CRSPDMSZROB), 

(22, BQROCLRYQNA), 

(25, YNOLZIOVNKX), 

(3, UJKHVEKRJGT), 

(18, FUVSGPVCURE), 

(4, TIJGUDJQIFS), 

(10, NCDAOXDKCZM), 

(7, QFGDRAGNFCP), 

(24, ZOPMAJPWOLY), 

(2, VKLIWFLSKHU), 

(12, LABYMVBIAXK), 

(17, GVWTHQWDVSF), 

(1, WLMJXGMTLIV), 

(13, KZAXLUAHZWJ), 

(0, XMNKYHNUMJW), 

(15, IXYVJSYFXUH), 

(14, JYZWKTZGYVI), 

(11, MBCZNWCJBYL), 

(23, APQNBKQXPMZ)] 

 

TESTS: 

 

The ciphertext cannot be an empty string:: 

 

sage: S.rank_by_squared_differences("", Pdict) 

Traceback (most recent call last): 

... 

AttributeError: 'str' object has no attribute 'parent' 

sage: S.rank_by_squared_differences(S.encoding(""), Pdict) 

Traceback (most recent call last): 

... 

ValueError: The ciphertext must be a non-empty string. 

sage: S.rank_by_squared_differences(S.encoding(" "), Pdict) 

Traceback (most recent call last): 

... 

ValueError: The ciphertext must be a non-empty string. 

 

The ciphertext must be encoded using the capital letters of the 

English alphabet as implemented in 

:func:`AlphabeticStrings() 

<sage.monoids.string_monoid.AlphabeticStrings>`:: 

 

sage: H = HexadecimalStrings() 

sage: S.rank_by_squared_differences(H.encoding("shift"), Pdict) 

Traceback (most recent call last): 

... 

TypeError: The ciphertext must be capital letters of the English alphabet. 

sage: B = BinaryStrings() 

sage: S.rank_by_squared_differences(B.encoding("shift"), Pdict) 

Traceback (most recent call last): 

... 

TypeError: The ciphertext must be capital letters of the English alphabet. 

 

The dictionary ``pdict`` cannot be empty:: 

 

sage: S.rank_by_squared_differences(C, {}) 

Traceback (most recent call last): 

... 

KeyError: 0 

""" 

# NOTE: the code in this method is very similar to that in the 

# method rank_by_chi_square(). The only difference here is the 

# line that computes the list RMk. 

 

# sanity check 

from sage.monoids.string_monoid import ( 

AlphabeticStringMonoid, 

AlphabeticStrings) 

if not isinstance(C.parent(), AlphabeticStringMonoid): 

raise TypeError("The ciphertext must be capital letters of the English alphabet.") 

if str(C) == "": 

raise ValueError("The ciphertext must be a non-empty string.") 

 

# compute the rank of each key 

AS = AlphabeticStrings() 

# the alphabet in question 

Alph = self.encoding("".join([str(e) for e in AS.gens()])) 

StrAlph = str(Alph) 

# message length 

L = len(C) 

# expected frequency tally 

EA = AS.characteristic_frequency() 

for e in EA: 

EA[e] *= L 

# the rank R(M, k) of M for each key 

Rank = [] 

for key in range(self.alphabet_size()): 

# observed frequency tally 

OM = pdict[key].frequency_distribution().function() 

for e in Alph: 

if e in OM: 

OM[e] *= L 

else: 

OM.setdefault(e, 0.0) 

# the rank R(M, K) of M with shift key k 

RMk = [(OM[AS(e)] - EA[e])**2 for e in StrAlph] 

Rank.append((sum(RMk), key)) 

# Sort in non-decreasing order of squared-differences statistic. It's 

# possible that two different keys share the same squared-differences 

# statistic. 

Rank = sorted(Rank) 

RankedList = [] 

# In the following line, the value of val is not used at all, making 

# it redundant to access val in the first place. This line 

# of code is written with readability in mind. 

[RankedList.append((key, pdict[key])) for val, key in Rank] 

return RankedList 

 

def brute_force(self, C, ranking="none"): 

r""" 

Attempt a brute force cryptanalysis of the ciphertext ``C``. 

 

INPUT: 

 

- ``C`` -- A ciphertext over one of the supported alphabets of this 

shift cryptosystem. See the class :class:`ShiftCryptosystem` for 

documentation on the supported alphabets. 

 

- ``ranking`` -- (default ``"none"``) the method to use for 

ranking all possible keys. If ``ranking="none"``, then do not 

use any ranking function. The following ranking functions are 

supported: 

 

- ``"chisquare"`` -- the chi-square ranking function as 

implemented in the method :func:`rank_by_chi_square`. 

 

- ``"squared_differences"`` -- the squared differences ranking 

function as implemented in the method 

:func:`rank_by_squared_differences`. 

 

OUTPUT: 

 

- All the possible plaintext sequences corresponding to the 

ciphertext ``C``. This method effectively uses all the possible 

keys in this shift cryptosystem to decrypt ``C``. The method is 

also referred to as exhaustive key search. The output is 

a dictionary of key, plaintext pairs. 

 

EXAMPLES: 

 

Cryptanalyze using all possible keys for various alphabets. Over 

the upper-case letters of the English alphabet:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: P = S.encoding("The shift cryptosystem generalizes the Caesar cipher.") 

sage: K = 7 

sage: C = S.enciphering(K, P) 

sage: Dict = S.brute_force(C) 

sage: for k in range(len(Dict)): 

....: if Dict[k] == P: 

....: print("key = " + str(k)) 

key = 7 

 

Over the hexadecimal number system:: 

 

sage: S = ShiftCryptosystem(HexadecimalStrings()) 

sage: P = S.encoding("Encryption & decryption shifts along the alphabet.") 

sage: K = 5 

sage: C = S.enciphering(K, P) 

sage: Dict = S.brute_force(C) 

sage: for k in range(len(Dict)): 

....: if Dict[k] == P: 

....: print("key = " + str(k)) 

key = 5 

 

And over the binary number system:: 

 

sage: S = ShiftCryptosystem(BinaryStrings()) 

sage: P = S.encoding("The binary alphabet is very insecure.") 

sage: K = 1 

sage: C = S.enciphering(K, P) 

sage: Dict = S.brute_force(C) 

sage: for k in range(len(Dict)): 

....: if Dict[k] == P: 

....: print("key = " + str(k)) 

key = 1 

 

Don't use any ranking functions, i.e. ``ranking="none"``:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: P = S.encoding("Shifting using modular arithmetic.") 

sage: K = 8 

sage: C = S.enciphering(K, P) 

sage: pdict = S.brute_force(C) 

sage: sorted(pdict.items()) 

<BLANKLINE> 

[(0, APQNBQVOCAQVOUWLCTIZIZQBPUMBQK), 

(1, ZOPMAPUNBZPUNTVKBSHYHYPAOTLAPJ), 

(2, YNOLZOTMAYOTMSUJARGXGXOZNSKZOI), 

(3, XMNKYNSLZXNSLRTIZQFWFWNYMRJYNH), 

(4, WLMJXMRKYWMRKQSHYPEVEVMXLQIXMG), 

(5, VKLIWLQJXVLQJPRGXODUDULWKPHWLF), 

(6, UJKHVKPIWUKPIOQFWNCTCTKVJOGVKE), 

(7, TIJGUJOHVTJOHNPEVMBSBSJUINFUJD), 

(8, SHIFTINGUSINGMODULARARITHMETIC), 

(9, RGHESHMFTRHMFLNCTKZQZQHSGLDSHB), 

(10, QFGDRGLESQGLEKMBSJYPYPGRFKCRGA), 

(11, PEFCQFKDRPFKDJLARIXOXOFQEJBQFZ), 

(12, ODEBPEJCQOEJCIKZQHWNWNEPDIAPEY), 

(13, NCDAODIBPNDIBHJYPGVMVMDOCHZODX), 

(14, MBCZNCHAOMCHAGIXOFULULCNBGYNCW), 

(15, LABYMBGZNLBGZFHWNETKTKBMAFXMBV), 

(16, KZAXLAFYMKAFYEGVMDSJSJALZEWLAU), 

(17, JYZWKZEXLJZEXDFULCRIRIZKYDVKZT), 

(18, IXYVJYDWKIYDWCETKBQHQHYJXCUJYS), 

(19, HWXUIXCVJHXCVBDSJAPGPGXIWBTIXR), 

(20, GVWTHWBUIGWBUACRIZOFOFWHVASHWQ), 

(21, FUVSGVATHFVATZBQHYNENEVGUZRGVP), 

(22, ETURFUZSGEUZSYAPGXMDMDUFTYQFUO), 

(23, DSTQETYRFDTYRXZOFWLCLCTESXPETN), 

(24, CRSPDSXQECSXQWYNEVKBKBSDRWODSM), 

(25, BQROCRWPDBRWPVXMDUJAJARCQVNCRL)] 

 

Use the chi-square ranking function, i.e. ``ranking="chisquare"``:: 

 

sage: S.brute_force(C, ranking="chisquare") 

<BLANKLINE> 

[(8, SHIFTINGUSINGMODULARARITHMETIC), 

(14, MBCZNCHAOMCHAGIXOFULULCNBGYNCW), 

(20, GVWTHWBUIGWBUACRIZOFOFWHVASHWQ), 

(13, NCDAODIBPNDIBHJYPGVMVMDOCHZODX), 

(1, ZOPMAPUNBZPUNTVKBSHYHYPAOTLAPJ), 

(23, DSTQETYRFDTYRXZOFWLCLCTESXPETN), 

(10, QFGDRGLESQGLEKMBSJYPYPGRFKCRGA), 

(6, UJKHVKPIWUKPIOQFWNCTCTKVJOGVKE), 

(22, ETURFUZSGEUZSYAPGXMDMDUFTYQFUO), 

(15, LABYMBGZNLBGZFHWNETKTKBMAFXMBV), 

(12, ODEBPEJCQOEJCIKZQHWNWNEPDIAPEY), 

(21, FUVSGVATHFVATZBQHYNENEVGUZRGVP), 

(16, KZAXLAFYMKAFYEGVMDSJSJALZEWLAU), 

(25, BQROCRWPDBRWPVXMDUJAJARCQVNCRL), 

(9, RGHESHMFTRHMFLNCTKZQZQHSGLDSHB), 

(24, CRSPDSXQECSXQWYNEVKBKBSDRWODSM), 

(3, XMNKYNSLZXNSLRTIZQFWFWNYMRJYNH), 

(5, VKLIWLQJXVLQJPRGXODUDULWKPHWLF), 

(7, TIJGUJOHVTJOHNPEVMBSBSJUINFUJD), 

(2, YNOLZOTMAYOTMSUJARGXGXOZNSKZOI), 

(18, IXYVJYDWKIYDWCETKBQHQHYJXCUJYS), 

(4, WLMJXMRKYWMRKQSHYPEVEVMXLQIXMG), 

(11, PEFCQFKDRPFKDJLARIXOXOFQEJBQFZ), 

(19, HWXUIXCVJHXCVBDSJAPGPGXIWBTIXR), 

(0, APQNBQVOCAQVOUWLCTIZIZQBPUMBQK), 

(17, JYZWKZEXLJZEXDFULCRIRIZKYDVKZT)] 

 

Use the squared differences ranking function, i.e. 

``ranking="squared_differences"``:: 

 

sage: S.brute_force(C, ranking="squared_differences") 

<BLANKLINE> 

[(8, SHIFTINGUSINGMODULARARITHMETIC), 

(23, DSTQETYRFDTYRXZOFWLCLCTESXPETN), 

(12, ODEBPEJCQOEJCIKZQHWNWNEPDIAPEY), 

(2, YNOLZOTMAYOTMSUJARGXGXOZNSKZOI), 

(9, RGHESHMFTRHMFLNCTKZQZQHSGLDSHB), 

(7, TIJGUJOHVTJOHNPEVMBSBSJUINFUJD), 

(21, FUVSGVATHFVATZBQHYNENEVGUZRGVP), 

(22, ETURFUZSGEUZSYAPGXMDMDUFTYQFUO), 

(1, ZOPMAPUNBZPUNTVKBSHYHYPAOTLAPJ), 

(16, KZAXLAFYMKAFYEGVMDSJSJALZEWLAU), 

(20, GVWTHWBUIGWBUACRIZOFOFWHVASHWQ), 

(24, CRSPDSXQECSXQWYNEVKBKBSDRWODSM), 

(14, MBCZNCHAOMCHAGIXOFULULCNBGYNCW), 

(13, NCDAODIBPNDIBHJYPGVMVMDOCHZODX), 

(3, XMNKYNSLZXNSLRTIZQFWFWNYMRJYNH), 

(10, QFGDRGLESQGLEKMBSJYPYPGRFKCRGA), 

(15, LABYMBGZNLBGZFHWNETKTKBMAFXMBV), 

(6, UJKHVKPIWUKPIOQFWNCTCTKVJOGVKE), 

(11, PEFCQFKDRPFKDJLARIXOXOFQEJBQFZ), 

(25, BQROCRWPDBRWPVXMDUJAJARCQVNCRL), 

(17, JYZWKZEXLJZEXDFULCRIRIZKYDVKZT), 

(19, HWXUIXCVJHXCVBDSJAPGPGXIWBTIXR), 

(4, WLMJXMRKYWMRKQSHYPEVEVMXLQIXMG), 

(0, APQNBQVOCAQVOUWLCTIZIZQBPUMBQK), 

(18, IXYVJYDWKIYDWCETKBQHQHYJXCUJYS), 

(5, VKLIWLQJXVLQJPRGXODUDULWKPHWLF)] 

 

TESTS: 

 

Currently, the octal number system is not supported as an alphabet for 

this shift cryptosystem:: 

 

sage: SA = ShiftCryptosystem(AlphabeticStrings()) 

sage: OctStr = OctalStrings() 

sage: C = OctStr([1, 2, 3]) 

sage: SA.brute_force(C) 

Traceback (most recent call last): 

... 

TypeError: ciphertext must be encoded using one of the supported cipher domains of this shift cryptosystem. 

 

Nor is the radix-64 alphabet supported:: 

 

sage: Rad64 = Radix64Strings() 

sage: C = Rad64([1, 2, 3]) 

sage: SA.brute_force(C) 

Traceback (most recent call last): 

... 

TypeError: ciphertext must be encoded using one of the supported cipher domains of this shift cryptosystem. 

""" 

# Sanity check: ensure that C is encoded using one of the 

# supported alphabets of this shift cryptosystem. 

from sage.monoids.string_monoid import ( 

AlphabeticStringMonoid, 

BinaryStringMonoid, 

HexadecimalStringMonoid) 

if not isinstance(C.parent(), ( 

AlphabeticStringMonoid, 

BinaryStringMonoid, 

HexadecimalStringMonoid)): 

raise TypeError("ciphertext must be encoded using one of the supported cipher domains of this shift cryptosystem.") 

ranking_functions = ["none", "chisquare", "squared_differences"] 

if ranking not in ranking_functions: 

raise ValueError("Keyword 'ranking' must be either 'none', 'chisquare', or 'squared_differences'.") 

 

# Now do the actual task of cryptanalysis by means of exhaustive key 

# search, also known as the brute force method. 

# let D be a dictionary of key/plaintext pairs 

D = {} 

 

# NOTE: This loop is a good candidate for loop unrolling. Unless we 

# can justify that this block of code is a bottleneck on the runtime 

# of the method, we should leave it as is. For the alphabets that 

# are supported by this shift cryptosystem, it can be a waste of 

# time optimizing the code when the largest alphabet size is less 

# than 100. 

for k in range(self.alphabet_size()): 

D.setdefault(k, self.deciphering(k, C)) 

 

if ranking == "none": 

return D 

if ranking == "chisquare": 

return self.rank_by_chi_square(C, D) 

if ranking == "squared_differences": 

return self.rank_by_squared_differences(C, D) 

 

def deciphering(self, K, C): 

r""" 

Decrypt the ciphertext ``C`` with the key ``K`` using shift cipher 

decryption. 

 

INPUT: 

 

- ``K`` -- a secret key; a key belonging to the key space of this 

shift cipher. This key is an integer `k` satisfying the inequality 

`0 \leq k < n`, where `n` is the size of the cipher domain. 

 

- ``C`` -- a string of ciphertext; possibly an empty string. 

Characters in this string must be encoded using one of the 

supported alphabets. See the method :func:`encoding()` 

for more information. 

 

OUTPUT: 

 

- The plaintext corresponding to the ciphertext ``C``. 

 

EXAMPLES: 

 

Let's perform decryption over the supported alphabets. Here is 

decryption over the capital letters of the English alphabet:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: P = S.encoding("Stop shifting me."); P 

STOPSHIFTINGME 

sage: K = 13 

sage: C = S.enciphering(K, P); C 

FGBCFUVSGVATZR 

sage: S.deciphering(K, C) == P 

True 

 

Decryption over the hexadecimal number system:: 

 

sage: S = ShiftCryptosystem(HexadecimalStrings()) 

sage: P = S.encoding("Shift me now."); P 

5368696674206d65206e6f772e 

sage: K = 7 

sage: C = S.enciphering(K, P); C 

cadfd0ddeb97d4dc97d5d6ee95 

sage: S.deciphering(K, C) == P 

True 

 

Decryption over the binary number system:: 

 

sage: S = ShiftCryptosystem(BinaryStrings()) 

sage: P = S.encoding("OK, enough shifting."); P 

0100111101001011001011000010000001100101011011100110111101110101011001110110100000100000011100110110100001101001011001100111010001101001011011100110011100101110 

sage: K = 1 

sage: C = S.enciphering(K, P); C 

1011000010110100110100111101111110011010100100011001000010001010100110001001011111011111100011001001011110010110100110011000101110010110100100011001100011010001 

sage: S.deciphering(K, C) == P 

True 

""" 

E = self(self.inverse_key(K)) 

return E(C) 

 

def enciphering(self, K, P): 

r""" 

Encrypt the plaintext ``P`` with the key ``K`` using shift cipher 

encryption. 

 

INPUT: 

 

- ``K`` -- a key belonging to the key space of this shift cipher. 

This key is an integer `k` satisfying the inequality 

`0 \leq k < n`, where `n` is the size of the cipher domain. 

 

- ``P`` -- a string of plaintext; possibly an empty string. 

Characters in this string must be encoded using one of the 

supported alphabets. See the method :func:`encoding()` for more 

information. 

 

OUTPUT: 

 

- The ciphertext corresponding to the plaintext ``P``. 

 

EXAMPLES: 

 

Let's perform encryption over the supported alphabets. Here is 

encryption over the capital letters of the English alphabet:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: P = S.encoding("Shift your gear."); P 

SHIFTYOURGEAR 

sage: K = 3 

sage: S.enciphering(K, P) 

VKLIWBRXUJHDU 

 

Encryption over the hexadecimal number system:: 

 

sage: S = ShiftCryptosystem(HexadecimalStrings()) 

sage: P = S.encoding("Capitalize with the shift key."); P 

4361706974616c697a65207769746820746865207368696674206b65792e 

sage: K = 5 

sage: S.enciphering(K, P) 

98b6c5bec9b6b1becfba75ccbec9bd75c9bdba75c8bdbebbc975b0bace73 

 

Encryption over the binary number system:: 

 

sage: S = ShiftCryptosystem(BinaryStrings()) 

sage: P = S.encoding("Don't shift."); P 

010001000110111101101110001001110111010000100000011100110110100001101001011001100111010000101110 

sage: K = 1 

sage: S.enciphering(K, P) 

101110111001000010010001110110001000101111011111100011001001011110010110100110011000101111010001 

""" 

E = self(K) 

return E(P) 

 

def encoding(self, S): 

r""" 

The encoding of the string ``S`` over the string monoid of this 

shift cipher. For example, if the string monoid of this cryptosystem 

is 

:class:`AlphabeticStringMonoid <sage.monoids.string_monoid.AlphabeticStringMonoid>`, 

then the encoding of ``S`` would be its upper-case equivalent 

stripped of all non-alphabetic characters. The following alphabets 

are supported for the shift cipher: 

 

- capital letters of the English alphabet as implemented in 

:func:`AlphabeticStrings() <sage.monoids.string_monoid.AlphabeticStrings>` 

 

- the alphabet consisting of the hexadecimal number system as 

implemented in 

:func:`HexadecimalStrings() <sage.monoids.string_monoid.HexadecimalStrings>` 

 

- the alphabet consisting of the binary number system as implemented in 

:func:`BinaryStrings() <sage.monoids.string_monoid.BinaryStrings>` 

 

INPUT: 

 

- ``S`` -- a string, possibly empty. 

 

OUTPUT: 

 

- The encoding of ``S`` over the string monoid of this cryptosystem. 

If ``S`` is an empty string, return an empty string. 

 

EXAMPLES: 

 

Encoding over the upper-case letters of the English alphabet:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: S.encoding("Shift cipher on capital letters of the English alphabet.") 

SHIFTCIPHERONCAPITALLETTERSOFTHEENGLISHALPHABET 

 

Encoding over the binary system:: 

 

sage: S = ShiftCryptosystem(BinaryStrings()) 

sage: S.encoding("Binary") 

010000100110100101101110011000010111001001111001 

 

Encoding over the hexadecimal system:: 

 

sage: S = ShiftCryptosystem(HexadecimalStrings()) 

sage: S.encoding("Over hexadecimal system.") 

4f7665722068657861646563696d616c2073797374656d2e 

 

The argument ``S`` can be an empty string, in which case an empty 

string is returned:: 

 

sage: ShiftCryptosystem(AlphabeticStrings()).encoding("") 

<BLANKLINE> 

sage: ShiftCryptosystem(HexadecimalStrings()).encoding("") 

<BLANKLINE> 

sage: ShiftCryptosystem(BinaryStrings()).encoding("") 

<BLANKLINE> 

""" 

D = self.cipher_domain() 

if isinstance(D, AlphabeticStringMonoid): 

return D(strip_encoding(S)) 

try: 

return D.encoding(S) 

except Exception: 

raise TypeError("Argument S = %s does not encode in the cipher domain" % S) 

 

def inverse_key(self, K): 

r""" 

The inverse key corresponding to the key ``K``. For the shift cipher, 

the inverse key corresponding to ``K`` is `-K \bmod n`, where 

`n > 0` is the size of the cipher domain, i.e. the 

plaintext/ciphertext space. A key `k` of the shift cipher is an 

integer `0 \leq k < n`. The key `k = 0` has no effect on either the 

plaintext or the ciphertext. 

 

INPUT: 

 

- ``K`` -- a key for this shift cipher. This must be an integer `k` 

such that `0 \leq k < n`, where `n` is the size of the cipher domain. 

 

OUTPUT: 

 

- The inverse key corresponding to ``K``. 

 

EXAMPLES: 

 

Some random keys and their respective inverse keys:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: key = S.random_key(); key # random 

2 

sage: S.inverse_key(key) # random 

24 

sage: S = ShiftCryptosystem(HexadecimalStrings()) 

sage: key = S.random_key(); key # random 

12 

sage: S.inverse_key(key) # random 

4 

sage: S = ShiftCryptosystem(BinaryStrings()) 

sage: key = S.random_key(); key # random 

1 

sage: S.inverse_key(key) # random 

1 

sage: key = S.random_key(); key # random 

0 

sage: S.inverse_key(key) # random 

0 

 

Regardless of the value of a key, the addition of the key and its 

inverse must be equal to the alphabet size. This relationship holds 

exactly when the value of the key is non-zero:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: K = S.random_key() 

sage: while K == 0: 

....: K = S.random_key() 

sage: invK = S.inverse_key(K) 

sage: K + invK == S.alphabet_size() 

True 

sage: invK + K == S.alphabet_size() 

True 

sage: K = S.random_key() 

sage: while K != 0: 

....: K = S.random_key() 

sage: invK = S.inverse_key(K) 

sage: K + invK != S.alphabet_size() 

True 

sage: K; invK 

0 

0 

 

TESTS: 

 

The key ``K`` must satisfy the inequality `0 \leq K < n` with `n` 

being the size of the plaintext, ciphertext, and key spaces. For the 

shift cryptosystem, all these spaces are the same alphabet. This 

inequality must be satisfied for each of the supported alphabets. 

The capital letters of the English alphabet:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: S.inverse_key(S.alphabet_size()) 

Traceback (most recent call last): 

... 

ValueError: K (=26) is outside the range of acceptable values for a key of this shift cryptosystem. 

sage: S.inverse_key(-1) 

Traceback (most recent call last): 

... 

ValueError: K (=-1) is outside the range of acceptable values for a key of this shift cryptosystem. 

 

The hexadecimal number system:: 

 

sage: S = ShiftCryptosystem(HexadecimalStrings()) 

sage: S.inverse_key(S.alphabet_size()) 

Traceback (most recent call last): 

... 

ValueError: K (=16) is outside the range of acceptable values for a key of this shift cryptosystem. 

sage: S.inverse_key(-1) 

Traceback (most recent call last): 

... 

ValueError: K (=-1) is outside the range of acceptable values for a key of this shift cryptosystem. 

 

The binary number system:: 

 

sage: S = ShiftCryptosystem(BinaryStrings()) 

sage: S.inverse_key(S.alphabet_size()) 

Traceback (most recent call last): 

... 

ValueError: K (=2) is outside the range of acceptable values for a key of this shift cryptosystem. 

sage: S.inverse_key(-1) 

Traceback (most recent call last): 

... 

ValueError: K (=-1) is outside the range of acceptable values for a key of this shift cryptosystem. 

""" 

# Sanity check: the key K must satisfy the inequality 

# 0 <= K < n with n being the size of the plaintext, ciphertext, and 

# key spaces. For the shift cryptosystem, all these spaces are the 

# same alphabet. 

if 0 <= K < self.alphabet_size(): 

# Let A be the alphabet of this cryptosystem and let n be the 

# number of elements in A. If k is a key, then the corresponding 

# inverse key is -k mod n. 

return self.key_space()(-Integer(K)).lift() 

else: 

raise ValueError("K (=%s) is outside the range of acceptable values for a key of this shift cryptosystem." % K) 

 

def random_key(self): 

r""" 

Generate a random key within the key space of this shift cipher. 

The generated key is an integer `0 \leq k < n` with `n` being the 

size of the cipher domain. Thus there are `n` possible keys in the 

key space, which is the set `\ZZ / n\ZZ`. The key `k = 0` has no 

effect on either the plaintext or the ciphertext. 

 

OUTPUT: 

 

- A random key within the key space of this shift cryptosystem. 

 

EXAMPLES:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: S.random_key() # random 

18 

sage: S = ShiftCryptosystem(BinaryStrings()) 

sage: S.random_key() # random 

0 

sage: S = ShiftCryptosystem(HexadecimalStrings()) 

sage: S.random_key() # random 

5 

 

Regardless of the value of a key, the addition of the key and its 

inverse must be equal to the alphabet size. This relationship holds 

exactly when the value of the key is non-zero:: 

 

sage: S = ShiftCryptosystem(AlphabeticStrings()) 

sage: K = S.random_key() 

sage: while K == 0: 

....: K = S.random_key() 

sage: invK = S.inverse_key(K) 

sage: K + invK == S.alphabet_size() 

True 

sage: invK + K == S.alphabet_size() 

True 

sage: K = S.random_key() 

sage: while K != 0: 

....: K = S.random_key() 

sage: invK = S.inverse_key(K) 

sage: K + invK != S.alphabet_size() 

True 

sage: K; invK 

0 

0 

""" 

# Return a random element in ZZ/nZZ where n is the number of elements 

# in the plaintext/ciphertext alphabet and key space. 

from sage.misc.prandom import randint 

return Integer(randint(0, self.alphabet_size() - 1)) 

 

class SubstitutionCryptosystem(SymmetricKeyCryptosystem): 

""" 

Create a substitution cryptosystem. 

 

INPUT: 

 

- ``S`` - a string monoid over some alphabet 

 

OUTPUT: 

 

- A substitution cryptosystem over the alphabet ``S``. 

 

EXAMPLES:: 

 

sage: M = AlphabeticStrings() 

sage: E = SubstitutionCryptosystem(M) 

sage: E 

Substitution cryptosystem on Free alphabetic string monoid on A-Z 

sage: K = M([ 25-i for i in range(26) ]) 

sage: K 

ZYXWVUTSRQPONMLKJIHGFEDCBA 

sage: e = E(K) 

sage: m = M("THECATINTHEHAT") 

sage: e(m) 

GSVXZGRMGSVSZG 

 

TESTS:: 

 

sage: M = AlphabeticStrings() 

sage: E = SubstitutionCryptosystem(M) 

sage: E == loads(dumps(E)) 

True 

""" 

 

def __init__(self, S): 

""" 

See ``SubstitutionCryptosystem`` for full documentation. 

 

EXAMPLES:: 

 

sage: M = AlphabeticStrings() 

sage: E = SubstitutionCryptosystem(M) 

sage: E 

Substitution cryptosystem on Free alphabetic string monoid on A-Z 

""" 

if not isinstance(S, StringMonoid_class): 

raise TypeError("S (= %s) must be a string monoid." % S) 

SymmetricKeyCryptosystem.__init__(self, S, S, S) 

 

def __call__(self, K): 

""" 

Create a substitution cipher. 

 

INPUT: 

 

- ``K`` - a key which is a permutation of the cryptosystem alphabet 

 

EXAMPLES:: 

 

sage: M = AlphabeticStrings() 

sage: E = SubstitutionCryptosystem(M) 

sage: E 

Substitution cryptosystem on Free alphabetic string monoid on A-Z 

sage: K = M([ 25-i for i in range(26) ]) 

sage: K 

ZYXWVUTSRQPONMLKJIHGFEDCBA 

sage: e = E(K) 

sage: m = M("THECATINTHEHAT") 

sage: e(m) 

GSVXZGRMGSVSZG 

""" 

if not isinstance(K, StringMonoidElement): 

raise TypeError("K (= %s) must be a string." % K) 

if K.parent() != self.key_space(): 

raise TypeError("K (= %s) must be a string in the key space." % K) 

return SubstitutionCipher(self, K) 

 

def _repr_(self): 

""" 

Return a string representation of self. 

 

EXAMPLES:: 

 

sage: A = AlphabeticStrings() 

sage: S = SubstitutionCryptosystem(A) 

sage: S 

Substitution cryptosystem on Free alphabetic string monoid on A-Z 

sage: S._repr_() 

'Substitution cryptosystem on Free alphabetic string monoid on A-Z' 

""" 

return "Substitution cryptosystem on %s" % self.cipher_domain() 

 

def random_key(self): 

""" 

Generate a random key within the key space of this substitution 

cipher. The generated key is a permutation of the cryptosystem 

alphabet. Let `n` be the length of the alphabet. Then there are 

`n!` possible keys in the key space. 

 

OUTPUT: 

 

- A random key within the key space of this cryptosystem. 

 

EXAMPLES:: 

 

sage: A = AlphabeticStrings() 

sage: S = SubstitutionCryptosystem(A) 

sage: K = S.random_key() 

sage: Ki = S.inverse_key(K) 

sage: M = "THECATINTHEHAT" 

sage: e = S(K) 

sage: d = S(Ki) 

sage: d(e(A(M))) == A(M) 

True 

""" 

from sage.combinat.permutation import Permutations 

S = self.cipher_domain() 

n = S.ngens() 

I = Permutations(n).random_element() 

return S([ i-1 for i in I ]) 

 

def inverse_key(self, K): 

""" 

The inverse key corresponding to the key ``K``. The specified key is a 

permutation of the cryptosystem alphabet. 

 

INPUT: 

 

- ``K`` - a key belonging to the key space of this cryptosystem 

 

OUTPUT: 

 

- The inverse key of ``K``. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = SubstitutionCryptosystem(S) 

sage: K = E.random_key() 

sage: L = E.inverse_key(K) 

sage: M = S("THECATINTHEHAT") 

sage: e = E(K) 

sage: c = E(L) 

sage: c(e(M)) 

THECATINTHEHAT 

""" 

I = K._element_list 

S = self.cipher_domain() 

n = S.ngens() 

return S([ I.index(i) for i in range(n) ]) 

 

def encoding(self, M): 

""" 

The encoding of the string ``M`` over the string monoid of this 

substitution cipher. For example, if the string monoid of this 

cryptosystem is :class:`AlphabeticStringMonoid`, then the encoding 

of ``M`` would be its upper-case equivalent stripped of all 

non-alphabetic characters. 

 

INPUT: 

 

- ``M`` - a string, possibly empty 

 

OUTPUT: 

 

- The encoding of ``M`` over the string monoid of this cryptosystem. 

 

EXAMPLES:: 

 

sage: M = "Peter Pan(ning) for gold." 

sage: A = AlphabeticStrings() 

sage: S = SubstitutionCryptosystem(A) 

sage: S.encoding(M) == A.encoding(M) 

True 

""" 

S = self.cipher_domain() 

if isinstance(S, AlphabeticStringMonoid): 

return S(strip_encoding(M)) 

try: 

return S.encoding(M) 

except Exception: 

raise TypeError("Argument M = %s does not encode in the cipher domain" % M) 

 

def deciphering(self, K, C): 

""" 

Decrypt the ciphertext ``C`` using the key ``K``. 

 

INPUT: 

 

- ``K`` - a key belonging to the key space of this substitution cipher 

 

- ``C`` - a string (possibly empty) over the string monoid of this 

cryptosystem. 

 

OUTPUT: 

 

- The plaintext corresponding to the ciphertext ``C``. 

 

EXAMPLES:: 

 

sage: S = SubstitutionCryptosystem(AlphabeticStrings()) 

sage: K = S.random_key() 

sage: M = S.encoding("Don't substitute me!") 

sage: S.deciphering(K, S.enciphering(K, M)) == M 

True 

""" 

i = self(self.inverse_key(K)) 

return i(C) 

 

def enciphering(self, K, M): 

""" 

Encrypt the plaintext ``M`` using the key ``K``. 

 

INPUT: 

 

- ``K`` - a key belonging to the key space of this substitution cipher 

 

- ``M`` - a string (possibly empty) over the string monoid of this 

cryptosystem. 

 

OUTPUT: 

 

- The ciphertext corresponding to the plaintext ``M``. 

 

EXAMPLES:: 

 

sage: S = SubstitutionCryptosystem(AlphabeticStrings()) 

sage: K = S.random_key() 

sage: M = S.encoding("Don't substitute me.") 

sage: S.deciphering(K, S.enciphering(K, M)) == M 

True 

""" 

e = self(K) 

return e(M) 

 

class TranspositionCryptosystem(SymmetricKeyCryptosystem): 

""" 

Create a transposition cryptosystem of block length ``n``. 

 

INPUT: 

 

- ``S`` - a string monoid over some alphabet 

 

- ``n`` - integer `> 0`; a block length of a block permutation 

 

OUTPUT: 

 

- A transposition cryptosystem of block length ``n`` over the 

alphabet ``S``. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = TranspositionCryptosystem(S,14) 

sage: E 

Transposition cryptosystem on Free alphabetic string monoid on A-Z of block length 14 

sage: K = [ 14-i for i in range(14) ] 

sage: K 

[14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

sage: e = E(K) 

sage: e(S("THECATINTHEHAT")) 

TAHEHTNITACEHT 

 

TESTS:: 

 

sage: S = AlphabeticStrings() 

sage: E = TranspositionCryptosystem(S,14) 

sage: E == loads(dumps(E)) 

True 

""" 

 

def __init__(self, S, n): 

""" 

See ``TranspositionCryptosystem`` for full documentation. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = TranspositionCryptosystem(S,14) 

sage: E 

Transposition cryptosystem on Free alphabetic string monoid on A-Z of block length 14 

""" 

if not isinstance(S, StringMonoid_class): 

raise TypeError("S (= %s) must be a string monoid." % S) 

key_space = SymmetricGroup(n) 

SymmetricKeyCryptosystem.__init__(self, S, S, key_space, block_length=n) 

 

def __call__(self, K): 

""" 

Create a transposition cipher. 

 

INPUT: 

 

- ``K`` - a key which specifies a block permutation 

 

EXAMPLES:: 

 

sage: M = AlphabeticStrings() 

sage: E = TranspositionCryptosystem(M,14) 

sage: E 

Transposition cryptosystem on Free alphabetic string monoid on A-Z of block length 14 

sage: K = [ 14-i for i in range(14) ] 

sage: K 

[14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] 

sage: e = E(K) 

sage: m = M("THECATINTHEHAT") 

sage: e(m) 

TAHEHTNITACEHT 

""" 

G = self.key_space() 

if isinstance(K, list): 

try: 

K = G(K) 

except Exception: 

raise TypeError("K (= %s) must specify a permutation." % K) 

if not isinstance(K, PermutationGroupElement) and K.parent() == G: 

raise TypeError("K (= %s) must be a permutation or list specifying a permutation." % K) 

return TranspositionCipher(self, K) 

 

def _repr_(self): 

""" 

Return a string representation of self. 

 

EXAMPLES:: 

 

sage: A = AlphabeticStrings() 

sage: T = TranspositionCryptosystem(A, 14) 

sage: T 

Transposition cryptosystem on Free alphabetic string monoid on A-Z of block length 14 

sage: T._repr_() 

'Transposition cryptosystem on Free alphabetic string monoid on A-Z of block length 14' 

""" 

return "Transposition cryptosystem on %s of block length %s" % ( 

self.cipher_domain(), self.block_length()) 

 

def random_key(self): 

""" 

Generate a random key within the key space of this transposition 

cryptosystem. Let `n > 0` be the block length of this cryptosystem. 

Then there are `n!` possible keys. 

 

OUTPUT: 

 

- A random key within the key space of this cryptosystem. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = TranspositionCryptosystem(S, 14) 

sage: K = E.random_key() 

sage: Ki = E.inverse_key(K) 

sage: e = E(K) 

sage: d = E(Ki) 

sage: M = "THECATINTHEHAT" 

sage: C = e(S(M)) 

sage: d(S(C)) == S(M) 

True 

""" 

n = self.block_length() 

return SymmetricGroup(n).random_element() 

 

def inverse_key(self, K, check=True): 

""" 

The inverse key corresponding to the key ``K``. 

 

INPUT: 

 

- ``K`` - a key belonging to the key space of this transposition 

cipher 

 

- ``check`` - bool (default: ``True``); check that ``K`` belongs to 

the key space of this cryptosystem. 

 

OUTPUT: 

 

- The inverse key corresponding to ``K``. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = TranspositionCryptosystem(S, 14) 

sage: K = E.random_key() 

sage: Ki = E.inverse_key(K) 

sage: e = E(K) 

sage: d = E(Ki) 

sage: M = "THECATINTHEHAT" 

sage: C = e(S(M)) 

sage: d(S(C)) == S(M) 

True 

""" 

if check: 

if not K in self.key_space(): 

raise TypeError("Argument K (= %s) is not in the key space." % K) 

return K**-1 

 

def encoding(self, M): 

""" 

The encoding of the string ``M`` over the string monoid of this 

transposition cipher. For example, if the string monoid of this 

cryptosystem is :class:`AlphabeticStringMonoid`, then the encoding 

of ``M`` would be its upper-case equivalent stripped of all 

non-alphabetic characters. 

 

INPUT: 

 

- ``M`` - a string, possibly empty 

 

OUTPUT: 

 

- The encoding of ``M`` over the string monoid of this cryptosystem. 

 

EXAMPLES:: 

 

sage: M = "Transposition cipher is not about matrix transpose." 

sage: A = AlphabeticStrings() 

sage: T = TranspositionCryptosystem(A, 11) 

sage: T.encoding(M) == A.encoding(M) 

True 

""" 

S = self.cipher_domain() 

if isinstance(S, AlphabeticStringMonoid): 

return S(strip_encoding(M)) 

try: 

return S.encoding(M) 

except Exception: 

raise TypeError("Argument M = %s does not encode in the cipher domain" % M) 

 

def deciphering(self, K, C): 

""" 

Decrypt the ciphertext ``C`` using the key ``K``. 

 

INPUT: 

 

- ``K`` - a key belonging to the key space of this transposition 

cipher 

 

- ``C`` - a string (possibly empty) over the string monoid of this 

cryptosystem. 

 

OUTPUT: 

 

- The plaintext corresponding to the ciphertext ``C``. 

 

EXAMPLES:: 

 

sage: T = TranspositionCryptosystem(AlphabeticStrings(), 14) 

sage: K = T.random_key() 

sage: M = T.encoding("The cat in the hat.") 

sage: T.deciphering(K, T.enciphering(K, M)) == M 

True 

""" 

i = self(self.inverse_key(K)) 

return i(C) 

 

def enciphering(self, K, M): 

""" 

Encrypt the plaintext ``M`` using the key ``K``. 

 

INPUT: 

 

- ``K`` - a key belonging to the key space of this transposition 

cipher 

 

- ``M`` - a string (possibly empty) over the string monoid of this 

cryptosystem 

 

OUTPUT: 

 

- The ciphertext corresponding to the plaintext ``M``. 

 

EXAMPLES:: 

 

sage: T = TranspositionCryptosystem(AlphabeticStrings(), 14) 

sage: K = T.random_key() 

sage: M = T.encoding("The cat in the hat.") 

sage: T.deciphering(K, T.enciphering(K, M)) == M 

True 

""" 

e = self(K) 

return e(M) 

 

class VigenereCryptosystem(SymmetricKeyCryptosystem): 

""" 

Create a Vigenere cryptosystem of block length ``n``. 

 

INPUT: 

 

- ``S``-- a string monoid over some alphabet 

 

- ``n`` - integer `> 0`; block length of an encryption/decryption key 

 

OUTPUT: 

 

- A Vigenere cryptosystem of block length ``n`` over the alphabet 

``S``. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = VigenereCryptosystem(S,14) 

sage: E 

Vigenere cryptosystem on Free alphabetic string monoid on A-Z of period 14 

sage: K = S('ABCDEFGHIJKLMN') 

sage: K 

ABCDEFGHIJKLMN 

sage: e = E(K) 

sage: e 

Cipher on Free alphabetic string monoid on A-Z 

sage: e(S("THECATINTHEHAT")) 

TIGFEYOUBQOSMG 

 

TESTS:: 

 

sage: S = AlphabeticStrings() 

sage: E = VigenereCryptosystem(S,14) 

sage: E == loads(dumps(E)) 

True 

""" 

 

def __init__(self, S, n): 

""" 

See ``VigenereCryptosystem`` for full documentation. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = VigenereCryptosystem(S,14) 

sage: E 

Vigenere cryptosystem on Free alphabetic string monoid on A-Z of period 14 

""" 

if not isinstance(S, StringMonoid_class): 

raise TypeError("S (= %s) must be a string monoid." % S) 

SymmetricKeyCryptosystem.__init__(self, S, S, S, block_length=1, period=n) 

 

def __call__(self, K): 

""" 

Create a Vigenere cipher. 

 

INPUT: A key which specifies a block permutation. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = VigenereCryptosystem(S,14) 

sage: E 

Vigenere cryptosystem on Free alphabetic string monoid on A-Z of period 14 

sage: K = S('ABCDEFGHIJKLMN') 

sage: K 

ABCDEFGHIJKLMN 

sage: e = E(K) 

sage: e 

Cipher on Free alphabetic string monoid on A-Z 

sage: e(S("THECATINTHEHAT")) 

TIGFEYOUBQOSMG 

""" 

S = self.key_space() 

m = self.period() 

if isinstance(K, list): 

try: 

K = S(K) 

except Exception: 

raise TypeError("K (= %s) must specify a string of length %s." % (K, m)) 

if not len(K) == m: 

raise TypeError("K (= %s) must specify a string of length %s." % (K, m)) 

return VigenereCipher(self, K) 

 

def _repr_(self): 

""" 

Return a string representation of self. 

 

EXAMPLES:: 

 

sage: A = AlphabeticStrings() 

sage: V = VigenereCryptosystem(A, 14) 

sage: V 

Vigenere cryptosystem on Free alphabetic string monoid on A-Z of period 14 

sage: V._repr_() 

'Vigenere cryptosystem on Free alphabetic string monoid on A-Z of period 14' 

""" 

return "Vigenere cryptosystem on %s of period %s" % ( 

self.cipher_domain(), self.period()) 

 

def random_key(self): 

""" 

Generate a random key within the key space of this Vigenere 

cryptosystem. Let `n > 0` be the length of the cryptosystem alphabet 

and let `m > 0` be the block length of this cryptosystem. Then there 

are `n^m` possible keys. 

 

OUTPUT: 

 

- A random key within the key space of this cryptosystem. 

 

EXAMPLES:: 

 

sage: A = AlphabeticStrings() 

sage: V = VigenereCryptosystem(A, 14) 

sage: M = "THECATINTHEHAT" 

sage: K = V.random_key() 

sage: Ki = V.inverse_key(K) 

sage: e = V(K) 

sage: d = V(Ki) 

sage: d(e(A(M))) == A(M) 

True 

""" 

S = self.key_space() 

n = S.ngens() 

m = self.period() 

return S([ randint(0, n-1) for i in range(m) ]) 

 

def inverse_key(self, K): 

""" 

The inverse key corresponding to the key ``K``. 

 

INPUT: 

 

- ``K`` - a key within the key space of this Vigenere cryptosystem 

 

OUTPUT: 

 

- The inverse key corresponding to ``K``. 

 

EXAMPLES:: 

 

sage: S = AlphabeticStrings() 

sage: E = VigenereCryptosystem(S,14) 

sage: K = E.random_key() 

sage: L = E.inverse_key(K) 

sage: M = S("THECATINTHEHAT") 

sage: e = E(K) 

sage: c = E(L) 

sage: c(e(M)) 

THECATINTHEHAT 

""" 

S = self.key_space() 

n = S.ngens() 

return S([ (-i)%(n) for i in K._element_list ]) 

 

def encoding(self, M): 

""" 

The encoding of the string ``M`` over the string monoid of this 

Vigenere cipher. For example, if the string monoid of this 

cryptosystem is :class:`AlphabeticStringMonoid`, then the encoding 

of ``M`` would be its upper-case equivalent stripped of all 

non-alphabetic characters. 

 

INPUT: 

 

- ``M`` - a string, possibly empty 

 

OUTPUT: 

 

- The encoding of ``M`` over the string monoid of this cryptosystem. 

 

EXAMPLES:: 

 

sage: A = AlphabeticStrings() 

sage: V = VigenereCryptosystem(A, 24) 

sage: M = "Jack and Jill went up the hill." 

sage: V.encoding(M) == A.encoding(M) 

True 

""" 

S = self.cipher_domain() 

if isinstance(S, AlphabeticStringMonoid): 

return S(strip_encoding(M)) 

try: 

return S.encoding(M) 

except Exception: 

raise TypeError("Argument M = %s does not encode in the cipher domain" % M) 

 

def deciphering(self, K, C): 

""" 

Decrypt the ciphertext ``C`` using the key ``K``. 

 

INPUT: 

 

- ``K`` - a key belonging to the key space of this Vigenere cipher 

 

- ``C`` - a string (possibly empty) over the string monoid of this 

cryptosystem 

 

OUTPUT: 

 

- The plaintext corresponding to the ciphertext ``C``. 

 

EXAMPLES:: 

 

sage: V = VigenereCryptosystem(AlphabeticStrings(), 24) 

sage: K = V.random_key() 

sage: M = V.encoding("Jack and Jill went up the hill.") 

sage: V.deciphering(K, V.enciphering(K, M)) == M 

True 

""" 

i = self(self.inverse_key(K)) 

return i(C) 

 

def enciphering(self, K, M): 

""" 

Encrypt the plaintext ``M`` using the key ``K``. 

 

INPUT: 

 

- ``K`` - a key belonging to the key space of this Vigenere cipher 

 

- ``M`` - a string (possibly empty) over the string monoid of this 

cryptosystem 

 

OUTPUT: 

 

- The ciphertext corresponding to the plaintext ``M``. 

 

EXAMPLES:: 

 

sage: V = VigenereCryptosystem(AlphabeticStrings(), 24) 

sage: K = V.random_key() 

sage: M = V.encoding("Jack and Jill went up the hill.") 

sage: V.deciphering(K, V.enciphering(K, M)) == M 

True 

""" 

e = self(K) 

return e(M)