当前位置:首页 > PHP

php实现playfair

2026-02-14 19:34:12PHP

实现 Playfair 加密算法的 PHP 代码

Playfair 是一种经典的对称加密算法,基于 5x5 的字母矩阵进行加密和解密。以下是一个完整的 PHP 实现示例:

<?php
class PlayfairCipher {
    private $key;
    private $keySquare;

    public function __construct($key) {
        $this->key = strtoupper($key);
        $this->prepareKeySquare();
    }

    private function prepareKeySquare() {
        $key = str_replace('J', 'I', $this->key);
        $key = preg_replace('/[^A-Z]/', '', $key);
        $key = str_split($key);
        $alphabet = range('A', 'Z');
        unset($alphabet[array_search('J', $alphabet)]);

        $this->keySquare = array_unique(array_merge($key, $alphabet));
        $this->keySquare = array_values($this->keySquare);
    }

    private function getPosition($char) {
        $index = array_search($char, $this->keySquare);
        return ['row' => (int)($index / 5), 'col' => $index % 5];
    }

    private function prepareText($text) {
        $text = strtoupper($text);
        $text = preg_replace('/[^A-Z]/', '', $text);
        $text = str_replace('J', 'I', $text);

        $result = '';
        $len = strlen($text);
        for ($i = 0; $i < $len; $i += 2) {
            $a = $text[$i];
            $b = ($i + 1 < $len) ? $text[$i + 1] : 'X';
            if ($a == $b) {
                $b = 'X';
                $i--;
            }
            $result .= $a . $b;
        }
        return $result;
    }

    public function encrypt($plaintext) {
        $text = $this->prepareText($plaintext);
        $ciphertext = '';

        for ($i = 0; $i < strlen($text); $i += 2) {
            $a = $text[$i];
            $b = $text[$i + 1];
            $posA = $this->getPosition($a);
            $posB = $this->getPosition($b);

            if ($posA['row'] == $posB['row']) {
                $ciphertext .= $this->keySquare[$posA['row'] * 5 + (($posA['col'] + 1) % 5)];
                $ciphertext .= $this->keySquare[$posB['row'] * 5 + (($posB['col'] + 1) % 5)];
            } elseif ($posA['col'] == $posB['col']) {
                $ciphertext .= $this->keySquare[(($posA['row'] + 1) % 5) * 5 + $posA['col']];
                $ciphertext .= $this->keySquare[(($posB['row'] + 1) % 5) * 5 + $posB['col']];
            } else {
                $ciphertext .= $this->keySquare[$posA['row'] * 5 + $posB['col']];
                $ciphertext .= $this->keySquare[$posB['row'] * 5 + $posA['col']];
            }
        }
        return $ciphertext;
    }

    public function decrypt($ciphertext) {
        $text = $this->prepareText($ciphertext);
        $plaintext = '';

        for ($i = 0; $i < strlen($text); $i += 2) {
            $a = $text[$i];
            $b = $text[$i + 1];
            $posA = $this->getPosition($a);
            $posB = $this->getPosition($b);

            if ($posA['row'] == $posB['row']) {
                $plaintext .= $this->keySquare[$posA['row'] * 5 + (($posA['col'] - 1 + 5) % 5)];
                $plaintext .= $this->keySquare[$posB['row'] * 5 + (($posB['col'] - 1 + 5) % 5)];
            } elseif ($posA['col'] == $posB['col']) {
                $plaintext .= $this->keySquare[(($posA['row'] - 1 + 5) % 5) * 5 + $posA['col']];
                $plaintext .= $this->keySquare[(($posB['row'] - 1 + 5) % 5) * 5 + $posB['col']];
            } else {
                $plaintext .= $this->keySquare[$posA['row'] * 5 + $posB['col']];
                $plaintext .= $this->keySquare[$posB['row'] * 5 + $posA['col']];
            }
        }
        return $plaintext;
    }
}

// 使用示例
$key = "MONARCHY";
$cipher = new PlayfairCipher($key);

$plaintext = "HELLO WORLD";
$encrypted = $cipher->encrypt($plaintext);
$decrypted = $cipher->decrypt($encrypted);

echo "Plaintext: $plaintext\n";
echo "Encrypted: $encrypted\n";
echo "Decrypted: $decrypted\n";
?>

Playfair 算法关键点说明

加密矩阵构建时,字母 'J' 通常被替换为 'I',矩阵由密钥和剩余字母填充,确保每个字母只出现一次。

明文预处理阶段,需要将文本转换为大写,去除非字母字符,处理重复字母对(插入 'X'),并确保文本长度为偶数。

加密规则分为三种情况:同行字母右移、同列字母下移、矩形对角交换。解密则是相反方向移动。

使用注意事项

密钥应选择足够长度且易记的单词或短语,避免使用包含大量重复字母的密钥。

明文中的 'J' 会被自动转换为 'I',解密后需要根据上下文判断是否需要还原为 'J'。

php实现playfair

对于短文本或特殊字符,可能需要在加密前后进行额外处理以确保数据完整性。

标签: phpplayfair
分享给朋友:

相关文章

php实现打印功能

php实现打印功能

PHP 实现打印功能的方法 PHP 可以通过多种方式实现打印功能,具体取决于打印的目标(如打印机、PDF、网页等)和需求(如直接打印、生成打印预览等)。以下是几种常见的实现方式: 使用 JavaSc…

php 实现自动收货

php 实现自动收货

PHP 实现自动收货功能 自动收货功能通常用于电商系统,在订单超过一定时间未手动确认收货时自动完成订单。以下是实现方法: 数据库设计 需要订单表包含以下关键字段: CREATE TABLE ord…

php登陆功能实现

php登陆功能实现

实现PHP登录功能 数据库准备 创建一个用户表存储登录信息,基本字段包括用户名、密码(需加密)等: CREATE TABLE users ( id INT AUTO_INCREMENT PR…

php数据库实现

php数据库实现

PHP 连接 MySQL 数据库 使用 mysqli 扩展连接 MySQL 数据库: <?php $servername = "localhost"; $username = "usernam…

php 实现链表

php 实现链表

PHP 实现链表的方法 链表是一种线性数据结构,由节点组成,每个节点包含数据和指向下一个节点的指针。PHP 中可以通过类和对象来实现链表。 定义链表节点类 创建一个 ListNode 类,用于表示链…

php 实现md5

php 实现md5

使用 PHP 内置函数实现 MD5 PHP 提供了 md5() 函数,可以直接计算字符串的 MD5 哈希值。该函数接受一个字符串参数,返回 32 字符的十六进制哈希值。 $string = "H…