Your IP : 216.73.216.40


Current Path : /var/www/html/venkat/
Upload File :
Current File : /var/www/html/venkat/rsa_attack.py

# -*- coding: utf-8 -*-
"""rsa-attack.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1GpqwM_6umL5CR0yrRqioIpcdacZ9W9m_
"""

#These codes are taken from various sources. Thanks to all authors and source
#Attack using CRT
#https://www.johndcook.com/blog/2019/03/06/rsa-exponent-3/
from secrets import randbits, randbelow
from sympy import nextprime
from sympy.ntheory.modular import crt
    
def modulus():
   p = nextprime(randbits(6))
   q = nextprime(randbits(6))
   print("P,Q =",p,q)
   return p*q
    
N = [modulus() for _ in range(3)]
print("N =", N)
m = randbelow(min(N))
print("m =",m)
c = [pow(m, 3, N[i]) for i in range(3)]
x = crt(N, c)[0]
print("c =",c)    
print("x =",x)
print("m =",x**(1./3.))

#attack using the common modulus
#https://www.di-mgt.com.au/rsa_factorize_n.html
import math
N = 25777 
e =3
d=16971 

k = (d * e) -1

for g in range (2,N-1):
  t = k
  print("g------------", g)
  d = 0;
  while (t % 2 == 0):
    t = t/2 
    print("t = ",t)
    t = int(t)
    x = pow(g,t) % N
    print("x = ",x)
    if(x > 1):
      y = math.gcd(x-1,N)
      if(y > 1):
        print("p=",y)
        print("y=",N/y)
        print("True")
        d = 1;
        break     
      else:
        d = 0;
        print("False")
  if(d==1):
      break
  print("\n")

#hashing from geeksforgeeks
import hashlib
  
# initializing string
str = "GeeksforGeeks"
  
result = hashlib.sha256(str.encode())
  
print("The hexadecimal equivalent of SHA256 is : ")
print(result.hexdigest())

#RSA
!pip install PyCrypto
#import cartopy
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA512, SHA384, SHA256, SHA, MD5
from Crypto import Random
from base64 import b64encode, b64decode
hash = "SHA-256"

def newkeys(keysize):
   random_generator = Random.new().read
   key = RSA.generate(keysize, random_generator)
   private, public = key, key.publickey()
   return public, private

def importKey(externKey):
   return RSA.importKey(externKey)

def getpublickey(priv_key):
   return priv_key.publickey()

def decrypt(ciphertext, priv_key):
   cipher = PKCS1_OAEP.new(priv_key)
   return cipher.decrypt(ciphertext)

def encrypt(message, pub_key):
   cipher = PKCS1_OAEP.new(pub_key)
   return cipher.encrypt(message)

public, private = newkeys(1024)
print("publickey = ", public)
print("publickey  e= ",private.e)
print("privatekey d= ",private.d)
print("N = ", private.n)
c = encrypt(b"hello",public)
print("cipher text = ", c)
p = decrypt(c,private)
print("plaintext = ",p)