Docsity

IT coding and security tools - innovation and technology management, Schemi e mappe concettuali di Sicurezza Dei Sistemi Informativi

Toggle sidebar
bg1
Data structures: how data can be represented in memory
Coding: process designing, building computer program to perform specific task (algorithm representation)
At the root of programming: algorithm
ALGORITHM: Works on Ideal memory, made of ABSTRACT data structures ranging from variables to lists
- Abstract: when we come to real memory we can only deal with bits/bytes (abstraction of bytes)
Variable = container located in an abstract memory (from point of view of an algorithm)
- No concern about overflow (we’re in an ideal kind of world). Variable named by us
- Will contain values characterized by a type (numeric, letters…)
Representation:
- Arrays: ordered, homogeneous collection of variables
- Matrices: bi-dimensional array (so row and columns)
Queue: finite set of nodes, each composed of {data, pointer}. Pointer = link to next element
- Last node has a null pointer | First node has an outgoing pointer only
- All the other pointers have an outgoing and an incoming pointer from and to other nodes
How queues are processed:
- FIFO | LIFO: better to manage the computer memory and the execution of programs
File system able to organize files in a hierarchical structure: tree (link = edge, point = node)
- Tree=set of nodes, of terminal nodes, a root and a set of edges
Notion of tree can be extended to graphs (set of objects connected together)
Recursion: breaking a problem down into a smaller and smaller subproblems to solve them trivially
= Involves function calling itself. Allows write elegant solutions to problems that may be very difficult
ALGORITHM: set of well-defined, unambiguous instructions in sequence to solve a problem
Qualities of a good algorithm:
- I/O defined precisely | Each step clear, unambiguous | Most effective solution to problem
- Must be as general as possible (generalize) | Shouldn’t include computer code
- Should be written in a way that can be used in different programming languages
Representation:
- Schematic/graphical: for humans. Not dependent on any programming language:
o Pseudocode: schematic plain language description of the steps of an algorithm
Often uses structural conventions of normal programming language
o Flowchart: graphical representation of an algorithm (diagram)
Execution statement: indivisible execution step
Control flow: order in which individual statements are executed (sequence of statements = block)
Scope: refers to the visibility of variables:
- Spatial: parts of code | Temporal: time window of the execution time
Programming language: primitives, rules collect stating how combine primitives to represent complex idea
Primitive=simplest operation that can be performed by an algorithm (atomic, unambiguous)
- Each one has its own syntax (symbolic representation) and semantic (meaning)
Computers only understand very basic language: machine language: ≠ 2° CPU (intel, AMD, ARM)
Basic primitives: Getting data stored in some main RAM Perform basic arithmetic/Boolean operations
- Store results in main memory (RAM)
Source code: program coded with a high-level programming language
Boolean operator:
Operator
Name
==
Equal
!=
Not equal
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
!
O
e
T
T
aI
a
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Anteprima parziale del testo

Scarica IT coding and security tools - innovation and technology management e più Schemi e mappe concettuali in PDF di Sicurezza Dei Sistemi Informativi solo su Docsity!

Data structures : how data can be represented in memory Coding : process designing, building computer program to perform specific task (algorithm representation) At the root of programming: algorithm ALGORITHM : Works on Ideal memory, made of ABSTRACT data structures ranging from variables to lists

  • Abstract : when we come to real memory we can only deal with bits/bytes (abstraction of bytes) Variable = container located in an abstract memory (from point of view of an algorithm)
  • No concern about overflow (we’re in an ideal kind of world). Variable named by us
  • Will contain values characterized by a type (numeric, letters…) Representation :
  • Arrays: ordered, homogeneous collection of variables
  • Matrices: bi-dimensional array ( so row and columns ) Queue : finite set of nodes, each composed of {data, pointer}. Pointer = link to next element
  • Last node has a null pointer | First node has an outgoing pointer only
  • All the other pointers have an outgoing and an incoming pointer from and to other nodes How queues are processed :
  • FIFO | LIFO : better to manage the computer memory and the execution of programs File system able to organize files in a hierarchical structure : tree (link = edge , point = node )
  • Tree =set of nodes , of terminal nodes , a root and a set of edges Notion of tree can be extended to graphs (set of objects connected together) Recursion : breaking a problem down into a smaller and smaller subproblems to solve them trivially = Involves function calling itself. Allows write elegant solutions to problems that may be very difficult ALGORITHM : set of well-defined, unambiguous instructions in sequence to solve a problem Qualities of a good algorithm:
  • I/O defined precisely | Each step clear, unambiguous | Most effective solution to problem
  • Must be as general as possible (generalize) | Shouldn’t include computer code
  • Should be written in a way that can be used in different programming languages Representation:
  • Schematic/graphical: for humans. Not dependent on any programming language: o Pseudocode : schematic plain language description of the steps of an algorithm Often uses structural conventions of normal programming language o Flowchart : graphical representation of an algorithm ( diagram ) Execution statement : indivisible execution step Control flow : order in which individual statements are executed (sequence of statements = block ) Scope : refers to the visibility of variables:
  • Spatial: parts of code | Temporal: time window of the execution time Programming language : primitives, rules collect stating how combine primitives to represent complex idea Primitive =simplest operation that can be performed by an algorithm (atomic, unambiguous)
  • Each one has its own syntax (symbolic representation) and semantic (meaning) Computers only understand very basic language: machine language: ≠ 2° CPU (intel, AMD, ARM) Basic primitives : Getting data stored in some main RAM Perform basic arithmetic/Boolean operations
  • Store results in main memory (RAM) Source code : program coded with a high-level programming language Boolean operator : Operator Name == Equal != Not equal

