Differences

This shows you the differences between two versions of the page.

Link to this comparison view

sasc:laboratoare:01 [2016/02/23 10:38]
sergiu.costea [Python Crash Course]
sasc:laboratoare:01 [2017/02/21 11:28] (current)
dan.dragan
Line 1: Line 1:
-===== Lab 01 =====+===== Lab 01 - Introduction ​=====
  
 ==== Python Crash Course ==== ==== Python Crash Course ====
Line 52: Line 52:
 <code Python> <code Python>
 def foo(a, b): def foo(a, b):
-    if (a > b):+    if a > b:
         x = a         x = a
     else:     else:
Line 68: Line 68:
     return     return
   else:   else:
-    return alphabet[(ord(letter) - ord('​A'​) ​3) % len(alphabet)]+    return alphabet[(ord(letter) - ord('​A'​) ​3) % len(alphabet)]
 </​code>​ </​code>​
  
Line 143: Line 143:
 >>>​ test + '​WORLD'​ >>>​ test + '​WORLD'​
 >>>​ caesar_enc_string(test) >>>​ caesar_enc_string(test)
 +</​code>​
 +
 +Another way to run things, which can be very useful in general is to use a main() function and write your program script as follows:
 +
 +<code Python '​test_caesar.py'>​
 +import sys
 +import random
 +import string
 +import operator
 +
 +alphabet='​ABCDEFGHIJKLMNOPQRSTUVWXYZ'​
 +
 +def caesar_enc(letter):​
 +  if letter < '​A'​ or letter > '​Z':​
 +    print '​Invalid letter'​
 +    return
 +  else:
 +    return alphabet[(ord(letter) - ord('​A'​) + 3) % len(alphabet)]
 +
 +def caesar_enc_string(plaintext):​
 +    ciphertext = ''​
 +    for letter in plaintext:
 +        ciphertext = ciphertext + caesar_enc(letter)
 +    return ciphertext
 +
 +def main():
 +  m = '​BINEATIVENIT'​
 +  c = caesar_enc_string(m)
 +  print c
 +  ​
 +
 +if __name__ == "​__main__":​
 +  main()
 +</​code>​
 +
 +Then you can simply run the program, or type the following in a terminal:
 +<code Python>
 +python test_caesar.py
 </​code>​ </​code>​
  
Line 171: Line 209:
         return None         return None
     else:     else:
-        return alphabet[(ord(letter) - ord('​A'​) ​k) % len(alphabet)]+        return alphabet[(ord(letter) - ord('​A'​) ​k) % len(alphabet)]
  
 def caesar_enc_string(plaintext,​ k = 3): def caesar_enc_string(plaintext,​ k = 3):
Line 193: Line 231:
 Using default parameters, expand your shift cipher decryption functions to support arbitrary keys. Using default parameters, expand your shift cipher decryption functions to support arbitrary keys.
  
-==== Exercise 1 ====+=== Python Recipe #4 - Format conversions ​===
  
-Alice sends Bob the following ciphertexts:​+<code Python>​ 
 +import binascii
  
-<​code>​ +def strxor(a, b): # xor two strings (trims the longer input) 
-LDPWKHORUGBRXUJRG +  ​return ""​.join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
-XNTRGZKKGZUDMNNSGDQFNCRADENQDLD +
-DTZXMFQQSTYRFPJDTZWXJQKFSDLWFAJSNRFLJ +
-SIOMBUFFHINNUEYNBYHUGYIZNBYFILXSIOLAIXCHPUCH +
-ERZRZOREGURFNOONGUQNLGBXRRCVGUBYL +
-CJIJPMTJPMAVOCZMVIYTJPMHJOCZM +
-DTZXMFQQSTYRZWIJW +
-ZPVTIBMMOPUDPNNJUBEVMUFSZ +
-FVBZOHSSUVAZALHS +
-KAGETMXXZAFSUHQRMXEQFQEFUYAZKMSMUZEFKAGDZQUSTNAGD +
-MCIGVOZZBCHRSGWFSOBMHVWBUHVOHPSZCBUGHCMCIFBSWUVPCIF +
-</​code>​+
  
