[python] 密码学:代换密码的实现

《密码学原理与实践》中古典密码的第二个内容就讲到了代换密码。

理论公式为:(截图来自原书)

[python] 密码学:代换密码的实现_第1张图片


随后书中给出了一个例题,如下(截图来自原书)



这种加密方法就是将某个字母唯一的与任意字母组成一一对应的关系:

例题中的表就是一个加密函数,例题的结尾给出了一个问题,让读者解密密文。

我的python代码如下:

import sys,getopt
plainfile=''
cipherfile=''
plainstring=''
cipherstring=''


encryDict={'\n':'\n',' ':' ','a':'X','b':'N','c':'Y','d':'A','e':'H','f':'P','g':'O','h':'G','i':'Z','j':'Q','k':'W','l':'B','m':'T','n':'S','o':'F','p':'L','q':'R','r':'C','s':'V','t':'M','u':'U','v':'E','w':'K','x':'J','y':'D','z':'I'}

def help():
	'HELP FUNCTION'
	print '''
	-h:help
	-i:plaintext filename
	-o:ciphertext filename
	--plain:plain-string
	--cipher:cipher-string
	'''

def encrypt(plainstring):
	'ENCRYPT FUNCTION'
#	print "plainstring:",plainstring
	cipher_array=[0 for i in range (len(plainstring))] #init the array
#	print cipher_array
	flag = 0
	for i in range(len(plainstring)):
		flag = 0
		for key in encryDict:
			if plainstring[i] == key:
				cipher_array[i] = encryDict[key]
				flag = 1
		if flag == 0:
			cipher_array[i] = plainstring[i]
	cipherstring_local = ''.join(cipher_array)
	return cipherstring_local

def decrypt(cipherstring):
	'DECRYPT FUNCTION'
#	print "cipherstring:",cipherstring
	plain_array=[0 for i in range (len(cipherstring))] #init the array
#	print plain_array
	flag = 0
	for i in range(len(cipherstring)):
		flag = 0
		for key in encryDict:
			if cipherstring[i] == encryDict[key]:
				plain_array[i] = key
				flag = 1
		if flag == 0:
			plain_array[i] = cipherstring[i]
	plainstring_local = ''.join(plain_array)
	return plainstring_local

def fileEncrypt(thefile):
	'ENCRYPT info in TXT'
	try:
		fobj_r = open(thefile,'r')
		all_the_text = fobj_r.read()
		fobj_r.close()

		fobj_w = open(thefile,'w')
		print >> fobj_w,encrypt(all_the_text)
		fobj_w.close()
	except IOError,e:
		print "ERROR INFO:",e
		

def fileDecrypt(thefile):
	'DECRYPT info in TXT'
	try:
		fobj_r = open(thefile,'r')
		all_the_text = fobj_r.read()
		fobj_r.close()
	
		fobj_w = open(thefile,'w')
		print >> fobj_w,decrypt(all_the_text)
		fobj_w.close()
	except IOError,e:
		print "ERROR INFO:",e

def main():
	'MAIN FUNCTION'
	opts,args=getopt.getopt(sys.argv[1:],"hc:d:",["plain=","cipher="])
	for op,value in opts:
		if op=="-h":
			help()
	for op,value in opts:
		if op=="-c":
			plainfile=value
			fileEncrypt(plainfile)
	for op,value in opts:
		if op=="-d":
			cipherfile=value
			fileDecrypt(cipherfile)
	for op,value in opts:
		if op=="--plain":
			plainstring=value
			cipherstring=encrypt(plainstring)
			print "cipher:",cipherstring
	for op,value in opts:
		if op=="--cipher":
			cipherstring=value
			plainstring=decrypt(cipherstring)
			print "plain:",plainstring

if __name__=="__main__":
	main()

运行如下:

[python] 密码学:代换密码的实现_第2张图片


可知原文的内容为thisciphertextcannotbedecrypted

完毕


你可能感兴趣的:([python] 密码学:代换密码的实现)