0


Python实现字符串与指定密钥循环异或加解密

异或运算在很多密码学算法中都有不同程度的应用,其运算特定在于一个数和另一个数连续异或两次仍得到原来的数。在实际使用中,因为要加密的信息和所使用的密钥在大多数情况下是不等长的,所以经常需要循环使用密钥。

def crypt1(source, key):

  1. '''source是要加密或解密的字符串,key是密钥字符串'''
  2. #result用来存放最终结果
  3. #index表示当前使用的密钥字符索引
  4. result = ''
  5. index = 0
  6. #遍历字符串中的每个字符
  7. for ch in source:
  8. #循环使用密钥字符串中的每个字符
  9. #如果已到最后一个字符,再从0重新开始
  10. if index == len(key):
  11. index = 0
  12. #异或运算
  13. result += chr(ord(ch) ^ ord(key[index]))
  14. index = index + 1
  15. return result

#也可以写成下面更简洁的形式

def crypt2(source, key):

  1. from itertools import cycle
  2. result = ''
  3. temp = cycle(key)
  4. for ch in source:
  5. result += chr(ord(ch) ^ ord(next(temp)))
  6. return result

source = '中国,Shandong 2016'

key = 'Dong Fuguo'

#测试

for func in (crypt1, crypt2):

  1. print('function name:', func.__name__)
  2. print('plain text:', source)
  3. c = func(source, key)
  4. print('crypted text:', c)
  5. m = func(c, key)
  6. print('decrypted text:', m)
  7. print('='*30)

上面的代码运行结果为:


本文转载自: https://blog.csdn.net/dongfuguo/article/details/118704613
版权归原作者 dongfuguo 所有, 如有侵权,请联系我们删除。

“Python实现字符串与指定密钥循环异或加解密”的评论:

还没有评论