-Charlie manages to capture the ciphertexts and he finds that the cipher used for +def hexxor(a, b): # xor two hex strings (trims ​the longer input) 
-encryption is the shift cipher (each message possibly encrypted with different +  ha = a.decode('​hex'​) 
-key). Can you decrypt the messages ?+  hb = b.decode('​hex'​) 
 +  return ""​.join([chr(ord(x) ^ ord(y)).encode('​hex'​) for (x, y) in zip(ha, hb)])
  
-Charlie also knows that the plaintext consists only of the English letters A to +def bitxor(a, b): # xor two bit strings (trims ​the longer input) 
-(all capitalsno punctuation).+  ​return ""​.join([str(int(x)^int(y)) for (xyin zip(a, b)]) 
 +   
 +def str2bin(ss):​ 
 +  """​ 
 +    Transform a string (e.g. '​Hello'​) into a string of bits 
 +  """​ 
 +  bs = ''​ 
 +  for c in ss: 
 +    bs = bs + bin(ord(c))[2:​].zfill(8) 
 +  return bs
  
-==== Exercise ​====+def hex2bin(hs):​ 
 +  """​ 
 +    Transform a hex string (e.g. '​a2'​) into a string of bits (e.g.10100010) 
 +  """​ 
 +  bs ''​ 
 +  for c in hs: 
 +    bs bs + bin(int(c,​16))[2:​].zfill(4) 
 +  return bs
  
-Alice sends Bob another ciphertextbut much longer this time:+def bin2hex(bs):​ 
 +  """​ 
 +    Transform a bit string into a hex string 
 +  """​ 
 +  return hex(int(bs,2))[2:-1]
  
-{{:sasc:laboratoare:sasc_msg_lab1.txt|Download message file}}+def byte2bin(bval): 
 +  """​ 
 +    Transform a byte (8-bit) value into a bitstring 
 +  """​ 
 +  return bin(bval)[2:].zfill(8) 
 +   
 +def str2int(ss):​ 
 +  """​ 
 +    Transform a string (e.g. '​Hello'​) into a (long) integer by converting 
 +    first to a bistream 
 +  """​ 
 +  bs = str2bin(ss) 
 +  li = int(bs, 2) 
 +  return li 
 +   
 +def int2hexstring(bval):​ 
 +  """​ 
 +    Transform an int value into a hexstring (even number of characters) 
 +  """​ 
 +  hs = hex(bval)[2:​] 
 +  lh = len(hs) 
 +  return hs.zfill(lh + lh%2) 
 +   
 +def bin2str(bs): 
 +  """​ 
 +    Transform a binary srting into an ASCII string 
 +  """​ 
 +  n = int(bs, 2) 
 +  return binascii.unhexlify('​%x'​ % n) 
 +</​code>​
  
-Charlie needs to decrypt this as well. Some colleagues tell him this is encrypted +=== Python Exercise #4 - Format conversions ===
-using the substitution cipher, and that again the plaintext consists only of the English letters **A** to **Z** (all capitals, no punctuation). Try to help Charlie to decrypt this.+
  
-Hint: use the frequency analysis mechanisms we discussed in class. Note that the frequency of each letter does not map precisely. In particular, the most frequent two letters do match well with the given table, but the others are sometimes mixed. However, Charlie knows that the most frequent bi-grams are the following ​(from most frequent to less frequent): +Find the plaintext messages for the following ciphertexts knowing ​that the cipher is the XOR operation ​(ciphertext = plaintext XOR keyand the key is "​abcdefghijkl"​. 
-**TH**, **HE**, **IN**, **OR**, **HA**, **ET**, **AN**, **EA**, **IS**, **OU**, **HI**, **ER**, **ST**, **RE**, **ND**+ 
 +<​code>​ 
 +C1 = "​000100010001000000001100000000110001011100000111000010100000100100011101000001010001100100000101"​ 
 + 
 +C2 = "​02030F07100A061C060B1909"​ 
 +</​code>​
  
-With this information,​ can you tell what the ciphertext is about? 
  
 +<​hidden>​
 +The solution is {{:​ic:​laboratoare:​lab1_sol.zip|here}}.
 +</​hidden>​
sasc/laboratoare/01.1456216707.txt.gz · Last modified: 2016/02/23 10:38 by sergiu.costea
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0