{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"markdown","source":"                                                    Intro\n\nThe programs that create deepfakes and the programs that detect them will soon enter into the same dynamic of malicious software and anti malicious software. Everytime an imporvement is made in detecing deepfakes, an improvement in generating them will also follow. Not to mention creating new testing and deploying new mwthods of deepfake detection will also need a lot of time,data and electricity also.\n\nThis notebook explores another possible soution to the deepfake problem without by taking a cryptographic approach instead. There will be a small demonstration on the training data of kaggle. To understand the solution one must understand the following concept(which will be explained here also):\n\n1) Encryption\n\n2) Hashing\n\n3) Digital Signature\n\n4) Certificate Authority Hierarchy\n"},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{},"cell_type":"markdown","source":"                                                         Encryption\nEncryption can be thought of as a transformation of readable text into text that seems to have no meaning at a glance. \nDecryption is the exact opposite of encryption. To perform encryption and decryption something called a key. In a sense, \nthe key can be thought of as something that locks or unlocks a message as and when required.\n\nIt is almost impossible to figure out a message that has been encrypted by modern-day algorithms. In symmetric-key encryption\n,the same key used to lock the message is used to unlock it. In our case, however, we need to use asymmetric key encryption \nas it can also be used as a digital signature.\n\nIn asymmetric key encryption, we use a key pair which is a pair of keys generated at the same time. If a message is locked \nor encrypted by one of these keys only the other key can unlock or decrypt it. It is not feasible to guess the other key \ngiven one of the keys from the key pair. From the key pair, one of the keys is referred to as a public key (intended to be \nknown by all) and the other is called a private key (intended to be known only to the owner of the key pair).\n\nFor this implementation, the RSA encryption scheme will be explined and used. Brute force attacks against these algorithms \nare practically impossible. "},{"metadata":{},"cell_type":"markdown","source":"                                                             Hashing\nHashing is the use of a mathematical function to map data of arbitrary size to a certain value of a fixed size. Hashing can \nessentially be thought of as a fingerprint of a given string. Hashing is used in cybersecurity to make sure that messages \nare not tampered with. A cryptographically secure hashing algorithm must have the following properties:\n\n1) The length of the output is fixed irrespective of the length of the input.\n\n2) It is impossible to predict the input string given only a hash value.\n\n3) Each input string has a unique hash value. Even a small change in the input string will give a completely different hash \nvalue.\n\n4) For a given input string the output hash value will always be the same We will use a member of the Secure Hashing Algorithm family called SHA-256. The 256 refers to the length of the output string in bits."},{"metadata":{},"cell_type":"markdown","source":"                                                        Digital Signature\nA unique property of asymmetric key encryption is that if the message is locked with one of the keys only the other key can unlock the message. This can be used to act like a signature used in our day to day lives. We had discussed the example of X and Y. If a message is encrypted by X private key the only thing that can unlock it will be X's public key.\n\nThis seems counter-intuitive to security but this can be used to prove that only X could have written the message (this is assuming only X knows the correct private key). This is the principle behind a digital signature where a message is first hashed, and then the hash is encrypted with a private key. A receiver of the message can decrypt the hash with the correct public key. \n\nThen the receiver can hash the message received. If the hashes are the same then it can be confirmed that the \nmessage was sent by a certain person and was not tampered with."},{"metadata":{},"cell_type":"markdown","source":"                                                Certificate Authority Hierarchy\nA vulnerability of asymmetric key encryption is that it is susceptible to man in the middle attacks. Assume X wishes to \ncommunicate with Y so X broadcasts a request for Y's key. However, if a malicious third party (Z) intercepts this message then Z can send his/her public key to X. Z would then send the message to Y and Y would respond with the intended public key. So X and Y communicate without knowing Z is reading and/or modifying their messages. This why when X sends a request for a public key, X must also request a certificate signed by an authority certifying that the given public key does indeed belong to Y. \n\nHence, we need a way to verify that the signature is from a valid authority. To solve this issue a Certificate Authority \nHierarchy is created. There is a root Certificate Authority which signs the certificates of the people working right under him/her. \n\nThe officers under the root CA are called the second level CA who signs the certificate of the third level CA. \nThis structure relieves the pressure of the root CA who does not have to sign every user's certificate. The root CA's \npublic key is treated as public knowledge. Using this anyone participate in a network can check if the certificate is valid or not."},{"metadata":{},"cell_type":"markdown","source":"                                                          Workflow \nEach and every camera must have a built in key pair that. The public key can be stored anywhere. The private key however can be stored on a seperate device like a USB. Now once someone uses the device to record audio or video a hash will be generated.\n\nThen the user must plug the USB with the private key into the device. \n\nAll applications on the phone will be suspended or stopped. On the application that will store the recording maybe allowed to work. This application will send a hash to the USB which will use the private key and sign the hash. "},{"metadata":{},"cell_type":"markdown","source":"In this demonstration the Rivest–Shamir–Adleman algorithm will be explained and used. Secure HashingAlgorithm 256(SHA-256) aso be used but will not be explainied."},{"metadata":{},"cell_type":"markdown","source":"                                                Ricest Shamir Adleman\n\nRSA algorithm works on the basis of the fact that it is very easy to multiply two number but very difficult to factorise a given number.\n\nThe steps for RSA key generation are:\n\n1)Randomly choose two large prime numbers.(p and q)\n\n2)Multiply the two number to get the product.(n)\n\n3)Multiply (p-1) and (q-1). Let us call this number f.\n\n4)Now we need to find a prime number which will not be be a factor of f.\n\n5) This can be one of our keys. Either the public key of the private key.Let us assume it is our public key.\n\n6) Now we need to find another number such that it is the modulo inverse of our public key. Assume we have a number prk(private key). The product of our public key and private key when divide by f should leave a remainder of 1. If this happens prk is the modulo inverse of our public key and hence is our private key.\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"#this code will generate a key pair using primes from 0,1000. In practice the numbers used have hundreds of digits.\nimport math\nimport random\ndef modin(a, m):\n   u1, u2, u3 = 1, 0, a\n   v1, v2, v3 = 0, 1, m\n   \n   while v3 != 0:\n      q = u3 // v3 #divides floors the result\n      v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3\n   return u1 % m\n\nlowprimes = lowPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, \n   67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, \n   157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, \n   251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,317, 331, 337, 347, 349, \n   353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, \n   457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, \n   571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, \n   673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, \n   797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, \n   911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]\nprint(len(lowprimes))\np=lowprimes[random.randrange(0,168)]# randomly pick a prime number:p\nq=lowprimes[random.randrange(0,168)]# randomly pick a prime number:q\nn=p*q\na=p-1 # meant to be p-1\nb=q-1 # meant to be q-1\npek=0 #encryption key or e or public key\nprk=0 #decryption key or d or private key\ne=2\nd=1\nf=a*b\nfac=[]\ncan=[]\nprint('p is',p)\nprint('q is',q)\nprint(' p-1 is ',a)\nprint(' q-1 is ',b)\nfor i in range(0,168): #This will get the list of primes that are not the factors of (p-1)*(q-1). (also called f)\n    if(f%lowprimes[i]!=0): #hence fac holds the public key candidates\n        fac.append(lowprimes[i])\npek=fac[random.randrange(0,len(fac))]  #public key\nprk=modin(pek,f)#function for modulo inverse\nprint(\"n\",n)\nprint(\"public key; \",pek)\nprint(\"private key: \",prk)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"                                                 Encryption and Decryption using RSA\nTo encrypt with RSA the unicode or ascii value of each charecter in your message is taken, then it is raised to the power of the either one of the keys. The value obtained is divided by n and the remainder is taken. \n\nTo decrypt each individual value is taken and raise to the power of the key the other key in the pair. The value obtained is divided by n and the remainder is the ascii value of the charecter. "},{"metadata":{"trusted":true},"cell_type":"code","source":"#this code will demonstrate the encryption and decryption process with RSA. We will consider the key pair already generated\n# eariler. We will encrypted the message with the private key and decrypted it with the public key.\nm='Hello World'#the message to be encrypted\ne=[]#this will store the encrypted message\nf=[]\nfor i in range(0,len(m)):\n    b=(pow(ord(m[i]),prk)%n)\n    e.append(b)\nprint(e)# e will appera like random gibberish because it it encrypted text\nfor i in range(0,len(e)):\n    b=chr((pow(e[i],pek)%n))\n    f.append(b)\nprint(f)\n    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The code in the next cells will read 2 videos one fake and one real. The real video will be signed with the private key \ngenerated earlier. "},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#this function will show how the idea will work. First we will sign a real video.\nimport cv2\nimport numpy as np\nimport hashlib as hb\na=[]\nfile = \"/kaggle/input/videos/dkuayagnmc.mp4\" # the real video\nBLOCK_SIZE = 65536 # The size of each read from the file\n\nfile_hash = hb.sha256() # Create the hash object, can use something other than `.sha256()` if you wish\nwith open(file, 'rb') as f: # Open the file to read it's bytes\n    fb = f.read(BLOCK_SIZE) # Read from the file. Take in the amount declared above\n    while len(fb) > 0: # While there is still data being read from the file\n        file_hash.update(fb) # Update the hash\n        fb = f.read(BLOCK_SIZE) # Read the next block from the file\n#print (file_hash.hexdigest())\nc1=file_hash.hexdigest()\nprint(\"real video unsigned hash\",c1)\ne=[]\nfor i in range(0,len(c1)):\n    d=(pow(ord(c1[i]),prk)%n)\n    e.append(d)\nprint(\"real video signed hash\",e)\n#now e has the signed hash of the real video","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now if someone wants to prove the fake video is fake, then need to hash the video then take the signed hash and decrypt\nit with the public key. If the decrypted hash and the hash of the fake video is not equal we can say the video is fake indeed.\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"file=\"/kaggle/input/videos/ahbweevwpv.mp4\" #the fake video\nhs=[]\nwith open(file, 'rb') as f: # Open the file to read it's bytes\n    fb = f.read(BLOCK_SIZE) # Read from the file. Take in the amount declared above\n    while len(fb) > 0: # While there is still data being read from the file\n        file_hash.update(fb) # Update the hash\n        fb = f.read(BLOCK_SIZE) # Read the next block from the file\n#print (file_hash.hexdigest())\nc=file_hash.hexdigest()\nfor i in range(0,len(e)): #this loop will decrypt the hash of the real video\n    d=chr((pow(e[i],pek)%n))\n    hs.append(d)\nprint(\"fake video hash\",c)\nhs=str(hs)\nprint(\"real video decrypted hash\",hs)\n","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}