Python编程实现凯撒密码加密示例
程序员文章站
2022-06-18 08:14:08
目录一、什么是凯撒密码“在密码学中,恺撒密码(英语:caesar cipher),或称恺撒加密、恺撒变换、变换加密,是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母...
一、什么是凯撒密码
“在密码学中,恺撒密码(英语:caesar cipher),或称恺撒加密、恺撒变换、变换加密,是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。例如,当偏移量是3的时候,所有的字母a将被替换成d,b变成e,以此类推。这个加密方法是以罗马共和时期恺撒的名字命名的,当年恺撒曾用此方法与其将军们进行联系。”
关于凯撒密码的详细介绍:恺撒密码_百度百科
二、python实现凯撒加密
凯撒密码程序的源代码 :
在文件编辑器中建立.py文件,并将其保存为caesarcipher.py。然后将本文配套资源
中的pyperclip.py模块放在与 caesarcipher.py 文件相同的目录(相同的文件夹)中、
caesarcipher.py将导人这个模块。pyperclip.py模块如下:
凯撒密码的pyperclip.py模块:
""" pyperclip a cross-platform clipboard module for python, with copy & paste functions for plain text. by al sweigart al@inventwithpython.com bsd license usage: import pyperclip pyperclip.copy('the text to be copied to the clipboard.') spam = pyperclip.paste() if not pyperclip.is_available(): print("copy functionality unavailable!") on windows, no additional modules are needed. on mac, the pyobjc module is used, falling back to the pbcopy and pbpaste cli commands. (these commands should come with os x.). on linux, install xclip or xsel via package manager. for example, in debian: sudo apt-get install xclip sudo apt-get install xsel otherwise on linux, you will need the gtk or pyqt5/pyqt4 modules installed. gtk and pyqt4 modules are not available for python 3, and this module does not work with pygobject yet. note: there seem sto be a way to get gtk on python 3, according to: https://askubuntu.com/questions/697397/python3-is-not-supporting-gtk-module cygwin is currently not supported. security note: this module runs programs with these names: - which - where - pbcopy - pbpaste - xclip - xsel - klipper - qdbus a malicious user could rename or add programs with these names, tricking pyperclip into running them with whatever permissions the python process has. """ __version__ = '1.6.0' import contextlib import ctypes import os import platform import subprocess import sys import time import warnings from ctypes import c_size_t, sizeof, c_wchar_p, get_errno, c_wchar # `import pyqt4` sys.exit()s if display is not in the environment. # thus, we need to detect the presence of $display manually # and not load pyqt4 if it is absent. has_display = os.getenv("display", false) except_msg = """ pyperclip could not find a copy/paste mechanism for your system. for more information, please visit https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error """ py2 = sys.version_info[0] == 2 str_or_unicode = unicode if py2 else str encoding = 'utf-8' # the "which" unix command finds where a command is. if platform.system() == 'windows': which_cmd = 'where' else: which_cmd = 'which' def _executable_exists(name): return subprocess.call([which_cmd, name], stdout=subprocess.pipe, stderr=subprocess.pipe) == 0 # exceptions class pyperclipexception(runtimeerror): pass class pyperclipwindowsexception(pyperclipexception): def __init__(self, message): message += " (%s)" % ctypes.winerror() super(pyperclipwindowsexception, self).__init__(message) def init_osx_pbcopy_clipboard(): def copy_osx_pbcopy(text): p = subprocess.popen(['pbcopy', 'w'], stdin=subprocess.pipe, close_fds=true) p.communicate(input=text.encode(encoding)) def paste_osx_pbcopy(): p = subprocess.popen(['pbpaste', 'r'], stdout=subprocess.pipe, close_fds=true) stdout, stderr = p.communicate() return stdout.decode(encoding) return copy_osx_pbcopy, paste_osx_pbcopy def init_osx_pyobjc_clipboard(): def copy_osx_pyobjc(text): '''copy string argument to clipboard''' newstr = foundation.nsstring.stringwithstring_(text).nsstring() newdata = newstr.datausingencoding_(foundation.nsutf8stringencoding) board = appkit.nspasteboard.generalpasteboard() board.declaretypes_owner_([appkit.nsstringpboardtype], none) board.setdata_fortype_(newdata, appkit.nsstringpboardtype) def paste_osx_pyobjc(): "returns contents of clipboard" board = appkit.nspasteboard.generalpasteboard() content = board.stringfortype_(appkit.nsstringpboardtype) return content return copy_osx_pyobjc, paste_osx_pyobjc def init_gtk_clipboard(): global gtk import gtk def copy_gtk(text): global cb cb = gtk.clipboard() cb.set_text(text) cb.store() def paste_gtk(): clipboardcontents = gtk.clipboard().wait_for_text() # for python 2, returns none if the clipboard is blank. if clipboardcontents is none: return '' else: return clipboardcontents return copy_gtk, paste_gtk def init_qt_clipboard(): global qapplication # $display should exist # try to import from qtpy, but if that fails try pyqt5 then pyqt4 try: from qtpy.qtwidgets import qapplication except: try: from pyqt5.qtwidgets import qapplication except: from pyqt4.qtgui import qapplication app = qapplication.instance() if app is none: app = qapplication([]) def copy_qt(text): cb = app.clipboard() cb.settext(text) def paste_qt(): cb = app.clipboard() return str_or_unicode(cb.text()) return copy_qt, paste_qt def init_xclip_clipboard(): default_selection='c' primary_selection='p' def copy_xclip(text, primary=false): selection=default_selection if primary: selection=primary_selection p = subprocess.popen(['xclip', '-selection', selection], stdin=subprocess.pipe, close_fds=true) p.communicate(input=text.encode(encoding)) def paste_xclip(primary=false): selection=default_selection if primary: selection=primary_selection p = subprocess.popen(['xclip', '-selection', selection, '-o'], stdout=subprocess.pipe, stderr=subprocess.pipe, close_fds=true) stdout, stderr = p.communicate() # intentionally ignore extraneous output on stderr when clipboard is empty return stdout.decode(encoding) return copy_xclip, paste_xclip def init_xsel_clipboard(): default_selection='-b' primary_selection='-p' def copy_xsel(text, primary=false): selection_flag = default_selection if primary: selection_flag = primary_selection p = subprocess.popen(['xsel', selection_flag, '-i'], stdin=subprocess.pipe, close_fds=true) p.communicate(input=text.encode(encoding)) def paste_xsel(primary=false): selection_flag = default_selection if primary: selection_flag = primary_selection p = subprocess.popen(['xsel', selection_flag, '-o'], stdout=subprocess.pipe, close_fds=true) stdout, stderr = p.communicate() return stdout.decode(encoding) return copy_xsel, paste_xsel def init_klipper_clipboard(): def copy_klipper(text): p = subprocess.popen( ['qdbus', 'org.kde.klipper', '/klipper', 'setclipboardcontents', text.encode(encoding)], stdin=subprocess.pipe, close_fds=true) p.communicate(input=none) def paste_klipper(): p = subprocess.popen( ['qdbus', 'org.kde.klipper', '/klipper', 'getclipboardcontents'], stdout=subprocess.pipe, close_fds=true) stdout, stderr = p.communicate() # workaround for https://bugs.kde.org/show_bug.cgi?id=342874 # todo: https://github.com/asweigart/pyperclip/issues/43 clipboardcontents = stdout.decode(encoding) # even if blank, klipper will append a newline at the end assert len(clipboardcontents) > 0 # make sure that newline is there assert clipboardcontents.endswith('\n') if clipboardcontents.endswith('\n'): clipboardcontents = clipboardcontents[:-1] return clipboardcontents return copy_klipper, paste_klipper def init_dev_clipboard_clipboard(): def copy_dev_clipboard(text): if text == '': warnings.warn('pyperclip cannot copy a blank string to the clipboard on cygwin. this is effectively a no-op.') if '\r' in text: warnings.warn('pyperclip cannot handle \\r characters on cygwin.') fo = open('/dev/clipboard', 'wt') fo.write(text) fo.close() def paste_dev_clipboard(): fo = open('/dev/clipboard', 'rt') content = fo.read() fo.close() return content return copy_dev_clipboard, paste_dev_clipboard def init_no_clipboard(): class clipboardunavailable(object): def __call__(self, *args, **kwargs): raise pyperclipexception(except_msg) if py2: def __nonzero__(self): return false else: def __bool__(self): return false return clipboardunavailable(), clipboardunavailable() # windows-related clipboard functions: class checkedcall(object): def __init__(self, f): super(checkedcall, self).__setattr__("f", f) def __call__(self, *args): ret = self.f(*args) if not ret and get_errno(): raise pyperclipwindowsexception("error calling " + self.f.__name__) return ret def __setattr__(self, key, value): setattr(self.f, key, value) def init_windows_clipboard(): global hglobal, lpvoid, dword, lpcstr, int, hwnd, hinstance, hmenu, bool, uint, handle from ctypes.wintypes import (hglobal, lpvoid, dword, lpcstr, int, hwnd, hinstance, hmenu, bool, uint, handle) windll = ctypes.windll msvcrt = ctypes.cdll('msvcrt') safecreatewindowexa = checkedcall(windll.user32.createwindowexa) safecreatewindowexa.argtypes = [dword, lpcstr, lpcstr, dword, int, int, int, int, hwnd, hmenu, hinstance, lpvoid] safecreatewindowexa.restype = hwnd safedestroywindow = checkedcall(windll.user32.destroywindow) safedestroywindow.argtypes = [hwnd] safedestroywindow.restype = bool openclipboard = windll.user32.openclipboard openclipboard.argtypes = [hwnd] openclipboard.restype = bool safecloseclipboard = checkedcall(windll.user32.closeclipboard) safecloseclipboard.argtypes = [] safecloseclipboard.restype = bool safeemptyclipboard = checkedcall(windll.user32.emptyclipboard) safeemptyclipboard.argtypes = [] safeemptyclipboard.restype = bool safegetclipboarddata = checkedcall(windll.user32.getclipboarddata) safegetclipboarddata.argtypes = [uint] safegetclipboarddata.restype = handle safesetclipboarddata = checkedcall(windll.user32.setclipboarddata) safesetclipboarddata.argtypes = [uint, handle] safesetclipboarddata.restype = handle safeglobalalloc = checkedcall(windll.kernel32.globalalloc) safeglobalalloc.argtypes = [uint, c_size_t] safeglobalalloc.restype = hglobal safegloballock = checkedcall(windll.kernel32.globallock) safegloballock.argtypes = [hglobal] safegloballock.restype = lpvoid safeglobalunlock = checkedcall(windll.kernel32.globalunlock) safeglobalunlock.argtypes = [hglobal] safeglobalunlock.restype = bool wcslen = checkedcall(msvcrt.wcslen) wcslen.argtypes = [c_wchar_p] wcslen.restype = uint gmem_moveable = 0x0002 cf_unicodetext = 13 @contextlib.contextmanager def window(): """ context that provides a valid windows hwnd. """ # we really just need the hwnd, so setting "static" # as predefined lpclass is just fine. hwnd = safecreatewindowexa(0, b"static", none, 0, 0, 0, 0, 0, none, none, none, none) try: yield hwnd finally: safedestroywindow(hwnd) @contextlib.contextmanager def clipboard(hwnd): """ context manager that opens the clipboard and prevents other applications from modifying the clipboard content. """ # we may not get the clipboard handle immediately because # some other application is accessing it (?) # we try for at least 500ms to get the clipboard. t = time.time() + 0.5 success = false while time.time() < t: success = openclipboard(hwnd) if success: break time.sleep(0.01) if not success: raise pyperclipwindowsexception("error calling openclipboard") try: yield finally: safecloseclipboard() def copy_windows(text): # this function is heavily based on # http://msdn.com/ms649016#_win32_copying_information_to_the_clipboard with window() as hwnd: # http://msdn.com/ms649048 # if an application calls openclipboard with hwnd set to null, # emptyclipboard sets the clipboard owner to null; # this causes setclipboarddata to fail. # => we need a valid hwnd to copy something. with clipboard(hwnd): safeemptyclipboard() if text: # http://msdn.com/ms649051 # if the hmem parameter identifies a memory object, # the object must have been allocated using the # function with the gmem_moveable flag. count = wcslen(text) + 1 handle = safeglobalalloc(gmem_moveable, count * sizeof(c_wchar)) locked_handle = safegloballock(handle) ctypes.memmove(c_wchar_p(locked_handle), c_wchar_p(text), count * sizeof(c_wchar)) safeglobalunlock(handle) safesetclipboarddata(cf_unicodetext, handle) def paste_windows(): with clipboard(none): handle = safegetclipboarddata(cf_unicodetext) if not handle: # getclipboarddata may return null with errno == no_error # if the clipboard is empty. # (also, it may return a handle to an empty buffer, # but technically that's not empty) return "" return c_wchar_p(handle).value return copy_windows, paste_windows # automatic detection of clipboard mechanisms and importing is done in deteremine_clipboard(): def determine_clipboard(): ''' determine the os/platform and set the copy() and paste() functions accordingly. ''' global foundation, appkit, gtk, qtpy, pyqt4, pyqt5 # setup for the cygwin platform: if 'cygwin' in platform.system().lower(): # cygwin has a variety of values returned by platform.system(), such as 'cygwin_nt-6.1' # fixme: pyperclip currently does not support cygwin, # see https://github.com/asweigart/pyperclip/issues/55 if os.path.exists('/dev/clipboard'): warnings.warn('pyperclip\'s support for cygwin is not perfect, see https://github.com/asweigart/pyperclip/issues/55') return init_dev_clipboard_clipboard() # setup for the windows platform: elif os.name == 'nt' or platform.system() == 'windows': return init_windows_clipboard() # setup for the mac os x platform: if os.name == 'mac' or platform.system() == 'darwin': try: import foundation # check if pyobjc is installed import appkit except importerror: return init_osx_pbcopy_clipboard() else: return init_osx_pyobjc_clipboard() # setup for the linux platform: if has_display: try: import gtk # check if gtk is installed except importerror: pass # we want to fail fast for all non-importerror exceptions. else: return init_gtk_clipboard() if _executable_exists("xclip"): return init_xclip_clipboard() if _executable_exists("xsel"): return init_xsel_clipboard() if _executable_exists("klipper") and _executable_exists("qdbus"): return init_klipper_clipboard() try: # qtpy is a small abstraction layer that lets you write applications using a single api call to either pyqt or pyside. # https://pypi.python.org/pypi/qtpy import qtpy # check if qtpy is installed except importerror: # if qtpy isn't installed, fall back on importing pyqt4. try: import pyqt5 # check if pyqt5 is installed except importerror: try: import pyqt4 # check if pyqt4 is installed except importerror: pass # we want to fail fast for all non-importerror exceptions. else: return init_qt_clipboard() else: return init_qt_clipboard() else: return init_qt_clipboard() return init_no_clipboard() def set_clipboard(clipboard): ''' explicitly sets the clipboard mechanism. the "clipboard mechanism" is how the copy() and paste() functions interact with the operating system to implement the copy/paste feature. the clipboard parameter must be one of: - pbcopy - pbobjc (default on mac os x) - gtk - qt - xclip - xsel - klipper - windows (default on windows) - no (this is what is set when no clipboard mechanism can be found) ''' global copy, paste clipboard_types = {'pbcopy': init_osx_pbcopy_clipboard, 'pyobjc': init_osx_pyobjc_clipboard, 'gtk': init_gtk_clipboard, 'qt': init_qt_clipboard, # todo - split this into 'qtpy', 'pyqt4', and 'pyqt5' 'xclip': init_xclip_clipboard, 'xsel': init_xsel_clipboard, 'klipper': init_klipper_clipboard, 'windows': init_windows_clipboard, 'no': init_no_clipboard} if clipboard not in clipboard_types: raise valueerror('argument must be one of %s' % (', '.join([repr(_) for _ in clipboard_types.keys()]))) # sets pyperclip's copy() and paste() functions: copy, paste = clipboard_types[clipboard]() def lazy_load_stub_copy(text): ''' a stub function for copy(), which will load the real copy() function when called so that the real copy() function is used for later calls. this allows users to import pyperclip without having determine_clipboard() automatically run, which will automatically select a clipboard mechanism. this could be a problem if it selects, say, the memory-heavy pyqt4 module but the user was just going to immediately call set_clipboard() to use a different clipboard mechanism. the lazy loading this stub function implements gives the user a chance to call set_clipboard() to pick another clipboard mechanism. or, if the user simply calls copy() or paste() without calling set_clipboard() first, will fall back on whatever clipboard mechanism that determine_clipboard() automatically chooses. ''' global copy, paste copy, paste = determine_clipboard() return copy(text) def lazy_load_stub_paste(): ''' a stub function for paste(), which will load the real paste() function when called so that the real paste() function is used for later calls. this allows users to import pyperclip without having determine_clipboard() automatically run, which will automatically select a clipboard mechanism. this could be a problem if it selects, say, the memory-heavy pyqt4 module but the user was just going to immediately call set_clipboard() to use a different clipboard mechanism. the lazy loading this stub function implements gives the user a chance to call set_clipboard() to pick another clipboard mechanism. or, if the user simply calls copy() or paste() without calling set_clipboard() first, will fall back on whatever clipboard mechanism that determine_clipboard() automatically chooses. ''' global copy, paste copy, paste = determine_clipboard() return paste() def is_available(): return copy != lazy_load_stub_copy and paste != lazy_load_stub_paste # initially, copy() and paste() are set to lazy loading wrappers which will # set `copy` and `paste` to real functions the first time they're used, unless # set_clipboard() or determine_clipboard() is called first. copy, paste = lazy_load_stub_copy, lazy_load_stub_paste __all__ = ['copy', 'paste', 'set_clipboard', 'determine_clipboard']
1.首先引用pyperclip.py模块:
import pyperclip
2.定义变量message,message为要加密的字符串:
# the string to be encrypted message = 'iloveyou.'
3.将偏移设为3,即令key=3,设置为解密模式,并加入所有可加密的符号:
# the encryption key: key = 3 mode = 'decrypt' # every possible symbol that can be encrypted: symbols = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz1234567890 !?.'
4. translated储存信息的解密形式,仅加密/解密在symbols和symbols里共有的字符(串)
# stores the encrypted/decrypted form of the message: translated = '' for symbol in message: # note: only symbols in the `symbols` string can be encrypted/decrypted. if symbol in symbols: symbolindex = symbols.find(symbol)
5.执行加密/解密并添加未加密/解密的字符:
# perform encryption/decryption: if mode == 'encrypt': translatedindex = symbolindex + key elif mode == 'decrypt': translatedindex = symbolindex - key # handle wrap-around, if needed: if translatedindex >= len(symbols): translatedindex = translatedindex - len(symbols) elif translatedindex < 0: translatedindex = translatedindex + len(symbols) translated = translated + symbols[translatedindex]
6.输出translated字符串:
print(translated) pyperclip.copy(translated)
以上就是python编程实现凯撒密码加密示例的详细内容,更多关于python实现凯撒密码加密的资料请关注其它相关文章!
上一篇: 数据库系统的结构
推荐阅读
-
Python编程二分法实现冒泡算法+快速排序代码示例
-
python实现换位加密算法的示例
-
python实现随机密码字典生成器示例
-
经典问题(c++/python)素数、杨辉三角(金字塔型)、统计单词数、简单计算器、密码安全程度、凯撒密码加密、汉诺塔 (python课设实验实例)-- biaobiao88
-
Python实现的HMacMD5加密算法示例
-
使用mongoose和bcrypt实现用户密码加密的示例
-
Python实现的排列组合、破解密码算法示例
-
Python网络编程使用select实现socket全双工异步通信功能示例
-
Python网络编程基于多线程实现多用户全双工聊天功能示例
-
Python编程实现的简单神经网络算法示例