Python 密码学 - 快速指南
Python 密码学 - 概述
密码学是两个用户之间通过编码消息进行通信的艺术。密码学的出现的基本动机是为从一方传输到另一方的机密消息提供安全性。
密码学被定义为隐藏消息以引入信息安全中所认可的隐私和秘密的艺术和科学。
密码学术语
密码学中常用的术语解释如下 -
纯文本
纯文本消息是所有用户可读且可以理解的文本。明文是经过加密的消息。
密文
密文是对明文应用密码学后得到的消息。
加密
将明文转换为密文的过程称为加密。它也称为编码。
解密
将密文转换为明文的过程称为解密。它也称为解码。
下图显示了密码学的完整过程 -
现代密码学的特点
现代密码学的基本特征如下 -
它对位序列进行操作。
它使用数学算法来保护信息。
它要求对安全通信通道感兴趣的各方实现隐私。
双倍强度加密
双倍强度加密,也称为多重加密,是使用相同或不同的算法/模式对已加密的文本进行一次或多次加密的过程。
双强度加密的其他名称包括级联加密或级联加密。
双倍强度加密级别
双强度加密包括各种级别的加密,如下所述 -
第一层加密
密文是使用哈希算法和对称密钥从原始可读消息生成的。后来的对称密钥借助非对称密钥进行加密。这种模式的最佳例证是将密文的哈希摘要合并到一个胶囊中。接收方将首先计算摘要,然后解密文本,以验证文本在中间没有被篡改。
第二层加密
第二层加密是用相同或不同的算法在密文上再添加一层的过程。通常,使用 32 位字符长的对称密码。
第三层加密
在此过程中,加密的胶囊通过 SSL/TLS 连接传输到通信伙伴。
下图形象地显示了双重加密过程 -
混合密码学
混合密码学是通过包含每种密码的优点来一起使用不同类型的多种密码的过程。通常遵循一种常见的方法来生成对称密码的随机密钥,然后通过非对称密钥加密术加密该密钥。
由于这种模式,原始消息本身使用对称密码进行加密,然后使用秘密密钥。接收方收到消息后,首先使用自己的私钥对消息进行解密,然后使用指定的密钥对消息进行解密。
Python概述和安装
Python是一种开源脚本语言,具有高级、解释性、交互性和面向对象的特点。它被设计为具有高度可读性。Python语言的语法易于理解,并且经常使用英文关键字。
Python语言的特点
Python 提供以下主要功能 -
解释
Python 在运行时使用解释器进行处理。执行前无需编译程序。它类似于 PERL 和 PHP。
面向对象
Python 遵循面向对象的风格和设计模式。它包括具有封装和多态性等各种功能的类定义。
Python语言要点
Python 编程语言的要点如下 -
它包括函数式和结构化编程和方法以及面向对象的编程方法。
它可以用作脚本语言或编程语言。
它包括自动垃圾收集。
它包括高级动态数据类型并支持各种动态类型检查。
Python 具有与 C、C++ 和 Java 等语言集成的功能。
Python 语言的下载链接如下:www.python.org/downloads它包含适用于各种操作系统(如 Windows、MacOS 和 Linux 发行版)的软件包。
Python 字符串
字符串的基本声明如下所示 -
str = 'Hello World!'
Python 列表
python 的列表可以声明为复合数据类型,用逗号分隔并括在方括号([])内。
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john']
Python 元组
元组是 Python 的动态数据类型,由多个用逗号分隔的值组成。元组用括号括起来。
tinytuple = (123, 'john')
Python 字典
Python 字典是哈希表的一种。字典键几乎可以是Python的任何数据类型,通常是数字或字符串。
tinydict = {'name': 'omkar','code':6734, 'dept': 'sales'}
密码学包
Python 包含一个名为 cryptography 的包,它提供密码配方和原语。它支持 Python 2.7、Python 3.4+ 和 PyPy 5.3+。加密包的基本安装是通过以下命令实现的 -
pip install cryptography
有各种包具有常见加密算法的高级配方和低级接口,例如对称密码、消息摘要和密钥派生函数。
在本教程中,我们将使用各种 Python 包来实现加密算法。
Python 密码学 - 逆向密码
上一章概述了如何在本地计算机上安装 Python。在本章中,您将详细了解反向密码及其编码。
逆向密码算法
逆向密码算法具有以下特点 -
反向密码使用反转纯文本字符串以转换为密文的模式。
加密和解密的过程是一样的。
要解密密文,用户只需将密文反转即可得到明文。
退税
反向密码的主要缺点是它非常弱。黑客可以轻松破解密文以获取原始消息。因此,反向密码不被认为是维护安全通信通道的好选择。
例子
考虑一个示例,其中语句“这是解释反向密码的程序”将使用反向密码算法来实现。以下Python代码使用该算法来获取输出。
message = 'This is program to explain reverse cipher.' translated = '' #cipher text is stored in this variable i = len(message) - 1 while i >= 0: translated = translated + message[i] i = i - 1 print(“The cipher text is : “, translated)
输出
您可以看到反转的文本,即输出,如下图所示 -
解释
纯文本存储在变量消息中,翻译后的变量用于存储创建的密文。
纯文本的长度是使用for循环并借助索引号来计算的。这些字符存储在最后一行打印的密文变量translated中。
Python 密码学 - 凯撒密码
在上一章中,我们讨论了反向密码。本章详细讨论凯撒密码。
凯撒密码算法
凯撒密码的算法具有以下特点 -
凯撒密码技术是一种简单易行的加密技术方法。
它是简单类型的替换密码。
纯文本的每个字母都被替换为字母表中具有固定数量位置的字母。
下图描述了凯撒密码算法实现的工作原理 -
凯撒密码算法的程序实现如下 -
def encrypt(text,s):
result = ""
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
result += chr((ord(char) + s-65) % 26 + 65)
# Encrypt lowercase characters in plain text
else:
result += chr((ord(char) + s - 97) % 26 + 97)
return result
#check the above function
text = "CEASER CIPHER DEMO"
s = 4
print "Plain Text : " + text
print "Shift pattern : " + str(s)
print "Cipher: " + encrypt(text,s)
输出
您可以看到凯撒密码,即输出,如下图所示 -
解释
一次遍历一个纯文本字符。
对于给定明文中的每个字符,根据文本加密和解密过程的规则对给定字符进行转换。
执行这些步骤后,将生成一个新字符串,称为密文。
凯撒密码算法的黑客攻击
密文可以通过多种可能性被破解。其中一种可能性是暴力技术,它涉及尝试所有可能的解密密钥。这种技术不需要太多努力,对于黑客来说相对简单。
黑客凯撒密码算法的程序实现如下 -
message = 'GIEWIVrGMTLIVrHIQS' #encrypted message
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for key in range(len(LETTERS)):
translated = ''
for symbol in message:
if symbol in LETTERS:
num = LETTERS.find(symbol)
num = num - key
if num < 0:
num = num + len(LETTERS)
translated = translated + LETTERS[num]
else:
translated = translated + symbol
print('Hacking key #%s: %s' % (key, translated))
考虑前面示例中加密的密文。然后,使用密钥和使用暴力攻击技术的可能的黑客方法的输出如下 -
使用 Python 进行密码学 - ROT13 算法
到目前为止,您已经了解了逆向密码和凯撒密码算法。现在,让我们讨论一下ROT13算法及其实现。
ROT13算法说明
ROT13密码是指Rotate by 13 位的缩写形式。这是凯撒密码的一个特例,其中移位始终为 13。每个字母都会移位 13 个位置来加密或解密消息。
例子
下图形象地解释了 ROT13 算法过程 -
程序代码
ROT13算法的程序实现如下 -
from string import maketrans
rot13trans = maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')
# Function to translate plain text
def rot13(text):
return text.translate(rot13trans)
def main():
txt = "ROT13 Algorithm"
print rot13(txt)
if __name__ == "__main__":
main()
您可以看到 ROT13 输出,如下图所示 -
退税
ROT13 算法使用 13 个移位。因此,通过反向移位字符来解密密文是非常容易的。
ROT13算法分析
ROT13 密码算法被认为是凯撒密码的特例。它不是一个非常安全的算法,可以通过频率分析或仅尝试可能的 25 个密钥来轻松破解,而 ROT13 可以通过移动 13 个位置来破解。因此,它不包括任何实际用途。
转置密码
转置密码是一种密码算法,其中明文中的字母顺序被重新排列以形成密文。在此过程中,不包括实际的纯文本字母。
例子
换位密码的一个简单示例是柱状换位密码,其中纯文本中的每个字符都以指定的字母宽度水平书写。密码是垂直书写的,这会产生完全不同的密码文本。
考虑纯文本hello world,让我们应用简单的列转置技术,如下所示
纯文本字符水平放置,密文以垂直格式创建:holewdlo lr。现在,接收者必须使用同一个表将密文解密为纯文本。
代码
以下程序代码演示了柱状转置技术的基本实现 -
def split_len(seq, length):
return [seq[i:i + length] for i in range(0, len(seq), length)]
def encode(key, plaintext):
order = {
int(val): num for num, val in enumerate(key)
}
ciphertext = ''
for index in sorted(order.keys()):
for part in split_len(plaintext, len(key)):
try:ciphertext += part[order[index]]
except IndexError:
continue
return ciphertext
print(encode('3214', 'HELLO'))
解释
使用函数split_len(),我们可以分割纯文本字符,可以将其放置为列式或行式格式。
编码方法有助于创建带有指定列数的密钥的密文,并通过读取每列中的字符来打印密文。
输出
柱状转置技术基本实现的程序代码给出以下输出 -
注意- 密码分析者观察到执行换位技术时密码安全性显着提高。他们还指出,使用相同的转置密码重新加密密文可以提高安全性。
转置密码加密
在上一章中,我们学习了转置密码。本章我们来讨论一下它的加密。
pyperclip
Python编程语言中pyperclip插件的主要用途是执行跨平台模块,将文本复制并粘贴到剪贴板。您可以使用如图所示的命令安装 python pyperclip模块
pip install pyperclip
如果系统中已存在该需求,您可以看到以下输出 -
代码
以 pyperclip 为主要模块的用于加密转置密码的 python 代码如下所示 -
import pyperclip
def main():
myMessage = 'Transposition Cipher'
myKey = 10
ciphertext = encryptMessage(myKey, myMessage)
print("Cipher Text is")
print(ciphertext + '|')
pyperclip.copy(ciphertext)
def encryptMessage(key, message):
ciphertext = [''] * key
for col in range(key):
position = col
while position < len(message):
ciphertext[col] += message[position]
position += key
return ''.join(ciphertext) #Cipher text
if __name__ == '__main__':
main()
输出
用于加密转置密码的程序代码(其中pyperclip是主要模块)给出以下输出 -
解释
函数main()调用encryptMessage() ,其中包括使用len函数分割字符并以列格式迭代它们的过程。
main 函数在最后初始化以获得适当的输出。
换位密码的解密
在本章中,您将学习解密转置密码的过程。
代码
请观察以下代码,以便更好地理解解密转置密码。密钥为6 的消息Transposition Cipher 的密文作为Toners raiCntisippoh 获取。
import math, pyperclip
def main():
myMessage= 'Toners raiCntisippoh'
myKey = 6
plaintext = decryptMessage(myKey, myMessage)
print("The plain text is")
print('Transposition Cipher')
def decryptMessage(key, message):
numOfColumns = math.ceil(len(message) / key)
numOfRows = key
numOfShadedBoxes = (numOfColumns * numOfRows) - len(message)
plaintext = float('') * numOfColumns
col = 0
row = 0
for symbol in message:
plaintext[col] += symbol
col += 1
if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes):
col = 0 row += 1 return ''.join(plaintext)
if __name__ == '__main__':
main()
解释
密文和所述密钥是通过将字符按列排列并横向读取的逆向技术对密文进行解码或解密的输入参数的两个值。
您可以将字母以列格式放置,然后使用以下代码将它们组合或连接在一起 -
for symbol in message: plaintext[col] += symbol col += 1 if (col == numOfColumns) or (col == numOfColumns - 1 and row >= numOfRows - numOfShadedBoxes): col = 0 row += 1 return ''.join(plaintext)
输出
用于解密转置密码的程序代码给出以下输出 -
文件加密
在Python中,可以在传输到通信通道之前对文件进行加密和解密。为此,您必须使用插件PyCrypto。您可以使用下面给出的命令安装此插件。
pip install pycrypto
代码
使用密码保护器加密文件的程序代码如下 -
# =================Other Configuration================
# Usages :
usage = "usage: %prog [options] "
# Version
Version="%prog 0.0.1"
# ====================================================
# Import Modules
import optparse, sys,os
from toolkit import processor as ps
def main():
parser = optparse.OptionParser(usage = usage,version = Version)
parser.add_option(
'-i','--input',type = 'string',dest = 'inputfile',
help = "File Input Path For Encryption", default = None)
parser.add_option(
'-o','--output',type = "string",dest = 'outputfile',
help = "File Output Path For Saving Encrypter Cipher",default = ".")
parser.add_option(
'-p','--password',type = "string",dest = 'password',
help = "Provide Password For Encrypting File",default = None)
parser.add_option(
'-p','--password',type = "string",dest = 'password',
help = "Provide Password For Encrypting File",default = None)
(options, args)= parser.parse_args()
# Input Conditions Checkings
if not options.inputfile or not os.path.isfile(options.inputfile):
print " [Error] Please Specify Input File Path"
exit(0)
if not options.outputfile or not os.path.isdir(options.outputfile):
print " [Error] Please Specify Output Path"
exit(0)
if not options.password:
print " [Error] No Password Input"
exit(0)
inputfile = options.inputfile
outputfile = os.path.join(
options.outputfile,os.path.basename(options.inputfile).split('.')[0]+'.ssb')
password = options.password
base = os.path.basename(inputfile).split('.')[1]
work = "E"
ps.FileCipher(inputfile,outputfile,password,work)
return
if __name__ == '__main__':
main()
您可以使用以下命令与密码一起执行加密过程 -
python pyfilecipher-encrypt.py -i file_path_for_encryption -o output_path -p password
输出
执行上面给出的代码时,您可以观察到以下输出 -
解释
密码是使用 MD5 哈希算法生成的,值存储在 Windows 系统中简单安全的备份文件中,其中包括如下所示的值 -
文件解密
在本章中,我们将讨论使用 Python 进行密码学中的文件解密。请注意,对于解密过程,我们将遵循相同的过程,但我们将重点关注输入路径或加密的必要文件,而不是指定输出路径。
代码
以下是使用 Python 解密文件的示例代码 -
#!/usr/bin/python
# ---------------- READ ME ---------------------------------------------
# This Script is Created Only For Practise And Educational Purpose Only
# This Script Is Created For http://bitforestinfo.blogspot.in
# This Script is Written By
#
#
##################################################
######## Please Don't Remove Author Name #########
############### Thanks ###########################
##################################################
#
#
# =================Other Configuration================
# Usages :
usage = "usage: %prog [options] "
# Version
Version="%prog 0.0.1"
# ====================================================
# Import Modules
import optparse, sys,os
from toolkit import processor as ps
def main():
parser = optparse.OptionParser(usage = usage,version = Version)
parser.add_option(
'-i','--input',type = 'string',dest = 'inputfile',
help = "File Input Path For Encryption", default = None)
parser.add_option(
'-o','--output',type = "string",dest = 'outputfile',
help = "File Output Path For Saving Encrypter Cipher",default = ".")
parser.add_option(
'-p','--password',type = "string",dest = 'password',
help = "Provide Password For Encrypting File",default = None)
(options, args) = parser.parse_args()
# Input Conditions Checkings
if not options.inputfile or not os.path.isfile(options.inputfile):
print " [Error] Please Specify Input File Path"
exit(0)
if not options.outputfile or not os.path.isdir(options.outputfile):
print " [Error] Please Specify Output Path"
exit(0)
if not options.password:
print " [Error] No
exit(0)
inputfile = options.inputfile
outputfile = options.outputfile
password = options.password
work = "D"
ps.FileCipher(inputfile,outputfile,password,work)
return
if __name__ == '__main__':
main()
您可以使用以下命令来执行上述代码 -
python pyfilecipher-decrypt.py -i encrypted_file_path -p password
输出
当您执行上面显示的命令时,您可以观察到以下代码 -
注意- 输出指定加密前和解密后的哈希值,这会记录同一文件已加密且过程成功。
Base64编码与解码
Base64 编码将二进制数据转换为文本格式,通过通信通道传递,用户可以安全地处理文本。Base64 也称为隐私增强电子邮件 (PEM),主要用于电子邮件加密过程。
Python 包含一个名为BASE64的模块,其中包含两个主要函数,如下所示 -
base64.decode(input, output) - 它解码指定的输入值参数并将解码的输出存储为对象。
Base64.encode(input, output) - 它对指定的输入值参数进行编码并将解码的输出存储为对象。
编码程序
您可以使用以下代码来执行base64编码 -
import base64
encoded_data = base64.b64encode("Encode this text")
print("Encoded text with base 64 is")
print(encoded_data)
输出
Base64 编码的代码为您提供以下输出 -
解码程序
您可以使用以下代码来执行 Base64 解码 -
import base64
decoded_data = base64.b64decode("RW5jb2RlIHRoaXMgdGV4dA==")
print("decoded text is ")
print(decoded_data)
输出
Base64 解码的代码为您提供以下输出 -
ASCII 和 Base64 之间的区别
当您使用 ASCII 和 base64 编码数据时,您可以观察到以下差异 -
当您使用 ASCII 编码文本时,您从文本字符串开始并将其转换为字节序列。
当您以 Base64 编码数据时,您从字节序列开始并将其转换为文本字符串。
退税
Base64算法通常用于在数据库中存储密码。主要缺点是每个解码的单词都可以通过任何在线工具轻松编码,入侵者可以轻松获取信息。
使用 Python 进行密码学 - 异或过程
在本章中,让我们了解 XOR 过程及其在 Python 中的编码。
算法
加解密的XOR算法将ASCII字节格式的明文转换为XOR过程,将其转换为指定的字节。它为其用户提供以下优势 -
- 快速计算
- 左右两侧无明显差异
- 易于理解和分析
代码
您可以使用以下代码来执行异或过程 -
def xor_crypt_string(data, key = 'awesomepassword', encode = False, decode = False):
from itertools import izip, cycle
import base64
if decode:
data = base64.decodestring(data)
xored = ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key)))
if encode:
return base64.encodestring(xored).strip()
return xored
secret_data = "XOR procedure"
print("The cipher text is")
print xor_crypt_string(secret_data, encode = True)
print("The plain text fetched")
print xor_crypt_string(xor_crypt_string(secret_data, encode = True), decode = True)
输出
XOR 过程的代码为您提供以下输出 -
解释
函数xor_crypt_string()包含一个参数来指定编码和解码模式以及字符串值。
基本功能由base64模块实现,该模块遵循XOR过程/操作来加密或解密纯文本/密文。
注- XOR 加密用于加密数据,很难通过暴力方法破解,即通过生成随机加密密钥来匹配正确的密文。
乘法密码
在使用凯撒密码技术时,加密和解密符号涉及通过简单的加法或减法基本过程将值转换为数字。
如果使用乘法来转换为密文,则称为环绕情况。考虑要使用的字母和相关数字,如下所示 -
这些数字将用于乘法过程,相关密钥为 7。在这种情况下生成乘法密码的基本公式如下 -
(Alphabet Number * key)mod(total number of alphabets)
将输出取出的数字映射到上表中,将对应的字母作为加密后的字母。
Python 中乘法密码的基本调制函数如下 -
def unshift(key, ch): offset = ord(ch) - ASC_A return chr(((key[0] * (offset + key[1])) % WIDTH) + ASC_A)
注意- 乘法密码的优点是它可以使用非常大的密钥,例如 8,953,851。计算机要暴力破解 900 万个密钥中的大多数,需要相当长的时间。
Python 密码学 - 仿射密码
仿射密码是乘法密码和凯撒密码算法的结合。仿射密码的基本实现如下图所示 -
在本章中,我们将通过创建相应的类来实现仿射密码,该类包括加密和解密的两个基本函数。
代码
您可以使用以下代码来实现仿射密码 -
class Affine(object):
DIE = 128
KEY = (7, 3, 55)
def __init__(self):
pass
def encryptChar(self, char):
K1, K2, kI = self.KEY
return chr((K1 * ord(char) + K2) % self.DIE)
def encrypt(self, string):
return "".join(map(self.encryptChar, string))
def decryptChar(self, char):
K1, K2, KI = self.KEY
return chr(KI * (ord(char) - K2) % self.DIE)
def decrypt(self, string):
return "".join(map(self.decryptChar, string))
affine = Affine()
print affine.encrypt('Affine Cipher')
print affine.decrypt('*18?FMT')
输出
当您实现仿射密码时,您可以观察到以下输出 -
输出显示纯文本消息Affine Cipher的加密消息和作为输入abcdefg发送的消息的解密消息。
破解单字母密码
在本章中,您将了解单字母密码及其使用 Python 的黑客攻击。
单表密码
单字母密码使用固定替换来加密整个消息。这里显示了使用带有 JSON 对象的 Python 字典的单字母密码 -
monoalpha_cipher = {
'a': 'm',
'b': 'n',
'c': 'b',
'd': 'v',
'e': 'c',
'f': 'x',
'g': 'z',
'h': 'a',
'i': 's',
'j': 'd',
'k': 'f',
'l': 'g',
'm': 'h',
'n': 'j',
'o': 'k',
'p': 'l',
'q': 'p',
'r': 'o',
's': 'i',
't': 'u',
'u': 'y',
'v': 't',
'w': 'r',
'x': 'e',
'y': 'w',
'z': 'q',
' ': ' ',
}
借助该字典,我们可以将字母与关联字母加密为 JSON 对象中的值。以下程序创建一个单字母程序作为类表示,其中包括所有加密和解密函数。
from string import letters, digits
from random import shuffle
def random_monoalpha_cipher(pool = None):
if pool is None:
pool = letters + digits
original_pool = list(pool)
shuffled_pool = list(pool)
shuffle(shuffled_pool)
return dict(zip(original_pool, shuffled_pool))
def inverse_monoalpha_cipher(monoalpha_cipher):
inverse_monoalpha = {}
for key, value in monoalpha_cipher.iteritems():
inverse_monoalpha[value] = key
return inverse_monoalpha
def encrypt_with_monoalpha(message, monoalpha_cipher):
encrypted_message = []
for letter in message:
encrypted_message.append(monoalpha_cipher.get(letter, letter))
return ''.join(encrypted_message)
def decrypt_with_monoalpha(encrypted_message, monoalpha_cipher):
return encrypt_with_monoalpha(
encrypted_message,
inverse_monoalpha_cipher(monoalpha_cipher)
)
稍后调用该文件来实现单字母密码的加密和解密过程,如下所述 -
import monoalphabeticCipher as mc
cipher = mc.random_monoalpha_cipher()
print(cipher)
encrypted = mc.encrypt_with_monoalpha('Hello all you hackers out there!', cipher)
decrypted = mc.decrypt_with_monoalpha('sXGGt SGG Nt0 HSrLXFC t0U UHXFX!', cipher)
print(encrypted)
print(decrypted)
输出
当您实现上面给出的代码时,您可以观察到以下输出 -
因此,您可以使用指定的键值对破解单字母密码,将密文破解为实际的纯文本。
简单替换密码
简单替换密码是最常用的密码,包括用每个明文字符替换每个密文字符的算法。在这个过程中,与凯撒密码算法相比,字母表是混乱的。
例子
简单替换密码的密钥通常由 26 个字母组成。一个示例键是 -
plain alphabet : abcdefghijklmnopqrstuvwxyz cipher alphabet: phqgiumeaylnofdxjkrcvstzwb
使用上述密钥的加密示例是:
plaintext : defend the east wall of the castle ciphertext: giuifg cei iprc tpnn du cei qprcni
以下代码显示了实现简单替换密码的程序 -
import random, sys
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
message = ''
if len(sys.argv) > 1:
with open(sys.argv[1], 'r') as f:
message = f.read()
else:
message = raw_input("Enter your message: ")
mode = raw_input("E for Encrypt, D for Decrypt: ")
key = ''
while checkKey(key) is False:
key = raw_input("Enter 26 ALPHA key (leave blank for random key): ")
if key == '':
key = getRandomKey()
if checkKey(key) is False:
print('There is an error in the key or symbol set.')
translated = translateMessage(message, key, mode)
print('Using key: %s' % (key))
if len(sys.argv) > 1:
fileOut = 'enc.' + sys.argv[1]
with open(fileOut, 'w') as f:
f.write(translated)
print('Success! File written to: %s' % (fileOut))
else: print('Result: ' + translated)
# Store the key into list, sort it, convert back, compare to alphabet.
def checkKey(key):
keyString = ''.join(sorted(list(key)))
return keyString == LETTERS
def translateMessage(message, key, mode):
translated = ''
charsA = LETTERS
charsB = key
# If decrypt mode is detected, swap A and B
if mode == 'D':
charsA, charsB = charsB, charsA
for symbol in message:
if symbol.upper() in charsA:
symIndex = charsA.find(symbol.upper())
if symbol.isupper():
translated += charsB[symIndex].upper()
else:
translated += charsB[symIndex].lower()
else:
translated += symbol
return translated
def getRandomKey():
randomList = list(LETTERS)
random.shuffle(randomList)
return ''.join(randomList)
if __name__ == '__main__':
main()
输出
当您实现上面给出的代码时,您可以观察到以下输出 -
简单替换密码的测试
在本章中,我们将重点使用各种方法测试替换密码,这有助于生成随机字符串,如下所示 -
import random, string, substitution
def main():
for i in range(1000):
key = substitution.getRandomKey()
message = random_string()
print('Test %s: String: "%s.."' % (i + 1, message[:50]))
print("Key: " + key)
encrypted = substitution.translateMessage(message, key, 'E')
decrypted = substitution.translateMessage(encrypted, key, 'D')
if decrypted != message:
print('ERROR: Decrypted: "%s" Key: %s' % (decrypted, key))
sys.exit()
print('Substutition test passed!')
def random_string(size = 5000, chars = string.ascii_letters + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
if __name__ == '__main__':
main()
输出
您可以将输出观察为随机生成的字符串,这有助于生成随机纯文本消息,如下所示 -
测试成功完成后,我们可以观察到输出消息Substitution test Passed!。
因此,您可以系统地破解替代密码。
简单替换密码的解密
在本章中,您可以了解替换密码的简单实现,它根据简单替换密码技术中使用的逻辑显示加密和解密的消息。这可以被视为编码的替代方法。
代码
您可以使用以下代码使用简单替换密码来执行解密 -
import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + \
'abcdefghijklmnopqrstuvwxyz' + \
'0123456789' + \
':.;,?!@#$%&()+=-*/_<> []{}`~^"\'\\'
def generate_key():
"""Generate an key for our cipher"""
shuffled = sorted(chars, key=lambda k: random.random())
return dict(zip(chars, shuffled))
def encrypt(key, plaintext):
"""Encrypt the string and return the ciphertext"""
return ''.join(key[l] for l in plaintext)
def decrypt(key, ciphertext):
"""Decrypt the string and return the plaintext"""
flipped = {v: k for k, v in key.items()}
return ''.join(flipped[l] for l in ciphertext)
def show_result(plaintext):
"""Generate a resulting cipher with elements shown"""
key = generate_key()
encrypted = encrypt(key, plaintext)
decrypted = decrypt(key, encrypted)
print 'Key: %s' % key
print 'Plaintext: %s' % plaintext
print 'Encrypted: %s' % encrypted
print 'Decrypted: %s' % decrypted
show_result('Hello World. This is demo of substitution cipher')
输出
上面的代码给出的输出如下所示 -
Python 密码学模块
在本章中,您将详细了解Python中密码学的各个模块。
密码模块
它包含所有配方和原语,并提供 Python 编码的高级接口。您可以使用以下命令安装加密模块 -
pip install cryptography
代码
您可以使用以下代码来实现加密模块 -
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt("This example is used to demonstrate cryptography module")
plain_text = cipher_suite.decrypt(cipher_text)
输出
上面给出的代码产生以下输出 -
此处给出的代码用于验证密码并创建其哈希值。它还包括用于验证密码以进行身份验证的逻辑。
import uuid
import hashlib
def hash_password(password):
# uuid is used to generate a random number of the specified password
salt = uuid.uuid4().hex
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt
def check_password(hashed_password, user_password):
password, salt = hashed_password.split(':')
return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()
new_pass = input('Please enter a password: ')
hashed_password = hash_password(new_pass)
print('The string to store in the db is: ' + hashed_password)
old_pass = input('Now please enter the password again to check: ')
if check_password(hashed_password, old_pass):
print('You entered the right password')
else:
print('Passwords do not match')
输出
场景 1 - 如果您输入了正确的密码,您可以找到以下输出 -
场景 2 - 如果我们输入错误的密码,您可以看到以下输出 -
解释
Hashlib包用于在数据库中存储密码。在此程序中,使用salt在实现哈希函数之前将随机序列添加到密码字符串中。
了解维涅雷密码
Vignere Cipher 包含了用于加密和解密的 Caesar Cipher 算法的变化。Vignere Cipher 的工作原理与 Caesar Cipher 算法类似,只有一个主要区别:Caesar Cipher 包括单字符移位算法,而 Vignere Cipher 包括具有多个字母移位的密钥。
数学方程
对于加密,数学方程如下 -
$$E_{k}\left ( M{_{i{}}} \right ) = \left ( M_{i}+K_{i} \right )\;\;\; 模组\;\; 26$$
对于解密,数学方程如下 -
$$D_{k}\left ( C{_{i{}}} \right ) = \left ( C_{i}-K_{i} \right )\;\;\; 模组\;\; 26$$
Vignere 密码使用多于一组的替换,因此它也称为多表密码。Vignere Cipher 将使用字母密钥而不是数字密钥表示:字母 A 将用于密钥 0,字母 B 将用于密钥 1,依此类推。加密过程之前和之后的字母数量如下所示 -
基于 Vignere 密钥长度的可能密钥数量的可能组合如下,给出了 Vignere 密码算法的安全性结果 -
维涅尔画面
Vignere 密码使用的表格如下所示 -
实施维涅尔密码
在本章中,让我们了解如何实现 Vignere 密码。考虑文本“这是 Vignere 密码的基本实现,需要进行编码”,使用的密钥是PIZZA。
代码
您可以使用以下代码在 Python 中实现 Vignere 密码 -
import pyperclip
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
myMessage = "This is basic implementation of Vignere Cipher"
myKey = 'PIZZA'
myMode = 'encrypt'
if myMode == 'encrypt':
translated = encryptMessage(myKey, myMessage)
elif myMode == 'decrypt':
translated = decryptMessage(myKey, myMessage)
print('%sed message:' % (myMode.title()))
print(translated)
print()
def encryptMessage(key, message):
return translateMessage(key, message, 'encrypt')
def decryptMessage(key, message):
return translateMessage(key, message, 'decrypt')
def translateMessage(key, message, mode):
translated = [] # stores the encrypted/decrypted message string
keyIndex = 0
key = key.upper()
for symbol in message:
num = LETTERS.find(symbol.upper())
if num != -1:
if mode == 'encrypt':
num += LETTERS.find(key[keyIndex])
elif mode == 'decrypt':
num -= LETTERS.find(key[keyIndex])
num %= len(LETTERS)
if symbol.isupper():
translated.append(LETTERS[num])
elif symbol.islower():
translated.append(LETTERS[num].lower())
keyIndex += 1
if keyIndex == len(key):
keyIndex = 0
else:
translated.append(symbol)
return ''.join(translated)
if __name__ == '__main__':
main()
输出
当您实现上面给出的代码时,您可以观察到以下输出 -
破解维涅尔密码的可能组合几乎是不可能的。因此,它被认为是一种安全的加密模式。
一次性一密密码
一次性密码是 Vignere 密码的一种,包括以下功能 -
这是一个牢不可破的密码。
密钥与加密消息的长度完全相同。
密钥由随机符号组成。
顾名思义,密钥仅使用一次,并且不会再次用于任何其他要加密的消息。
因此,加密的消息很容易受到密码分析者的攻击。用于一次性密码的密钥称为pad,因为它打印在一叠纸上。
为什么它坚不可摧?
由于具有以下特征,密钥牢不可破 -
密钥与给定的消息一样长。
密钥是真正随机的并且是专门自动生成的。
密钥和纯文本按模 10/26/2 计算。
每个密钥应使用一次并由发送者和接收者销毁。
密钥应有两份:一份属于发送者,另一份属于接收者。
加密
要加密信件,用户需要在明文下面写入密钥。明文字母位于顶部,密钥字母位于左侧。两个字母之间的横截面就是纯文本。下面的示例对此进行了描述 -
解密
要解密字母,用户获取左侧的密钥字母并在该行中找到密文字母。明文字母放置在列的顶部,用户可以在其中找到密文字母。
一次性一密密码的实现
Python 包含一个用于一次性密码实现的 hacky 实现模块。该软件包名称为 One-Time-Pad,其中包含一个命令行加密工具,该工具使用类似于一次性密码算法的加密机制。
安装
您可以使用以下命令来安装此模块 -
pip install onetimepad
如果您想从命令行使用它,请运行以下命令 -
onetimepad
代码
以下代码有助于生成一次性密码本密码 -
import onetimepad
cipher = onetimepad.encrypt('One Time Cipher', 'random')
print("Cipher text is ")
print(cipher)
print("Plain text is ")
msg = onetimepad.decrypt(cipher, 'random')
print(msg)
输出
运行上面给出的代码时,您可以观察到以下输出 -
注意- 如果密钥的长度小于消息(纯文本)的长度,则加密的消息很容易被破解。
无论如何,密钥不一定是随机的,这使得一次性密码成为一种有价值的工具。
对称和非对称密码学
在本章中,让我们详细讨论对称和非对称密码学。
对称密码学
在这种类型中,加密和解密过程使用相同的密钥。它也称为秘密密钥密码术。对称密码学的主要特点如下 -
- 它更简单、更快。
- 双方以安全的方式交换密钥。
退税
对称加密的主要缺点是,如果密钥泄露给入侵者,消息可以很容易地被更改,这被认为是一个风险因素。
数据加密标准 (DES)
最流行的对称密钥算法是数据加密标准 (DES),Python 包含一个包,其中包含 DES 算法背后的逻辑。
安装
在 Python 中安装 DES 包pyDES的命令是 -
pip install pyDES
DES算法的简单程序实现如下 -
import pyDes
data = "DES Algorithm Implementation"
k = pyDes.des("DESCRYPT", pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5)
d = k.encrypt(data)
print "Encrypted: %r" % d
print "Decrypted: %r" % k.decrypt(d)
assert k.decrypt(d) == data
它调用变量padmode,该变量根据 DES 算法实现获取所有包,并以指定方式进行加密和解密。
输出
您可以看到上面给出的代码的结果如下 -
非对称密码学
它也称为公钥密码术。它的工作原理与对称密码学相反。这意味着它需要两个密钥:一个用于加密,另一个用于解密。公钥用于加密,私钥用于解密。
退税
- 由于其密钥长度,它的加密速度较低。
- 密钥管理至关重要。
以下 Python 程序代码说明了使用 RSA 算法的非对称加密的工作原理及其实现 -
from Crypto import Random from Crypto.PublicKey import RSA import base64 def generate_keys(): # key length must be a multiple of 256 and >= 1024 modulus_length = 256*4 privatekey = RSA.generate(modulus_length, Random.new().read) publickey = privatekey.publickey() return privatekey, publickey def encrypt_message(a_message , publickey): encrypted_msg = publickey.encrypt(a_message, 32)[0] encoded_encrypted_msg = base64.b64encode(encrypted_msg) return encoded_encrypted_msg def decrypt_message(encoded_encrypted_msg, privatekey): decoded_encrypted_msg = base64.b64decode(encoded_encrypted_msg) decoded_decrypted_msg = privatekey.decrypt(decoded_encrypted_msg) return decoded_decrypted_msg a_message = "This is the illustration of RSA algorithm of asymmetric cryptography" privatekey , publickey = generate_keys() encrypted_msg = encrypt_message(a_message , publickey) decrypted_msg = decrypt_message(encrypted_msg, privatekey) print "%s - (%d)" % (privatekey.exportKey() , len(privatekey.exportKey())) print "%s - (%d)" % (publickey.exportKey() , len(publickey.exportKey())) print " Original content: %s - (%d)" % (a_message, len(a_message)) print "Encrypted message: %s - (%d)" % (encrypted_msg, len(encrypted_msg)) print "Decrypted message: %s - (%d)" % (decrypted_msg, len(decrypted_msg))
输出
执行上面给出的代码时,您可以找到以下输出 -
了解RSA算法
RSA算法是一种公钥加密技术,被认为是最安全的加密方式。它由 Rivest、Shamir 和 Adleman 于 1978 年发明,因此命名为RSA算法。
算法
RSA 算法具有以下特点 -
RSA 算法是有限域中对整数(包括素数)进行求幂的一种流行算法。
该方法使用的整数足够大,使得求解变得困难。
该算法中有两组密钥:私钥和公钥。
您必须执行以下步骤才能使用 RSA 算法 -
第 1 步:生成 RSA 模数
初始过程首先选择两个素数,即 p 和 q,然后计算它们的乘积 N,如下所示 -
N=p*q
这里,令N为指定的大数。
步骤 2:派生数 (e)
将数字 e 视为派生数,它应大于 1 且小于 (p-1) 和 (q-1)。主要条件是 (p-1) 和 (q-1) 不应有除 1 之外的公因数
第三步:公钥
指定的数字对n和e形成 RSA 公钥并公开。
第四步:私钥
私钥d是根据数字 p、q 和 e 计算得出的。数字之间的数学关系如下 -
ed = 1 mod (p-1) (q-1)
上式是扩展欧几里得算法的基本公式,它以p和q为输入参数。
加密公式
考虑一个发件人将纯文本消息发送给公钥为(n,e) 的某人。要在给定场景中加密纯文本消息,请使用以下语法 -
C = Pe mod n
解密公式
解密过程非常简单,包括系统方法的计算分析。考虑到接收者C拥有私钥d,结果模数将计算为 -
Plaintext = Cd mod n
创建 RSA 密钥
在本章中,我们将重点介绍使用 Python 逐步实现 RSA 算法。
生成 RSA 密钥
生成 RSA 密钥涉及以下步骤 -
创建两个大素数,即p和q。这些数字的乘积称为n,其中n= p*q
生成与(p-1)和(q-1)互质的随机数。将该数字称为e。
计算 e 的模逆。计算出的倒数将被称为d。
生成 RSA 密钥的算法
我们需要两种主要算法来使用 Python 生成 RSA 密钥 - Cryptomath 模块和Rabin Miller 模块。
密码数学模块
遵循 RSA 算法所有基本实现的 cryptomath 模块的源代码如下 -
def gcd(a, b):
while a != 0:
a, b = b % a, a
return b
def findModInverse(a, m):
if gcd(a, m) != 1:
return None
u1, u2, u3 = 1, 0, a
v1, v2, v3 = 0, 1, m
while v3 != 0:
q = u3 // v3
v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
return u1 % m
拉宾米勒模块
RabinMiller 模块的源代码遵循 RSA 算法的所有基本实现,如下所示 -
import random
def rabinMiller(num):
s = num - 1
t = 0
while s % 2 == 0:
s = s // 2
t += 1
for trials in range(5):
a = random.randrange(2, num - 1)
v = pow(a, s, num)
if v != 1:
i = 0
while v != (num - 1):
if i == t - 1:
return False
else:
i = i + 1
v = (v ** 2) % num
return True
def isPrime(num):
if (num 7< 2):
return False
lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61,
67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241,
251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449,
457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569,
571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661,
673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787,
797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,
911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
if num in lowPrimes:
return True
for prime in lowPrimes:
if (num % prime == 0):
return False
return rabinMiller(num)
def generateLargePrime(keysize = 1024):
while True:
num = random.randrange(2**(keysize-1), 2**(keysize))
if isPrime(num):
return num
生成 RSA 密钥的完整代码如下 -
import random, sys, os, rabinMiller, cryptomath
def main():
makeKeyFiles('RSA_demo', 1024)
def generateKey(keySize):
# Step 1: Create two prime numbers, p and q. Calculate n = p * q.
print('Generating p prime...')
p = rabinMiller.generateLargePrime(keySize)
print('Generating q prime...')
q = rabinMiller.generateLargePrime(keySize)
n = p * q
# Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
print('Generating e that is relatively prime to (p-1)*(q-1)...')
while True:
e = random.randrange(2 ** (keySize - 1), 2 ** (keySize))
if cryptomath.gcd(e, (p - 1) * (q - 1)) == 1:
break
# Step 3: Calculate d, the mod inverse of e.
print('Calculating d that is mod inverse of e...')
d = cryptomath.findModInverse(e, (p - 1) * (q - 1))
publicKey = (n, e)
privateKey = (n, d)
print('Public key:', publicKey)
print('Private key:', privateKey)
return (publicKey, privateKey)
def makeKeyFiles(name, keySize):
# Creates two files 'x_pubkey.txt' and 'x_privkey.txt'
(where x is the value in name) with the the n,e and d,e integers written in them,
# delimited by a comma.
if os.path.exists('%s_pubkey.txt' % (name)) or os.path.exists('%s_privkey.txt' % (name)):
sys.exit('WARNING: The file %s_pubkey.txt or %s_privkey.txt already exists! Use a different name or delete these files and re-run this program.' % (name, name))
publicKey, privateKey = generateKey(keySize)
print()
print('The public key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1]))))
print('Writing public key to file %s_pubkey.txt...' % (name))
fo = open('%s_pubkey.txt' % (name), 'w')
fo.write('%s,%s,%s' % (keySize, publicKey[0], publicKey[1]))
fo.close()
print()
print('The private key is a %s and a %s digit number.' % (len(str(publicKey[0])), len(str(publicKey[1]))))
print('Writing private key to file %s_privkey.txt...' % (name))
fo = open('%s_privkey.txt' % (name), 'w')
fo.write('%s,%s,%s' % (keySize, privateKey[0], privateKey[1]))
fo.close()
# If makeRsaKeys.py is run (instead of imported as a module) call
# the main() function.
if __name__ == '__main__':
main()
输出
生成公钥和私钥并将其保存在各自的文件中,如以下输出所示。
RSA 密码加密
在本章中,我们将重点关注 RSA 密码加密的不同实现及其所涉及的函数。您可以参考或包含此 python 文件来实现 RSA 密码算法实现。
加密算法包含的模块如下 -
from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_