Advertisement
Guest User

Untitled

a guest
Nov 21st, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. from Crypto.Cipher import DES
  2. import matplotlib.pyplot as plt
  3. from collections import defaultdict
  4. import random
  5. import numpy as np
  6. import math
  7.  
  8. def DESEncrypt(key,plaintext):
  9. cipher = DES.new(key,DES.MODE_ECB)
  10. ciphertext = cipher.encrypt(plaintext)
  11. return ciphertext
  12.  
  13. def DESDecrypt(key,ciphertext):
  14. cipher = DES.new(key,DES.MODE_ECB)
  15. plaintext = cipher.decrypt(ciphertext)
  16. return plaintext
  17.  
  18. def int_to_bytes(x: int) -> bytes:
  19. #x = x.item()
  20. return x.to_bytes((x.bit_length() + 7) // 8, 'big', signed = False)
  21.  
  22. def int_from_bytes(xbytes: bytes) -> int:
  23. return int.from_bytes(xbytes, 'big',signed = False)
  24.  
  25. def intArrayToByteArray(intArray):
  26. tempByteArray = bytearray()
  27. for i in range(len(intArray)):
  28. if (intArray[i] == 0):
  29. tempByteArray += b'0'
  30. tempByteArray += int_to_bytes(intArray[i])
  31.  
  32. return tempByteArray
  33.  
  34. key = [0]*8
  35.  
  36. keyTable = []
  37.  
  38. #This is creating all key and set it into a table
  39. for firstByte in range(0,128):
  40. for secondByte in range(0,128):
  41. for thirdByte in range(0,64):
  42. key[0] = firstByte
  43. key[1] = secondByte
  44. key[2] = thirdByte
  45. tempArray = intArrayToByteArray(key)
  46. keyTable.append(tempArray)
  47. key = [0]*8
  48.  
  49. print(len(keyTable))
  50. print("Key table generation done")
  51.  
  52. plaintext_orig = bytearray(b'01234567')
  53. ciphertext = bytearray(b':\xae%I\xd2t\xf8>')
  54.  
  55. EncTable = []
  56. for key in keyTable:
  57. tempCipher = DESEncrypt(key, plaintext_orig)
  58. EncTable.append(tempCipher)
  59.  
  60. print()
  61. print(len(EncTable))
  62. print("All ciphertext calculated")
  63.  
  64. restoredKeyPair = []
  65.  
  66. for key in keyTable:
  67. tempDecryptedValue = DESDecrypt(key, ciphertext)
  68. if tempDecryptedValue in EncTable:
  69. key1 = EncTable.index(tempDecryptedValue)
  70. key2 = key
  71. restoredKeyPair.append((key1, key2))
  72.  
  73. print(restoredKeyPair)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement