字符串加密python习题
时间: 2023-07-25 12:13:58 浏览: 57
您好!对于字符串加密的Python习题,可以有多种实现方式,以下是一种简单的加密算法示例:
```python
def encrypt(s):
result = ""
for char in s:
# 将字符转换为ASCII码值
ascii_code = ord(char)
# 对ASCII码值加上一个固定值(例如3),得到新的ASCII码值
new_ascii_code = ascii_code + 3
# 将新的ASCII码值转换为字符
new_char = chr(new_ascii_code)
# 将新的字符添加到结果字符串中
result += new_char
return result
```
使用示例:
```python
s = "hello, world!"
encrypted_s = encrypt(s)
print(encrypted_s) # 输出:khoor/#zruog$
```
解密时,只需要将加密算法中的加法操作改成减法操作即可。
相关问题
pta字符串加密python
PTA字符串加密是一道常见的编程题目,要求对给定的字符串进行加密操作。下面是一种可能的Python实现方式:
```python
def encrypt_string(s):
result = ""
for i in range(len(s)):
if s[i].isalpha():
if s[i].islower():
result += chr((ord(s[i]) - ord('a') + 3) % 26 + ord('a'))
else:
result += chr((ord(s[i]) - ord('A') + 3) % 26 + ord('A'))
else:
result += s[i]
return result
# 测试
s = input("请输入要加密的字符串:")
encrypted_string = encrypt_string(s)
print("加密后的字符串为:", encrypted_string)
```
上述代码中,`encrypt_string`函数接受一个字符串作为参数,然后遍历字符串中的每个字符。如果字符是字母,则根据其大小写进行不同的加密操作,将其ASCII码值加上3并取模,再转换回字符。如果字符不是字母,则直接保留原样。最后将加密后的字符拼接起来并返回。
字符串加密python
以下是一个字符串加密的Python示例,使用AES算法和PKCS7填充模式:
```python
import base64
from Crypto.Cipher import AES
def pad(s):
"""PKCS7填充"""
return s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)
def encrypt(message, key):
"""AES加密"""
cipher = AES.new(pad(key).encode(), AES.MODE_ECB)
encrypted_message = cipher.encrypt(pad(message).encode())
return base64.b64encode(encrypted_message).decode()
# 示例
message = "Hello, world!"
key = "mysecretkey"
encrypted_message = encrypt(message, key)
print(encrypted_message)
```
请注意,此示例中使用的密钥长度为16字节,因为AES算法要求密钥长度为16、24或32字节。如果您需要使用不同长度的密钥,请使用其他填充模式。