我想为python中的某些文本创建自己的极其简单的加密。这只会阻止人们找到我要加密的文件。我在下面的这段代码可以做到这一点,但是要花很多时间以这种方式进行编码,并确保它不是最有效的。我想知道是否有一种方法可以使用更少的代码来做到这一点。 (a,b,c不是我将要使用的唯一字符。而且我自己可以很好地复制/粘贴随机文本)
def encrypt(text):
return str(text).replace("a", "3tpkDWCiXw").replace("b", "moOK4LWTUx").replace("c", "qqN9zTb9nR")
def decrypt(text):
return str(text).replace("3tpkDWCiXw", "a").replace("moOK4LWTUx", "b").replace("qqN9zTb9nR", "c")
encrypted = encrypt("abc")
print(encrypted)
decrypted = decrypt(encrypted)
print(decrypted)
预先感谢,因为它还将帮助我完成其他事情,而不仅仅是这个小项目。PS我只是想像给出的例子一样简单,因为我不希望/需要更复杂的加密。
编辑:我不使用更复杂的加密的另一个原因是因为每当我复制代码并尝试自己做时,都会遇到错误。我也确实安装了加密技术,但是由于某种原因它没有用。
这里是凯撒密码:
#! /usr/bin/env python
# Caesar Cipher Encryption and Decryption tool.
# Introduction
print('\nHow to use:\n\n')
print('Encrypt:\n')
print('\tEnter your encryption key (1-25)\n')
print('\tThen, enter the message to encrypt.\n\n')
print('Decrypt:\n')
print('\tEnter the decryption key.\n')
print('\tThen, paste the encrypted message.')
print('\n\nEnter "q" or "quit" to exit.\n')
# Every possible symbol that can be encrypted/decrypted:
SYMBOLS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.~`@#$%^&*)("
message = ''
mode = ''
# User enters the mode
currentMode = input("Mode: [encrypt] or [decrypt]: ")
# ENCRYPT settings
if currentMode == 'e'.lower() or currentMode == 'encrypt'.lower():
mode = 'encrypt'
key = int(input('Encryption Key: '))
while key >= len(SYMBOLS) or key <= 0:
print('Please enter an encryption key between 1-' + str(len(SYMBOLS) - 1))
key = int(input('Encryption Key: '))
message = input('What would you like to encrypt?\n')
# DECRYPT settings
elif currentMode == 'D' or currentMode == 'd' or currentMode == 'decrypt' or currentMode == 'DECRYPT':
mode = 'decrypt'
key = int(input('Decryption Key: '))
while key >= len(SYMBOLS) or key <= 0:
print('Please enter a decryption key between 1-' + str(len(SYMBOLS) - 1))
key = int(input('Decryption Key: '))
message = input('Paste the encrypted text below:\n')
# Quit
elif currentMode == 'Q' or currentMode == 'q' or currentMode == 'quit' or currentMode == 'QUIT':
exit()
# Store encrypted / decrypted message:
translated = ''
for symbol in message:
if symbol in SYMBOLS:
symbolIndex = SYMBOLS.find(symbol)
# Perform encryption / decryption
if mode == 'encrypt':
translatedIndex = symbolIndex + key
if mode == 'decrypt':
translatedIndex = symbolIndex - key
# Handle wraparound if needed:
if translatedIndex >= len(SYMBOLS):
translatedIndex = translatedIndex - len(SYMBOLS)
elif translatedIndex < 0:
translatedIndex = translatedIndex + len(SYMBOLS)
translated = translated + SYMBOLS[translatedIndex]
else:
# Append the symbol without encrypting / decrypting:
translated = translated + symbol
# Output text
if mode == 'encrypt':
print('\nYour ENCRYPTED message:')
elif mode == 'decrypt':
print('\nThe secret message is:')
# Ciphertext
print('\n\t' + translated + '\n')
您还可以检出仿射或换位密码,它们都很简单(但比凯撒密码更复杂)