O e T T a I a

HOW TO EXECUTE PROGRAMS: Compiled languages : a complier (special program) translates source code in specific machine language output is an executable program

    • efficient , + control hardware aspects (memory managm, CPU) Interpreted languages : an interpreter (special program) reads and processes each source code instruction. For each one the interpreter executes all the actions associated Programming paradigms : Procedural paradigm: concept of procedure: set of computational steps to be carried out (program unit) Object oriented paradigm: objects that expose behaviours (methods) and data (attributes)
  • Identification of main entities. Program execution as a simulation of the represented “world” PYTHON : general purpose programming language allowing rapid prototyping. Open source
  • Guido Van Rossum 1991 Main objectives: code readability; Allow programmers to express concepts in fewer lines of code Usages: web / GUI development; scientific and numeric, software development, system administration Program : uses a set of primitives (assignments, tests, loops) gathered together by functions (C, Java, C++)
  • Learning curve very steep (ripida, rapida) Script : can use primitives as programs & existing software as packages/libraries (Python, R, Perl, Javascript)
  • Are already present packages with basic algorithms that you can modify Learning curve very soft Variable : Lists, tuples, stack, graphs, trees
  • Primitive: usual ones (numbers, Boolean, strings, dates, time, enumerated…)
  • Abstract: these data structures don’t exist physically. Convenient way to visualize data (bits) Python is a case sensitive language V ariable ≠ v ariable When I perform an assignment, it creates (allocates) a variable in memory Create = interpreter makes request to OS to allocate some memory (If available succeed; if NOT no)
  • If variable re-assigned there is NO creation, just update of the variable content RESTO : R = N Mod k = N % k (operator reminder of N/k) Space between variables : variable 1 + “ “ + variable 2 + “ “ + variable 3 >Assign : Variable = Value >List : ordered collections of elements: numbers = [1, 2, 3, 4]
  • Can be empty , duplicates , heterogeneous , contain lists
  • Explicit assignment, squared brackets, comma, mutable, pos
  • To recall element of list in list: mylist[posList][posElement] Slice operator : allows to consider only a part of a data structure. End element ignored. First position = 0
  • Mylist[start:end:delta] / mylist[n] takes elements every delta Conditional primitives : alter the control flow depending whether certain conditions are true or false
  • If / elif (anyway executed) / else Boolean predicate that can only be true of false Iteration primitive : repeated execution of statement as long as condition true (iterative also with for)
  • While loop: For – each loop: through each element of collection. Only stops when elements are finished
  • For I in mylist / for I in range() Range : provides set of indexes: stop excludes element stop.
  • Range(start, stop, delta) / range(n) = from 0 to n- 1. Delta negative = iterate going back Float variables : floating point : process to code rational numbers in format that computer can understand Input primitive: always give a STRING I need a CAST to make calculus Type(nome) says what kind of string is Cast operations : to convert one variable type into another: not always possible
  • Int() string integer number (only if string made of digits only)
  • Float() string float variable ( any kind of number ), most efficient
  • Str() number string (the result will include digit only) READ NUMBERS IN STRINGS IN QUOTES AS SINGLE NUMBERS: “1234” = one, two, three, four >Methods : functions applied to given data structures

