PHP实现vigenere cipher维吉尼亚密码算法(附完整源码)

本文介绍了如何使用PHP实现维吉尼亚密码(Vigenere cipher)算法,提供了详细的示例代码。代码中,函数接受字符串和密钥,通过ASCII码偏移计算加密大写字母,非字母字符保持不变。示例加密了文本并展示了加密过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@toc
以下是一个使用PHP实现维吉尼亚密码(Vigenere cipher)算法的示例代码:

<?php
function vigenereCipher($str, $key) {
   
    $result = "";
以下是Java实现维吉尼亚密码加解密算法的完整源码: ```java import java.util.Scanner; public class VigenereCipher { private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 读取明文和密钥 System.out.print("请输入明文:"); String plainText = scanner.nextLine().toUpperCase(); System.out.print("请输入密钥:"); String key = scanner.nextLine().toUpperCase(); // 加密 String cipherText = encrypt(plainText, key); System.out.println("加密后的密文为:" + cipherText); // 解密 String decryptedText = decrypt(cipherText, key); System.out.println("解密后的明文为:" + decryptedText); scanner.close(); } /** * 维吉尼亚密码加密 * * @param plainText 明文 * @param key 密钥 * @return 密文 */ public static String encrypt(String plainText, String key) { StringBuilder cipherText = new StringBuilder(); int keyIndex = 0; for (char c : plainText.toCharArray()) { if (Character.isLetter(c)) { int plainTextIndex = ALPHABET.indexOf(c); int keyCharIndex = ALPHABET.indexOf(key.charAt(keyIndex)); int cipherTextIndex = (plainTextIndex + keyCharIndex) % ALPHABET.length(); cipherText.append(ALPHABET.charAt(cipherTextIndex)); keyIndex = ++keyIndex % key.length(); } else { cipherText.append(c); } } return cipherText.toString(); } /** * 维吉尼亚密码解密 * * @param cipherText 密文 * @param key 密钥 * @return 明文 */ public static String decrypt(String cipherText, String key) { StringBuilder plainText = new StringBuilder(); int keyIndex = 0; for (char c : cipherText.toCharArray()) { if (Character.isLetter(c)) { int cipherTextIndex = ALPHABET.indexOf(c); int keyCharIndex = ALPHABET.indexOf(key.charAt(keyIndex)); int plainTextIndex = (cipherTextIndex - keyCharIndex + ALPHABET.length()) % ALPHABET.length(); plainText.append(ALPHABET.charAt(plainTextIndex)); keyIndex = ++keyIndex % key.length(); } else { plainText.append(c); } } return plainText.toString(); } } ``` 使用时,只需在主函数中调用 `encrypt` 和 `decrypt` 方法即可。注意,这里使用的是大写字母表,如果要支持小写字母,可以在字母表中添加小写字母即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

源代码大师

赏点狗粮吧

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

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

打赏作者

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

抵扣说明:

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

余额充值