第三章 Mooc慕课传统加密技术 Playfair密码的代码实现

实现Playfair密码的实现:

我的答案:

1. 信息(Playfair 密码算法的基本信息)

Playfair 密码是一种古典加密技术,使用一个 5x5 的字母矩阵来加密信息。这个矩阵由一个密钥词填充,剩余的字母按顺序填充到矩阵中,通常省略字母 'J'。

加密过程包括以下步骤:

  • 将明文分为两个字母的一组,必要时在末尾添加一个填充字母(比如 'X')。
  • 对于每对字母,根据它们在矩阵中的位置来确定如何加密:
    • 如果两字母在同一行,则每个字母都用其右侧的字母替换。
    • 如果两字母在同一列,则每个字母都用其下方的字母替换。
    • 如果两字母不在同一行或列,则每个字母都用在相同行且与另一个字母同列的字母替换。

2. 分析

  • 密钥矩阵的生成:我们需要一个函数来根据给定的密钥生成 5x5 的矩阵。
  • 明文处理:明文需要被分割成两个字母的组合,必要时添加填充字母。
  • 加密过程:根据字母对在矩阵中的位置,使用不同的规则进行替换。

3. 算法设计

  • 生成矩阵:创建一个 5x5 矩阵并使用密钥和字母表填充。
  • 处理明文:将明文切分成字母对,必要时添加 'X'。
  • 加密字母对:根据字母对在矩阵中的位置应用加密规则。

4. 代码实现

#include <iostream>
#include <string>
#include <map>
#include <cctype>

using namespace std;

const int size = 5;
char matrix[size][size];

void generateMatrix(const string& key) {
    bool exists[26] = {false};
    int x = 0, y = 0;

    for (char ch : key) {
        if (ch == 'j') continue;
        if (!exists[ch - 'a']) {
            matrix[x][y++] = ch;
            exists[ch - 'a'] = true;
            if (y == size) {
                x++;
                y = 0;
            }
        }
    }

    for (char ch = 'a'; ch <= 'z'; ch++) {
        if (ch == 'j') continue;
        if (!exists[ch - 'a']) {
            matrix[x][y++] = ch;
            exists[ch - 'a'] = true;
            if (y == size) {
                x++;
                y = 0;
            }
        }
    }
}

string formatPlainText(const string& text) {
    string formatted;
    for (int i = 0; i < text.length(); i++) {
        if (text[i] == 'j') formatted += 'i';
        else formatted += text[i];

        if (i < text.length() - 1 && text[i] == text[i + 1])
            formatted += 'x';
    }

    if (formatted.length() % 2 != 0)
        formatted += 'x';

    return formatted;
}

pair<int, int> findPosition(char ch) {
    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if (matrix[i][j] == ch)
                return {i, j};
        }
    }
    return {-1, -1};
}

string encryptPair(char a, char b) {
    pair<int, int> posA = findPosition(a);
    pair<int, int> posB = findPosition(b);
    string encrypted;

    if (posA.first == posB.first) {
        encrypted += matrix[posA.first][(posA.second + 1) % size];
        encrypted += matrix[posB.first][(posB.second + 1) % size];
    } else if (posA.second == posB.second) {
        encrypted += matrix[(posA.first + 1) % size][posA.second];
        encrypted += matrix[(posB.first + 1) % size][posB.second];
    } else {
        encrypted += matrix[posA.first][posB.second];
        encrypted += matrix[posB.first][posA.second];
    }

    return encrypted;
}

string encrypt(const string& text) {
    string encrypted;
    for (int i = 0; i < text.length(); i += 2) {
        encrypted += encryptPair(tolower(text[i]), tolower(text[i + 1]));
    }
    return encrypted;
}

int main() {
    string key, plaintext;
    cout << "Enter key: ";
    cin >> key;
    cout << "Enter plaintext: ";
    cin >> plaintext;

    generateMatrix(key);
    string formattedText = formatPlainText(plaintext);
    string encryptedText = encrypt(formattedText);

    cout << "Encrypted Text: " << encryptedText << endl;

    return 0;
}

5. 可能遇到的问题

  • 密钥处理:确保密钥中没有重复的字母。
  • 明文长度:处理明文长度为奇数的情况。
  • 特殊情况处理:如同行或同列的字母对。

7.验证

爆错了,有哪位读者可以看出哪里错了吗?

答案:问题就出现在我在代码中用了using namespace,在这个库中定义了和我size一样的变量。这是一个推测代码中,错误可能是由于 size 这个名称造成的。size 是一个非常常见的名称,可能在某个库或命名空间中已经定义过了。由于我使用了 using namespace std;,这可能包含了标准库中的 size 名称,与我定义的全局常量 size 冲突。

正确答案:

C++:

#include <iostream>
#include <string>
#include <map>
#include <cctype>

