Advertisement
Tenac451

Untitled

Apr 27th, 2020
289
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. from Crypto.Cipher import AES
  2. from Crypto.Util import Padding, strxor
  3.  
  4.  
  5.  
  6. def ctr_enc(key, nonce, message):
  7. cipher_ctr = AES.new(key, AES.MODE_CTR, nonce=nonce, initial_value=1)
  8. return cipher_ctr.encrypt(message)
  9.  
  10.  
  11. def ctr_dec(key, nonce, ciphertext):
  12. cipher_ctr = AES.new(key, AES.MODE_CTR, nonce=nonce, initial_value=1)
  13. return cipher_ctr.decrypt(ciphertext)
  14.  
  15.  
  16. def ecb_enc(k, data):
  17. cipher_ctr = AES.new(k, AES.MODE_ECB)
  18. return cipher_ctr.encrypt(data)
  19.  
  20.  
  21. def byte_xor(ba1, ba2):
  22. # https://nitratine.net/blog/post/xor-python-byte-strings/
  23. return bytes([_a ^ _b for _a, _b in zip(ba1, ba2)])
  24.  
  25.  
  26. def cbc_mac(k, n, a, m):
  27. gruen = n + len(m).to_bytes(8, 'big')
  28. gelb = len(a).to_bytes(8, 'big') + a
  29. blau = m
  30.  
  31. data = gruen + Padding.pad(gelb, 16) + blau
  32. data = Padding.pad(data, 16)
  33.  
  34. cipher = AES.new(k, AES.MODE_CBC, iv=b'\00'*16)
  35. n0 = ecb_enc(k, n+b'\x00'*8)
  36. c = cipher.encrypt(data)[-16:]
  37.  
  38. return byte_xor(n0, c)
  39.  
  40.  
  41. def ccm_enc(k, n, a, m):
  42. # nonce based CTR ENC
  43. c = ctr_enc(k, n, m)
  44. # CBC-MAC with a-data
  45. t = cbc_mac(k, n, a, m)
  46. print(f'enc tag: {t}')
  47. return a, c, t
  48.  
  49.  
  50. def ccm_dec(k, n, a, c, t):
  51. m = ctr_dec(k, n, c)
  52. # CBC-MAC with a-data
  53. t = cbc_mac(k, n, a, m)
  54. print(f'dec tag: {t}')
  55. return a, m
  56.  
  57. a = b'das ist gar nicht geheim'
  58. m = b'this is a stupid and totally useless but very secret message'
  59. k = b'einszweidreivier'
  60. n = bytes.fromhex('1122334455667788')
  61. (a1, c, t) = ccm_enc(k, n, a, m)
  62. print("encrypted data:")
  63. print(a1)
  64. print(f' ciphertext: {c}')
  65.  
  66. (a2,m2) = ccm_dec(k,n,a1,c,t)
  67.  
  68. print("Checking decryption result: ", a==a2 and m==m2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement