Python编写程序,完成凯撒密码计算。要求:键盘输入明文字符串,以及转换密钥k值
时间: 2023-04-06 21:04:40 浏览: 104
好的,这个问题我可以回答。以下是Python编写的凯撒密码计算程序:
```python
plain_text = input("请输入明文字符串:")
k = int(input("请输入转换密钥k值:"))
cipher_text = ""
for char in plain_text:
if char.isalpha():
if char.islower():
cipher_text += chr((ord(char) - 97 + k) % 26 + 97)
else:
cipher_text += chr((ord(char) - 65 + k) % 26 + 65)
else:
cipher_text += char
print("密文字符串为:", cipher_text)
```
这个程序可以将输入的明文字符串按照凯撒密码的规则进行加密,输出对应的密文字符串。
相关问题
对ascii码进行凯撒加密
假设加密密钥为k,则对于ascii码表中的每个字符,都将其值向右移动k位,若超过了ascii码表的范围,则回到表头继续计算。
例如,若密钥为3,则对于字符'A',其ascii码为65,加密后的值为65+3=68,对应的字符为'D'。对于字符'Z',其ascii码为90,加密后的值为90+3=93,由于93已经超出了ascii码表的范围,因此回到表头继续计算,即93-26=67,对应的字符为'C'。
下面是一个简单的python程序示例:
```python
def caesar_encrypt(plaintext, key):
ciphertext = ''
for c in plaintext:
if c.isalpha():
base = ord('a') if c.islower() else ord('A')
ciphertext += chr((ord(c) - base + key) % 26 + base)
else:
ciphertext += c
return ciphertext
```
其中,plaintext为待加密的文本,key为加密密钥。程序首先进行了字符类型的判断,然后根据字符的大小写情况计算出该字符所在的ascii码表的起始位置,将其值加上密钥再进行模运算和加上起始位置即可得到加密后的字符。
实现维吉尼亚密码算法的加解密过程
### 维吉尼亚密码加解密原理
维吉尼亚密码是一种基于凯撒密码改进而来的多表替换加密方法。其核心在于通过一个重复使用的密钥来改变字符位移量,从而提高安全性[^1]。
对于每一个待处理的明文字母 \( P_i \),会依据相应位置上的密钥字母 \( K_i \) 来决定具体的偏移值;而在解码过程中,则反向操作恢复原始信息[^3]。
具体来说:
- **加密公式**:\( C_i = (P_i + K_i) \% 26 \)
- **解密公式**:\( P_i = (C_i - K_i + 26) \% 26 \)
这里假设 A 对应数值 0, B 对应 1... Z 对应 25,并且当计算结果小于零时加上 26 确保最终得到的是有效的字母索引范围内的数[^4]。
下面给出一段 Python 实现的例子用于展示该算法的工作流程:
```python
def vigenere_encrypt(plaintext, keyword):
ciphertext = ""
key_length = len(keyword)
for i in range(len(plaintext)):
char = plaintext[i].upper()
if 'A' <= char <= 'Z':
shift = ord(keyword[i % key_length]) - ord('A')
encrypted_char = chr((ord(char) - ord('A') + shift) % 26 + ord('A'))
ciphertext += encrypted_char
else:
ciphertext += char
return ciphertext
def vigenere_decrypt(ciphertext, keyword):
decryptedtext = ""
key_length = len(keyword)
for i in range(len(ciphertext)):
char = ciphertext[i].upper()
if 'A' <= char <= 'Z':
shift = ord(keyword[i % key_length]) - ord('A')
decrypted_char = chr(((ord(char) - ord('A') - shift + 26) % 26) + ord('A'))
decryptedtext += decrypted_char
else:
decryptedtext += char
return decryptedtext.lower()
if __name__ == "__main__":
message = "GoodStudy"
secret_key = "HnUn"
encoded_message = vigenere_encrypt(message, secret_key)
decoded_message = vigenere_decrypt(encoded_message, secret_key)
print(f"Original Message: {message}")
print(f"Cipher Text: {encoded_message}")
print(f"Decoded Message: {decoded_message}")
```
这段代码实现了基本的功能测试,其中包含了大小写字母的支持以及非字母字符保持不变的特点[^2]。
阅读全文