这次我们复习加解密算法。
一、替代加密法 凯撒密码是应用替代方法加密的经典例子。以下是python实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 def encrypt (): p, key = input ('请输入明文(仅限小写英文字母):' ), int (input ('请输入密钥(密钥为自然数):' )) c = '' for i in range (len (p)): if 'a' <= p[i] <= 'z' : c += chr ((ord (p[i]) - 97 + key) % 26 + 97 ) else : return '输入有误' return '密文:' + cdef decrypt (): c, key = input ('请输入密文(仅限小写英文字母):' ), int (input ('请输入密钥(密钥为自然数):' )) p = '' for i in range (len (c)): if 'a' <= c[i] <= 'z' : m = ord (c[i]) - key if m < 97 : m += 26 p += chr (m) else : return '输入有误' return '明文:' + pif __name__ == "__main__" : select = input ('加密选1,解密选2:' ) if select == '1' : print(encrypt()) elif select == '2' : print(decrypt()) else : print('输入有误' )
二、换位密码法 换位的规则有有很多,这里选取的是 前后部分先倒序再互换。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 def encrypt (): p, key = input ('请输入明文:' ), int (input ('请输入密钥(密钥为正整数):' )) c = '' key %= len (p) if key == 0 : return '密文:' + p s1 = p[0 :key][::-1 ] s2 = p[key:len (p)][::-1 ] c = s2 + s1 return '密文:' + cdef decrypt (): c, key = input ('请输入密文:' ), int (input ('请输入密钥(密钥为正整数):' )) p = '' key = len (p) - key % len (c) if key == 0 : return '明文:' + c s1 = c[0 :key][::-1 ] s2 = c[key:len (c)][::-1 ] p = s2 + s1 return '明文:' + pif __name__ == "__main__" : select = input ('加密选1,解密选2:' ) if select == '1' : print(encrypt()) elif select == '2' : print(decrypt()) else : print('输入有误' )
三、简单异或法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 def encrypt (): p, key = input ('请输入明文:' ), input ('请输入密钥(密钥为二进制数):' ) c = [] l = [] for i in range (len (p)): l.append(bin (ord (p[i])).replace('0b' , '' )) for i in range (len (p)): x = '' lenkey, lenpb = len (key), len (l[i]) if lenkey < lenpb: key += (lenpb - lenkey) * '0' elif lenkey > lenpb: key = key[0 :lenpb] for j in range (lenpb): x += str (int (l[i][j]) ^ int (key[j])) c.append(x) return '密文:' + '' .join(c)def decrypt (): c, key, length = input ('请输入密文:' ), input ('请输入密钥(密钥为二进制数):' ), int (input ('请输入密文内含字符数:' )) p = [] l = [] s = 0 for i in range (length): m = int (input ('请输入第' + str (i + 1 ) + '个密文二进制数的长度:' )) l.append(c[s: s + m]) s += m for i in range (length): x = '' lenkey, lencb = len (key), len (l[i]) if lenkey < lencb: key += (lencb - lenkey) * '0' elif lenkey > lencb: key = key[0 :lencb] for j in range (lencb): x += str (int (l[i][j]) ^ int (key[j])) p.append(chr (int (x, 2 ))) return '明文:' + '' .join(p)if __name__ == "__main__" : select = input ('加密选1,解密选2:' ) if select == '1' : print(encrypt()) elif select == '2' : print(decrypt()) else : print('输入有误' )
由于博主能力有限,所以虽然加密算法可以加密任何字符集的字符,但是解密算法却只能解密ASCII码集的字符。
效果如下:
加密ASCII码集字符
解密ASCII码集字符
加密UTF-8码集和ASCII码集的字符
— 【参考资料 —— 网络文献】