给我写一份Python比较简单的加密代码
时间: 2024-04-12 08:07:30 浏览: 23
好的,这里提供一个简单的Python加密代码示例,使用的是 Caesar Cipher(凯撒密码):
```python
def encrypt(text, shift):
result = ""
for i in range(len(text)):
char = text[i]
if char.isupper():
result += chr((ord(char) + shift - 65) % 26 + 65)
else:
result += chr((ord(char) + shift - 97) % 26 + 97)
return result
```
使用方法:
- `text`:需要加密的明文
- `shift`:加密时偏移的位数
例如,使用偏移量为3加密字符串"hello",调用`encrypt("hello", 3)`,输出结果为"khoor"。
相关问题
写一份Python比较简单的加密代码
好的,下面是一个比较简单的Python加密代码示例:
```python
def encrypt(message, key):
result = ""
for char in message:
result += chr(ord(char) + key)
return result
def decrypt(message, key):
result = ""
for char in message:
result += chr(ord(char) - key)
return result
```
以上代码中,`encrypt()` 函数将输入的字符串按照 ASCII 码表进行加密,每个字符加上一个密钥 `key`。`decrypt()` 函数是加密的反向操作,将密文解密回原来的明文。
使用方法示例:
```python
message = "Hello, world!"
key = 3
encrypted_message = encrypt(message, key)
print(f"Encrypted message: {encrypted_message}")
decrypted_message = decrypt(encrypted_message, key)
print(f"Decrypted message: {decrypted_message}")
```
输出:
```
Encrypted message: Khoor/#zruog$
Decrypted message: Hello, world!
```
请注意,以上加密算法仅仅是一个简单的示例,不适用于实际加密场景,安全性无法得到保障。在实际应用中需要使用专业的加密库来保证安全性。
帮我用python写一份加密代码
好的,以下是一份简单的加密代码,用于对字符串进行加密:
```python
def encrypt(message, key):
"""
Encrypts a message using a simple Caesar cipher, where each letter in the
message is shifted by the key parameter.
:param message: The message to be encrypted
:param key: The key to use for encryption, an integer between 1 and 26
:return: The encrypted message
"""
encrypted_message = ''
for char in message:
if char.isalpha():
shifted_char = chr((ord(char) - 65 + key) % 26 + 65)
encrypted_message += shifted_char
else:
encrypted_message += char
return encrypted_message
```
这个加密算法使用了一个简单的凯撒密码,每一个字母都向右移动了“key”个位置。请注意,这种简单的加密算法并不是安全的,因为它容易受到暴力破解的攻击。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)