const int matrixSize = 5;
char matrix[matrixSize][matrixSize];

void generateMatrix(const std::string& key) {
    bool exists[26] = {false};
    int x = 0, y = 0;

    for (char ch : key) {
        if (ch == 'j') continue;
        if (!exists[ch - 'a']) {
            matrix[x][y++] = ch;
            exists[ch - 'a'] = true;
            if (y == matrixSize) {
                x++;
                y = 0;
            }
        }
    }

    for (char ch = 'a'; ch <= 'z'; ch++) {
        if (ch == 'j') continue;
        if (!exists[ch - 'a']) {
            matrix[x][y++] = ch;
            exists[ch - 'a'] = true;
            if (y == matrixSize) {
                x++;
                y = 0;
            }
        }
    }
}

std::string formatPlainText(const std::string& text) {
    std::string formatted;
    for (int i = 0; i < text.length(); i++) {
        if (text[i] == 'j') formatted += 'i';
        else formatted += text[i];

        if (i < text.length() - 1 && text[i] == text[i + 1])
            formatted += 'x';
    }

    if (formatted.length() % 2 != 0)
        formatted += 'x';

    return formatted;
}

std::pair<int, int> findPosition(char ch) {
    for (int i = 0; i < matrixSize; i++) {
        for (int j = 0; j < matrixSize; j++) {
            if (matrix[i][j] == ch)
                return {i, j};
        }
    }
    return {-1, -1};
}

std::string encryptPair(char a, char b) {
    std::pair<int, int> posA = findPosition(a);
    std::pair<int, int> posB = findPosition(b);
    std::string encrypted;

    if (posA.first == posB.first) {
        encrypted += matrix[posA.first][(posA.second + 1) % matrixSize];
        encrypted += matrix[posB.first][(posB.second + 1) % matrixSize];
    } else if (posA.second == posB.second) {
        encrypted += matrix[(posA.first + 1) % matrixSize][posA.second];
        encrypted += matrix[(posB.first + 1) % matrixSize][posB.second];
    } else {
        encrypted += matrix[posA.first][posB.second];
        encrypted += matrix[posB.first][posA.second];
    }

    return encrypted;
}

std::string encrypt(const std::string& text) {
    std::string encrypted;
    for (int i = 0; i < text.length(); i += 2) {
        encrypted += encryptPair(std::tolower(text[i]), std::tolower(text[i + 1]));
    }
    return encrypted;
}

int main() {
    std::string key, plaintext;
    std::cout << "Enter key: ";
    std::cin >> key;
    std::cout << "Enter plaintext: ";
    std::cin >> plaintext;

    generateMatrix(key);
    std::string formattedText = formatPlainText(plaintext);
    std::string encryptedText = encrypt(formattedText);

    std::cout << "Encrypted Text: " << encryptedText << std::endl;

    return 0;
}

JAVA(老师给的):