Greater < Less than = Greater or equal <= Less than or equal

Assignment operators Operator Syntax Same as

  • = X + = n X = x + n
  • = X - = n X = x – n / = con resto X / = n X = x / n // = approx. difett X // = n X = x // n
  • = X * = n X = x * n ** = potenza X ** = n X = x ** n % = resto X % = n X = x % n

Affogather

dare moat

o

E

concatenation

E

Binary search complexity Sequential search complexity Best case O(1) O(1) Worst/average case n/2k^ = 1 log 2 (n)+1 O(n) With n = 1 million 9 operations (sorted data) 1 million operations (unsorted dat) Binary search : + elegante import math def binaryPos(mylist, x, start=0, end=-1): if end == - 1: end = len(mylist) mid = math.floor((start+end)/2) if mylist[mid] == x: found = True else: if start < end: #so if we can divide again sublist if mylist[mid] > x: return(binaryPos(mylist, x, stard, mid - 1)) else: return(binaryPos(mylist, x, mid + 1, end)) else: found = False def binaryPos (mylist, x): return return (binaryPos(mylist, x) != None) result in just one line Iterative Binary Search Function : returns index [pos] of x in given array if present, else returns - 1 def binary_search(arr, x): low = 0 high = len(arr) - 1 mid = 0 while low <= high: mid = (high + low) // 2 if arr[mid] < x: # Check if x is present at mid low = mid + 1 elif arr[mid] > x: # If x is greater, ignore left half high = mid - 1 else: # If x is smaller, ignore right half return mid return - 1 # convention, not important - 1 EFFICIENT: insertion > bubble > selection https://www.toptal.com/developers/sorting-algorithms SORTING ALGORITHMS : “algorithm that put elements of a list in certain order” (numerical/lexicographical)

  • Output = permutation: reordering yet retaining all original elements of the input >Selection sorting : select smallest entry and moving to the front : repeat. Consider from the pivot on (on the left of the pivot already ordered) Complexity of a selection sort is O(n^2 ) regardless peculiarity of dataset to be sorted
  • Outer loop: from 0 to len(n)-1. At each outer iteration pivot is moved up to position len(mylist)- 1 o First iteration: performed n-1 comparisons and one swap ∑^ 𝑖 = [𝑛∗(𝑛− 1 )] 2 = 𝑛^2 −𝑛 2 𝑛− 1 𝑖= 1
  • Inner loop : from pivot to len(n) to identify position of smaller element tmp = temporary variable (abstract element) Pivot = first element | MinPos = smallest number SWAP tmp = mylist[minPos] Mylist[minPos] = mylist[pivot] Mylist[pivot] = tmp >Bubble sort algorithm : compares each pairs of adjacent elements and swap the 2 if out of order
  • Pushes greatest number to last position; changes content of mylist
  • Iterated until a scan of all element pairs does NOT perform any swap. {xi|(xi d xi++1) ; i=1 ,…, (n-1)}
  • Works really well if data at least partially ordered
  • If already sorted, if condition will NEVER be true. = BEST COMPUTATIONAL COMPLEXITY : O(n) Meno elegante: import math def binarySearch(mylist, x, start, end): mid = math.floor((start+end)/2) if mylist[mid] == x: found = True else: if start < end: # so if we can divide again sublist if mylist[mid] > x: return(binarySearch(mylist, x, stard, mid - 1)) else: return(binarySearch(mylist, x, mid + 1, end)) else: found = False return(found) def findMinimum Position (mylist, startPos=0): minPos = startPos for i in range (startPos, len(mylist)): if mylist[i] < mylist[minPos]: minPos = i return minPos e
