看题目名字就能猜测和DES有关系,直接看所给的python代码也能看出和现有的DES遵循一个同样的框架,更确切来说,和现行DES都遵循feistel结构,其中要求轮函数F是自反的,即

F(x)=y    F(y)=x

这里的F就是代码中的round_add函数,很容易能写出对应的解密函数,跟加密函数完全相反就可以。

  1. def encrypt(self, plaintext):
  2. if (len(plaintext) % 16 != 0 or isinstance(plaintext, bytes) == False):
  3. raise Exception("plaintext must be a multiple of 16 in length")
  4. res = ''
  5. for i in range(len(plaintext) / 16):
  6. block = plaintext[i * 16:(i + 1) * 16]
  7. L = block[:8]
  8. R = block[8:]
  9. for round_cnt in range(32):
  10. L, R = R, (round_add(L, self.Kn[round_cnt]))
  11. L, R = R, L
  12. res += L + R
  13. return res
  14. def decrypt(self, ciphertext):
  15. if (len(ciphertext) % 16 != 0 or isinstance(ciphertext, bytes) == False):
  16. raise Exception("ciphertext must be a multiple of 16 in