public class PlayfairCipher {

private char[][] keyTable = new char[5][5];
private String key;

public PlayfairCipher(String key) {
this.key = key;
generateKeyTable();
}

private void generateKeyTable() {
boolean[] used = new boolean[26];

//  将密钥中的字母插入到表格中,并标记为已用。
int index = 0;
for (int i = 0; i < key.length(); i++) {
char c = key.charAt(i);
if (c == 'J') {
c = 'I';
}
if (!used[c - 'A']) {
used[c - 'A'] = true;
keyTable[index / 5][index % 5] = c;
index++;
}
}

//  将剩余未用过的字母按顺序插入到表格中。
for (int i = 0; i < 26; i++) {
if (!used[i]) {
char c = (char) ('A' + i);
if (c == 'J') {
continue;
}
keyTable[index / 5][index % 5] = c;
index++;
}
}
}

private String preparePlainText(String plainText) {
//  移除非字母字符并将小写字母转换为大写字母。
StringBuilder sb = new StringBuilder();
for (char c : plainText.toCharArray()) {





if (Character.isLetter(c)) {
if (c == 'j'  || c == 'J') {
sb.append('I');
} else {
sb.append(Character.toUpperCase(c));
}
}
}

//  将重复出现的字母用 X  代替。
for (int i = 1; i < sb.length(); i += 2) {
if (sb.charAt(i) == sb.charAt(i - 1)) {
sb.insert(i, 'X');
}
}

//  如果最后一位是单个字母,则添加 X  作为填充。
if (sb.length() % 2 == 1) {
sb.append('X');
}

return sb.toString();
}

private char[][] preparePairs(String plainText) {
char[][] pairs = new char[plainText.length() / 2][2];
int index = 0;
for (int i = 0; i < plainText.length(); i += 2) {
pairs[index][0] = plainText.charAt(i);
pairs[index][1] = plainText.charAt(i + 1);
index++;
}
return pairs;
}

private char[] findCoords(char c) {
if (c == 'J') {
c = 'I';
}
char[] coords = new char[2];
for (int i = 0; i < 5; i++) {
for (intj = 0; j < 5; j++) {
if (keyTable[i][j] == c) {
coords[0] = (char) i;





coords[1] = (char) j;
return coords;
}
}
}
return null;
}

public String encrypt(String plainText) {
String preparedPlainText = preparePlainText(plainText);
char[][] pairs = preparePairs(preparedPlainText);
StringBuilder cipherText = new StringBuilder();
for (char[] pair : pairs) {
char[] coords1 = findCoords(pair[0]);
char[] coords2 = findCoords(pair[1]);

if (coords1[0] == coords2[0]) {
//  在同一行中寻找加密后的两个字符。
cipherText.append(keyTable[coords1[0]][(coords1[1] + 1) % 5]);
cipherText.append(keyTable[coords2[0]][(coords2[1] + 1) % 5]);
} else if (coords1[1] == coords2[1]) {
//  在同一列中寻找加密后的两个字符。
cipherText.append(keyTable[(coords1[0] + 1) % 5][coords1[1]]);
cipherText.append(keyTable[(coords2[0] + 1) % 5][coords2[1]]);
} else {
//  在矩形中寻找加密后的两个字符。
cipherText.append(keyTable[coords1[0]][coords2[1]]);
cipherText.append(keyTable[coords2[0]][coords1[1]]);
}
}
return cipherText.toString();
}

public String decrypt(String cipherText) {
StringBuilder plainText = new StringBuilder();
char[][] pairs = preparePairs(cipherText);
for (char[] pair : pairs) {
char[] coords1 = findCoords(pair[0]);
char[] coords2 = findCoords(pair[1]);

if (coords1[0] == coords2[0]) {
//  在同一行中寻找解密后的两个字符。
plainText.append(keyTable[coords1[0]][(coords1[1] + 4) % 5]);
plainText.append(keyTable[coords2[0]][(coords2[1] + 4) % 5]);





} else if (coords1[1] == coords2[1]) {
//  在同一列中寻找解密后的两个字符。
plainText.append(keyTable[(coords1[0] + 4) % 5][coords1[1]]);
plainText.append(keyTable[(coords2[0] + 4) % 5][coords2[1]]);
} else {
//  在矩形中寻找解密后的两个字符。
plainText.append(keyTable[coords1[0]][coords2[1]]);
plainText.append(keyTable[coords2[0]][coords1[1]]);
}
}

//  移除填充的 X  字符。
for (int i = plainText.length() - 1; i >= 0; i--) {
if (plainText.charAt(i) == 'X') {
plainText.deleteCharAt(i);
} else {
break;
}
}

return plainText.toString();
}

public static void main(String[] args) {
PlayfairCipher cipher = new PlayfairCipher("SECRETKEY");
String plainText = "The quick brown fox jumps over the lazy dog.";
System.out.println(" 明文: " + plainText);
String cipherText = cipher.encrypt(plainText);
System.out.println("加密后: " + cipherText);
String decryptedText = cipher.decrypt(cipherText);
System.out.println("解密后: " + decryptedText);
}
}

总结: 

  1. 编程语言特性

    • 范围基于的 for 循环:了解现代编程语言中简化数组和容器遍历的高级特性。
    • 数据结构:理解如何使用数组(或其他数据结构)来存储和管理数据。
    • 字符串操作:掌握字符串处理技巧,如拼接、替换和大小写转换等。
  2. 算法实现

    • 理解 Playfair 密码算法的工作原理:学习如何将一个复杂的问题分解成可通过编程解决的子问题。
    • 算法设计:理解如何从头开始设计一个算法,并将其转化为实际的代码。
    • 调试和测试:通过实现和测试算法来练习调试技能,确保程序能正确加密和解密信息。
  3. 密码学基础

    • 古典密码学:了解密码学的基本概念,包括加密和解密过程,以及如何使用密钥。
    • 安全性和限制:了解 Playfair 密码的安全性及其局限性,比如它对已知明文攻击的脆弱性。
  4. 编程实践和原则

    • 代码组织:学习如何组织和结构化代码,使其清晰、模块化,易于理解和维护。
    • 命名约定:明白选择有意义的变量名和函数名对于编写可读代码的重要性。
    • 避免魔法数字:理解为什么使用命名常量比在代码中直接使用数字更好。
  5. 跨语言编程

    • 理解不同语言的语法和范式:通过比较 Java 和 C++ 的不同之处,了解不同编程语言之间的相似之处和差异。
    • 适应新语境:学会如何将在一种语言中学到的概念和技巧转移到另一种语言中。

通过解决这样的问题,你不仅能够提高特定编程语言的技能,还能够获得可转移到其他语言和领域的宝贵经验。此外,你还会对加密和安全通信有更深入的理解,这在当今的数字世界中极为重要。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夏驰和徐策

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值