ehm
  • Worst complexity : data sorted from larger to smaller complexity = O(n^2 ) (n-1)+(n-2)+(n-3)…
  • Average case : between O(n) and O(n^2 ) def bubbleSort(myList): n = len(myList) for i in range(n - 1): # external loop for j in range(0, n - i - 1): # internal loop (slave) if myList[j] > myList[j + 1]: myList[j], myList[j + 1] = myList[j + 1], myList[j] #greatest element shifted at the end return(myList) Def bubbleSort1(mylist, ascending = True): atLeastOneSwap = True while atLeastOneSwap: atLeastOneSwap = False for i in range(len(mylist)-1): if ascending: doSwap = mylist[i] > mylist[i+1] else: doSwap = mylist[i] < mylist[i+1] if doSwap: tmp = mylist[i] mylist[i] = mylist[i+1] mylist[i+1] = tmp atLeastOneSwap = True return(mylist) >Insertion sort : bubble sort not enough. Gain in simplicity but execution not so satisfactory
  • 1 st^ comparison of couple of elements and 2nd^ of element swapped with previous
  • Changes content of mylist. ABSTRACT DATA STRUCTURE : “convenient way to regroup primitive values”. Editable = change the content of element (not edit content of set) >TUPLE : collection of heterogeneous elements Tuple = (‘house’, 12, 3.34, ‘hi!’) rounded brackets Tuple = (1,) singleton Replication of singleton in time: tuple = tuple * n Properties : more efficient than list IF you will not need to edit elements ( immutable )
  • Optimized (easier for python to handle). Can alter if one of its elements is a list
  • Each element has position can use indexes [] , slice operator and len() Add elements to tuple: tuple = tuple + (element_to_add,) print max if NO lists: print(max(tuple)) Packing : assign elements of tuple. Tuple=(1, 2, 3) uno, due, tre = tuple print(uno) Determine number of times an item occurs in list : Print(tuple.count(‘item’)) Determine position of tuple element : Print(tuple.index(position)) Substitute element of list in a tuple list : tuple=(2, 4, 5, [1, 2, 3], 4, 5)
  • tuple[PosInTuple][PosInList]=- 9 tuple=(2, 4, 5, [1, - 9, 3], 4, 5) Sorted function : order tuple returning a list : print(sorted(tuple)) >SETS : elements NOT ordered, Cannot be indexed , not editable Fruit = {‘apple’, ‘orange’, ‘kiwi’, ‘pinapple’} GRAFFE OBBLIGATORIE Browse a set : For item in fruit: Print(item) Kiwi, orange, apple, pinapple Set.add() adds element in random position ONLY IF element not already present Set.remove() doesn’t check if element to remove exists Set.discard() more efficient , if element doesn’t exists nothing happens BUT more expensive for machine Set.pop() removes last element not sure which one (set is NOT ordered) Set.clear() def insertionSort(myList): for i in range(1, len(myList)): key = myList[i] j = i - 1 while j >= 0 and key < myList[j]: myList[j + 1] = myList[j] j = j - 1 myList[j + 1] = key Comparison loop: COME QUESTA atLeastOneSwap = True while atLeastOneSwap: atLeastOneSwap = False for i in range(len(mylist)-1): if mylist[i] > mylist[i+1]: tmp = mylist[i] mylist[i] = mylist[i+1] mylist[i+1] = tmp atLeastOneSwap = True COME QUELLA : for i in range(len(mylist)-1): if ascending ^ (mylist[i] < mylist[i+1]): mylist[i], mylist[i+1] = mylist[i+1], mylist[i] atLeastOneSwap = True def bubbleSort(myList): ALTRA n = len(myList) for i in range(n - 1): # external loop for j in range(0, n - i - 1): # internal loop (slave) if myList[j] > myList[j + 1]: myList[j], myList[j + 1] = myList[j + 1], myList[j] return(myList) Cast a list into a tuple : Mylist = [] For x in range(tot): Mylist.append(x) Mytuple=tuple(mylist) Print(mytuple) (0, 1, 2, tot)

O

daptinestable^ inplaceonline

Immutable

9in alter (^) list e I

Import numpy as np: Multidimensional matrix : we can specify as many dimensions as we need: Array = np.array([3, 6, 9, 12]) transform (cast) list in array Division = array/3 with lists I couldn’t do it in one only line (heterogeneous elements) ndarray (usually fixed size) multidimensional container of items of the same type and size N° of dimensions and items defined by its shape (tuple of N non negative integers that specify size of each dimension Basic function for array creation : np.array(data, datatype) datatype inferred by data nature Popular NumPy functions : np.zeros(shape) create array and initialize elements to 0 np.zeros (plain, rows, columns) np.ones() create array and initialize to 1 np.arange(number) create array that contain numbers until the one specified np.arange(start, end, increment) end excluded (I care about position np.linspace(start, end, numberOfPoints) end included (interval divided in tot) np.full(shape, value, dtype=int) array creation ; value initialize array to that value

  • Np.full ((4,4), 2) multidimensional array requires tuple for the shape definition (4,4) Np.add(X, Y) | np.subtract(X, Y) | np.divide(X, Y) | np.multiply(X, Y) operations with array Array math : Scalar product, vector: X = {xi; I = 1, …, n} x = np.array([1, 2, 3]) Y = {yi; I = 1, …, n} y = np.array([4, 5, 6]) XY = ∑xiyi x.dot(y) 32 Popular features : Dot product, singular value decomposition, eigenvalues and eigenvectors, matrix determinant, least square optimizations, QR decomposition np.linalg.xxx linear algebra np.random.randint(10, size=6) line of 6 values = size(1, 6) np.random.randint(start, end, howMany): creating array with random numbers
  • howMany can be size of array to create a matrix (start, end, (index, value)) Numpy operators : +, - , /, * Will perform these operations between 2 arrays
  • Also possible to multiply of divide an array by a scalar (number) Poly1d([1, 2, 3]) =x^2 +2x+3. can solve a polynomial equation of second degree (2 solutions) System of linear equations (≠ methods): Np.linald.inv(A): find inverse of matrix A
  • X = np.linalg.inv(A).dot(B) A=matrix with coefficients a, b. B=matrix with coefficient c Dataframe = data table (bi dimensional). Each column contains the same kind of data (numbers/strings)
  • Each row : data sample | Each column : ≠ variable describing the sample (row) Useful when what I want to handle is so complex that normal instruments are not enough Dataframe handled by ad-hoc library = PANDAS PANDAS : fast, powerful, flexible, easy, open source data analysis & manipulation tool. Based on NumPy Expressive data structures designed to make working with “relational” or “labeled” data easy and intuitive. Aims to be the fundamental high level building block for doing practical, real world data analysis in Python
  • Tabular data, also heterogeneous typed columns as SQL table or excel spreadsheet
  • Ordered and unordered (not necessarily fixed frequency) time series data
  • Arbitrary matrix data with row and columns labels
  • Any other form of observational / statistical data sets Type(array[i]): to know type of data in array Array shapes :
  • Sequence o Mydata[ index ]
  • Matrix : bidimensional data structure o Mydata[ rowindex, colindex ]: Mydata = np.array([1, 2, 3, 4, 5)] Type(mydata[0]) Numpy.int Mydata = np.array([[1,2,3,4,5], [6,6,8,9,10]]) Type(mydata[0]) Numpy.int Matrix math : X = np.full((3,3), 2) = array 3 x 3 full of 2 Y = np.full((3,3), 4) c = x*y L i f a f

Dot Product

ONE dimensional polynomial class

Pandas data structures : Series: one dimensional labeled array capable of holding any data type

  1. Myseries = pd.Series(np.arange(10, 51, 10), index=[‘a’,’b’,’c’,’d’,’e’]) a. np.arange(start, stop, step) at the end dtype: int
  2. Myseries[‘c’] è come dire myseries[ 2 ] https://archive.ics.uci.edu/ml/index.php = Repository of real data, for machine learning Typically data are dirty, messed up process them before anything (estimate errors and correct them) Format conventions dataframes : Separated by comma or any character: CVS (character separated values) Create a dataframe : pd.dataframe({}) DataframeName.shape(): will tell me the shape of the matrix (indexes x values). Shape[0]=index. [1]=values Dataframe.head(tot): consider only first tot rows .iloc integer position based (from 0 to len–1 of the axis, similar to array/list slicing): Physical position .loc label based; logical position dataframe indexing (cont.) df = pd.DataFrame(np.random.randint(1,20, (6, 4)), index=['a','b','c','d','e','f'], columns=['A','B','C','D’]) df.loc[‘b’] = riga b (6, 4) = matrix size: (index, columns) df.loc[‘b’, ‘B’] = intersection column B and row b df.loc[:, ‘A’] = A column referring to logical value ( includes boundaries ). : = all df.iloc[0, 0] = posizione index = 0, column = 0 df1 = auto.set_index(‘cylinders’) df1.loc[8] dataframe multi level indexing df1 = auto.set_index([‘cylinders’,’year’]) same as. df1.loc[(8,70)] Validate and clean dataset: remove extra spaces and data not required:
  • import os.path #to handle file system | import wget | !pip install wget
  • Os.path.exixsts(name) | wget.download(name) | pd.read_csv(name, datafr) Df[‘gender’].replace(to_replace=[‘male’, ‘female’], value=[0, 1], inplace=True). Replace m/f with 0, 1 To perform diagrams : import matplotlib.pyplot as plt | scipy.stats as stats scatter plot adult.plot(kind = 'scatter', x = 'Age', y='Hours_per_week', color='red') plt.show() adult.groupby('Edu')['Cap_gain'].nunique().plot(kind='bar', color = 'green', title ='Edu vs Cap_gain') bar plot adult.groupby(['Native_country', 'Gender']).size().unstack().plot(kind = 'bar', stacked = True). Stack bar to export data in excel rename file to name.csv loading dataframe : large collection of functions to ‘read’ data into a dataframe from ≠ sources and formats mtcars = pd.read_csv('http://www.dmf.unicatt.it/~tessera/mtcars.csv') Data visualization : mtcars = pd.read_csv('http://www.dmf.unicatt.it/~tessera/mtcars.csv’) mtcars[‘cylinders’].value_counts() mtcars[‘cylinders’].value_counts().plot(kind=’pie’)
  • Reorder data and provide the one with mayor frequency mtcars[‘cylinders’].value_counts(sort=False).plot(kind=’pie’)
  • I don’t want the data to be ordered, just to highlight the one with mayor frequency Functions to process strings : .Index(string): finds first occurrence of the specified value (where in original string another substring is) .Isalnum() returns True if all the characters are alphanumeric (a-z) and numbers (0-9) .Isdigit() returns True if all characters in the string are digits .lower() converts a string into lower case .lstrip() / .rstrip() returns a left / right trim version of the string [deletes extra spaces on the left/right] Substring a string: extract one or more characters from a string. Use the template string[start: end: step]
  • Useful to analyze texts (grammar definition, spell checking, look for specific words) Pd.to_datetime(): function will reassemble dates previously expressed in string to “universal” dates a 10 b 20 c 30 d 40 e 50 È Datatrane E_ I (^) E

c

CSV: comma separated values Returns lowest index in the string where substring is found: position in which sub starts

  • Polymorphism : methods of class can take different forms (≠ classes inherit method from same class & implement in ≠ ways) o Overloading: same method defined many times with ≠ arguments (all of them valid) o Overriding: same method implemented in ≠ way in derived class EXCEPTIONS : 3 kinds of errors Syntax error (python tells us where it is) Python controls if script written in correct syntax (grammar rules)
  • Interpreter analyze only code executed àthis why some syntax errors detected only in 2° moment Semantic error : logical error in code; unexpected results or stopping prematurely = bug [only at run time]
  • To Find them: o Print statement everywhere to check correctness (print content of variables I use) o Debugger : python instrument that shows you whatever happen in every statement Exceptions : you can take care of them: Division by 0: is not a number à impossible à exception Python has many built in exceptions
  • Interpreter stops process and pass it to calling process until it’s handled (if not crash ) Can be handled by invoking library sys and using a try statement Try clause : Code that handles exceptions written in except clause Sys.exc_info()[0] à <class ‘type of error’> Assert = condition that must be respected (in tab try:) Exception creation : raise exceptions myself if condition holds in script If condition: à raise TypeError(‘nome errore’) Finally : will execute as last task before try statement completes. Runs whether or not try produces except NETWORK SECURITY: internet population growth
  • Cyber security : involves only technologies like endpoint security software, antivirus, firewall
  • Information security : involves also procedures, policies, human factor, performance evaluation 3 pillars : Principles of network security :
  • Integrity : information must not be corrupted/manipulated in any way (modified with no authorization)
  • Confidentiality : only authorized people can access information (visualize, sender and receiver) o Authentication : sender and receiver want to confirm identity of each other
  • Access and Availability : information must be accessible and available to users when needed Cryptography: Encryption (of plain text) with KA / decryption (of ciphertext) with KB = decryption key
  • m = plain text; KA(m) = ciphertext, encrypted with key KA à m = KB(KA(m)) Problems :
  • Eavesdrop : intercept messages | insert messages in connection | Impersonation : fake source address
  • Hijacking (take over) ongoing connection by removing sender or receivers inserting himself in place
  • Denial of service : prevent service from being used by others (overloading resources) Breaking encryption scheme : Ciphertext only attack (cyphertext that can be analysed)
  • Brute force vs. Statistical analysis à to decrypt a ciphertext or to discover the encryption key
  • Know plaintext attack : having a plaintext that corresponds to ciphertext (attacker knows both)
  • Chosen plaintext attack : can get ciphertext for chosen plaintext (presume presence of this ability) Cipher text code breaking : process to decrypt a ciphertext or to discover the encryption key Computational safe encryption system :
  • Cost for decrypting message much larger than message value
  • Time required to break code much longer than security temporal scope Simple monoalphabetic cipher: 26! = 10^26 Text analysis code breaking Security only depends from length (n° of bit) of the key, not from type of cryptography Symmetric key cryptography : same Ks need to be communicated by NOT using network
  • Simple encryption scheme : “not so efficient” o Substitution cipher : substituting one thing for another = stream ciphers § Monoalphabetic cipher: substitute one letter for another o Encryption key : mapping from set of 26 letters to set of 26 letters Try: divisione except: print(sys.exc_info()[0])

e

g

f E

  • Multiple substitution cipher : n substitutional ciphers and cyclic pattern o For each plaintext symbol use subsequent substitution pattern in cyclic pattern Symmetric key cryptography: DES : Data Encryption Standard = US encryption standard | 56 bit symmetric key (8 characters, 7 bits), 64 bit plaintext input
  • Block cipher : encrypt n° of ≠ bits as single unit| Not known good analytic attack
  • 3DES : encrypt 3 times with 3 different keys Most used: AES : Advanced Encryption Standard
  • Symmetric key NIST standard, replaced DES
  • Process data in 128 bit blocks à 128, 192, 256 bit keys Public key cryptography : Asymmetric encryption: new method.
  • Radically ≠ approach: sender, receiver do NOT need to share secret key
  • Public encryption key known to all | Private decryption key known only to receiver and ≠ for everyone
  • Requirements : public key K+^ and private key K-^ such that K-(K+(m)) = m o Given public key should be impossible to compute private key
  • RSA : creating public / private key pair (takes advantage of both techniques) better than DES o Choose 2 large prime numbers p, q (1024 bits each) o Compute n = pq; z = (p – 1) * (q – 1 ) o Choose e < n relatively prime : no common factors with z o Choose d such that (ed mod z = 1) o Public key is (n, e) = K+^. Private key is (n, d) = K- o Need to find factors of n without knowing p and q à hard § Exponentiation à huge computational complexity § DES decryption at least 100 times faster than RSA § Public key crypto to establish secure connectionàsecond key ( symmetric session ) to encrypt
  • RSA encryption, decryption : given (n, e) and (n, d): o To encrypt message m (<n) à c = me^ mod n o To decrypt received bit pattern, c à m = cd^ mod n à m = (me^ mod n)d^ mod n 2 properties :
  • Public key followed by private key = m = private key followed by public key. K-(K+(m)) = m = K+(K-(m)) AUTHENTICATION : need to identify someone / something. Authentication protocols: Ap : Ap1 : Ap2 : Ap3 : same problem if password encrypted Ap4 : to avoid playback attack : NONCE : number R only once in a lifetime. Uses symmetric key Ks To work with public key, need to substitute invio of K+^ with invio of security certificate by CA Ap5 : “as secure as the distribution of public keys”. Possibility to impersonate / intercept. Difficult to detect A PROBLEM B “I’m A” à ß R “I’m A” à ß R KA-(R) à ß “send me public Key” KP-(R) à ß “send me public Key” KA+^ à ß KA+(m) KP+^ à ß KP+(m) Get m = KA-(KA+(m)) Get m = KP-(KP+(m)) For insurances about IDENTITY : CA certificates Digital signatures : cryptographic technique analog to hand written signatures = signed message digest A PROBLEM B “I’m A” à Stop | “I’m A” à Cannot verify A is A A PROBLEM : ip spoofing B “I’m A”+A’s IP address à Stop | “I’m A”+A’s Ip address à Cannot verify A is A A PROBLEM : eavesdrop B “I’m A”+password à Stop | “I’m A”+password à Cannot verify A is A A B “I’m A”à ß “R” “Ks(R)”à If decrypting Ks(R) with Ks = R ok Only A and B have Ks Slow : more often used to transmit shared keys x symmetric key cryptography a è è 4 with

Keys needed to decrypt held in escrow à an authorized third party may gain access to keys under certain circumstances SSL = secure sockets layer = unique standard about security on internet (to secure internet browser) Digital certificate : certificate that a given public key is associated to a given identity Security issues : Malware: software that performs hidden actions to weaken security of our system

  • Virus / Spyware / Trojan horses Botnet (DDOS): distributed denial of service attack: tries to prevent use of a system by overloading it
  • Also looks for bugs to take the control Sniffing: Phishing / spear: Ransomware: malware that encrypt content of pc and ask for money to decrypt it
  • Causes: outdated software with known vulnerabilities / misconfiguration
  • Can also encrypt and stole à threaten to reveal data [ double ransom ] Limited use of sophisticated malware, large use of simple technique:
  • To hide full in view
  • Spear – phishing (targeted attack to specific individuals / companies) (social engineering)
  • Living off the land approach Cloud and IoT numbers : 25% of data shared on data architecture à 30/40 applications Time for IoT attack: 2 minutes à “ Symantec ” attacks on honey pot: 5 per hours in January 2016 Email threats :
  • Malwares
  • Spear phishing frauds o Financial frauds pretending to be manager and CEOs § Causes: no procedure to double heck information / no training to employees
  • Social engineering for improving the effectiveness of email frauds o Office, JavaScript, WSF attachments (window script file) o Very easy with share of private information on social networks
  • Targeted sectors: o Malware: building, finance, transport, public utilities o Phishing: transport and public utilities Best practices :
  • Antivirus software
  • Deleting suspicious mails
  • Pay attention to attachments
  • Pay attention to emails containing unrequested attachments
  • Update antivirus and operating systems
  • Reply to email using agenda address and not with the reply to facility
  • Never follow email links to connect to portals
  • Limit the information shared with social networks ( share after, NOT before ) Causes : known vulnerabilities, websites downtime, data breach
  • Absence of strategy on approaching security (define what’s needed to be protected) Strategy:
  • Awareness : of employees
  • Organization : start from the top introducing policies and budget to approach issue
  • Monitoring : technical to check presence of non vulnerabilities / test procedures
  • Technologies : useful only if are present other pillars Risk based approach : Limited budget à identify asset to protect à prioritize protection of critical assets (the one that if compromised could lead to critical failure à identify best and most efficient counter measures e

mira

Ee E

Process mapping à risk identification à risk evaluation à risk treatment ISO 27001 : standard for information security :

  • Allocate resources needed to fulfill the requirement
  • Evaluate risk of possible incident
  • Define specific procedure to guarantee security of the information
  • Continuously improve the information security system
  • Make employees aware of their responsibilities and about possible threat
  • Leadership (management involved)
  • Risk assessment (how to identify risk, mitigate them)
  • Human resources : screening before employment, awareness, training (education)
  • Continuous improvement

Advantages of approach :

  • Competitive advantage: international organization are aware of cyber risks and are asking to the supply

chain to demonstrate how information security is guaranteed

  • Ready to be compliant to law, industry requirements: possibility offer services to regulated entities
  • Continuous improvement: to face constant evolution of threats
  • Protection of critical assets:

DATA SCIENCE : field of study that combines:

  • Domain expertise
  • Programming skills
  • Knowledge of mathematics and statistics to extract meaningful insights from data

Applies machine learning algorithms to numbers, text, images, video, audio and more to produce artificial intelligence (AI) systems to perform tasks that ordinarily require human intelligence Systems generate insights which analysts and business users can translate into tangible business values Problems targeted :

  • Customer segmentation (demographics, psychographics, sales behavior)
  • Uber’s pickup analysis
  • Web traffic forecasting using time series (planning server usage, optimizing network)
  • Predicting restaurant success (for lenders and investors helping profitable financial decisions)
  • Detecting fake news:

A DATA SCIENCE PROBLEM : classification through regression : Dataset 4 columns x 7 rows of data, 1 of titles Regression = predicting a cell missing in the dataset through known data

  • We could call 3 known columns “independent variables”, last one (incognita) “dependent variable”

o Dependent variable can be continuous only (not categorial) Techniques to build a predictor : Predicting power taking in account an error

  • Simple linear : when dependent variable depends on one independent variable only (not realistic)

o Calculates the slope and the intercept of the line describing dependency of y upon x o Equation of the line: Y^I = b 0 + b 1 Xi o B 1 =slope, b 0 =intercept of Y^ when Xi= o Before train the model (80% dataset) à then test (20%)

  • Multiple regression : dependent variable depends on at least 2 independent variables

ARTIFICIAL INTELLIGENCE : simulation of human intelligence processes by machines, computer systems Can have very specific applications To do so we assume activity of brain are computational process

  • Knowing some facts they are able to reach some conclusions

Image processing and face detection : E 4 I