SlideShare une entreprise Scribd logo
1  sur  9
Télécharger pour lire hors ligne
import random
from random import randrange, getrandbits
from math import log10
from time import time
from functools import reduce
from itertools import repeat
# FRSA
# By: KHAN FARHAN RAFAT
# This code is provided as it is. No implicit and explicit obligations
# Use @ your own RISK
# Credits: Author
# The RSA result (output) is transposed using a key that can be made dynamic :)
# Contacts: ubiquitousorpervasive@gmail.com
def mInverse(p, q):
def xgcd(xP, yP):
#Extended Euclidean Algorithm
seed1, seed0 = 0, 1
t1, t0 = 1, 0
while yP:
q = xP // yP
xP, yP = yP, xP % yP
seed1, seed0 = seed0 - q * seed1, seed1
t1, t0 = t0 - q * t1, t1
return xP, seed0, t0
sP, tP = xgcd(p, q)[0:2]
assert sP == 1
if tP < 0:
tP += q
return tP
def genPrime(nP):
def isPrime(nP, t=7):
def ifComposite(aP):
if pow(aP, dP, nP) == 1:
return False
for i in range(s):
if pow(aP, 2 ** i * dP, nP) == nP - 1:
return False
return True
assert nP > 0
if nP < 3:
return [False, False, True][nP]
elif not nP & 1:
return False
else:
s, dP = 0, nP - 1
while not dP & 1:
s += 1
dP >>= 1
for _ in repeat(None, t):
if ifComposite(randrange(2, n)):
return False
return True
p = getrandbits(n)
while not isPrime(p):
p = getrandbits(n)
return p
# https://crypto.stackexchange.com/questions/3110/impacts-of-not-using-rsa-exponent-of-65537
def genRSA(p, q):
phie, n = (p - 1) * (q - 1), p * q
if n < 65537:
return (3, mInverse(3, phie), n)
else:
return (65537, mInverse(65537, phie), n)
def t2i(text):
return reduce(lambda x, y: (x << 8) + y, map(ord, text))
def i2t(number, size):
text = "".join([chr((number >> j) & 0xff)
for j in reversed(range(0, size << 3, 8))])
return text.lstrip("x00")
def i2l(number, size):
return [(number >> j) & 0xff
for j in reversed(range(0, size << 3, 8))]
def l2i(listInt):
return reduce(lambda x, y: (x << 8) + y, listInt)
def sizeofModulous(mod):
sizeofModulous = len("{:02x}".format(mod)) // 2
return sizeofModulous
def encryptIt(ptext, pk, mod):
size = sizeofModulous(mod)
output = []
while ptext:
nbytes = min(len(ptext), size - 1)
aux1 = t2i(ptext[:nbytes])
assert aux1 < mod
aux2 = pow(aux1, pk, mod)
output += i2l(aux2, size + 2)
ptext = ptext[size:]
return output
def decryptIt(ctext, sk, p, q):
mod = p * q
size = sizeofModulous(mod)
output = ""
while ctext:
auxP = l2i(ctext[:size + 2])
assert auxP < mod
m1 = pow(auxP, sk % (p - 1), p)
m2 = pow(auxP, sk % (q - 1), q)
hP = (mInverse(q, p) * (m1 - m2)) % p
aux4 = m2 + hP * q
output += i2t(aux4, size)
ctext = ctext[size + 2:]
return output
def transP(matrix, words):
cipher = ''
length = len(matrix)
blanks = ''.join(' ' for i in range(length - 1))
for x in range(0, len(words), length):
# todo optimization
item = words[x: x + length] + blanks
for pos in matrix:
cipher += item[pos - 1]
return cipher
def rotaTe(matrix):
length = len(matrix)
arr = [0] * length
for i in range(length):
arr[matrix[i] - 1] = i + 1
return arr
def printHexList(intList):
for index, elem in enumerate(intList):
if index % 32 == 0:
print()
print("{:02x}".format(elem), end="")
print()
def printLargeInteger(number):
string = "{:02x}".format(number)
for jP in range(len(string)):
if jP % 64 == 0:
print()
print(string[jP], end="")
print()
def useCase(p, q, msg):
#print("Computed Key size is : {:0d} bits".format(round(log10(p * q) / log10(2))))
pk, sk, mod = genRSA(p, q)
print("nPhi ",end="")
printLargeInteger(mod)
print("nNow Encrypting ... ... ...")
st = time()
cText = reduce(lambda string, item: string + chr(item), encryptIt(msg, pk, mod), "")
print("nCiphertext: ")
print(cText)
matrix = [6, 2, 4, 1, 7, 3, 8, 5]
ciphertext = transP(matrix, cText)
print("nTransposed String:n", end="")
print(ciphertext)
en = time()
print("Encryption took ", end="")
print("({:0.3f}) seconds".format(round(en - st, 3)))
print("-------------------------------")
print("nNow Decrypting ... ... ...")
st = time()
secret = rotaTe(matrix)
cText=transP(secret, ciphertext).strip()
print("nReversed Transposition n", cText)
k = []
for c in cText:
k.append(ord(c))
cText = k
pText = decryptIt(cText, sk, p, q)
en = time()
print("nDecrypted Text:", pText)
print("nDecryption took ", end="")
print("({:0.3f}) seconds".format(round(en - st, 3)))
print("-------------------------------")
if __name__ == "__main__":
Message=input("Type in your Message! : ")
n=int(input("Enter Length (in bits) for generating Primes p and q ! (256, 512, 1024, 2048) : "))
st = time()
p = genPrime(n)
q = genPrime(n)
en = time()
print("nPrime (p): ", end="")
printLargeInteger(p)
print("nPrime (q): ", end="")
printLargeInteger(q)
print("nTime elapsed in generating {:0d}-bit prime = ".format(n), end="")
print("({:0.3f}) seconds".format(round(en - st, 3)))
print("----------------------------------------------------------")
useCase(p, q, Message)

Contenu connexe

Tendances

Computer graphics programs in c++
Computer graphics programs in c++Computer graphics programs in c++
Computer graphics programs in c++Ankit Kumar
 
Go vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoFGo vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoFTimur Safin
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changeshayato
 
Pythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPUPythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPUPaulo Sergio Lemes Queiroz
 
Short intro to the Rust language
Short intro to the Rust languageShort intro to the Rust language
Short intro to the Rust languageGines Espada
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat SheetKarlijn Willems
 
The simplest existential graph system
The simplest existential graph systemThe simplest existential graph system
The simplest existential graph systemArmahedi Mahzar
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Platonov Sergey
 
20170714 concurrency in julia
20170714 concurrency in julia20170714 concurrency in julia
20170714 concurrency in julia岳華 杜
 
関数プログラミングことはじめ revival
関数プログラミングことはじめ revival関数プログラミングことはじめ revival
関数プログラミングことはじめ revivalNaoki Kitora
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheetGil Cohen
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
ゼロから始めるScala文法
ゼロから始めるScala文法ゼロから始めるScala文法
ゼロから始めるScala文法Ryuichi ITO
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesSubhajit Sahu
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat SheetGlowTouch
 

Tendances (20)

Computer graphics programs in c++
Computer graphics programs in c++Computer graphics programs in c++
Computer graphics programs in c++
 
C++ TUTORIAL 7
C++ TUTORIAL 7C++ TUTORIAL 7
C++ TUTORIAL 7
 
Go vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoFGo vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoF
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changes
 
Pythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPUPythonbrasil - 2018 - Acelerando Soluções com GPU
Pythonbrasil - 2018 - Acelerando Soluções com GPU
 
Short intro to the Rust language
Short intro to the Rust languageShort intro to the Rust language
Short intro to the Rust language
 
Python For Data Science Cheat Sheet
Python For Data Science Cheat SheetPython For Data Science Cheat Sheet
Python For Data Science Cheat Sheet
 
Cquestions
Cquestions Cquestions
Cquestions
 
The simplest existential graph system
The simplest existential graph systemThe simplest existential graph system
The simplest existential graph system
 
Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”Rainer Grimm, “Functional Programming in C++11”
Rainer Grimm, “Functional Programming in C++11”
 
Py3k
Py3kPy3k
Py3k
 
20170714 concurrency in julia
20170714 concurrency in julia20170714 concurrency in julia
20170714 concurrency in julia
 
関数プログラミングことはじめ revival
関数プログラミングことはじめ revival関数プログラミングことはじめ revival
関数プログラミングことはじめ revival
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
Coding
CodingCoding
Coding
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
2 a networkflow
2 a networkflow2 a networkflow
2 a networkflow
 
ゼロから始めるScala文法
ゼロから始めるScala文法ゼロから始めるScala文法
ゼロから始めるScala文法
 
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : NotesCUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
CUDA First Programs: Computer Architecture CSE448 : UAA Alaska : Notes
 
Python Cheat Sheet
Python Cheat SheetPython Cheat Sheet
Python Cheat Sheet
 

Similaire à Frsa

Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for SpeedYung-Yu Chen
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxhappycocoman
 
Sparse Matrix and Polynomial
Sparse Matrix and PolynomialSparse Matrix and Polynomial
Sparse Matrix and PolynomialAroosa Rajput
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1Ke Wei Louis
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014PyData
 
A scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codeA scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codePVS-Studio LLC
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryDatabricks
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryDatabricks
 
第13回数学カフェ「素数!!」二次会 LT資料「乱数!!」
第13回数学カフェ「素数!!」二次会 LT資料「乱数!!」第13回数学カフェ「素数!!」二次会 LT資料「乱数!!」
第13回数学カフェ「素数!!」二次会 LT資料「乱数!!」Ken'ichi Matsui
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingSaurabh Singh
 
Python basic
Python basic Python basic
Python basic sewoo lee
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manualUma mohan
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFTvikram mahendra
 

Similaire à Frsa (20)

Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
 
Sparse Matrix and Polynomial
Sparse Matrix and PolynomialSparse Matrix and Polynomial
Sparse Matrix and Polynomial
 
Super Advanced Python –act1
Super Advanced Python –act1Super Advanced Python –act1
Super Advanced Python –act1
 
Array
ArrayArray
Array
 
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
Pythran: Static compiler for high performance by Mehdi Amini PyData SV 2014
 
A scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ codeA scrupulous code review - 15 bugs in C++ code
A scrupulous code review - 15 bugs in C++ code
 
Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
 
Nbvtalkatbzaonencryptionpuzzles
NbvtalkatbzaonencryptionpuzzlesNbvtalkatbzaonencryptionpuzzles
Nbvtalkatbzaonencryptionpuzzles
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
User Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love StoryUser Defined Aggregation in Apache Spark: A Love Story
User Defined Aggregation in Apache Spark: A Love Story
 
第13回数学カフェ「素数!!」二次会 LT資料「乱数!!」
第13回数学カフェ「素数!!」二次会 LT資料「乱数!!」第13回数学カフェ「素数!!」二次会 LT資料「乱数!!」
第13回数学カフェ「素数!!」二次会 LT資料「乱数!!」
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Gentle Introduction to Functional Programming
Gentle Introduction to Functional ProgrammingGentle Introduction to Functional Programming
Gentle Introduction to Functional Programming
 
Python basic
Python basic Python basic
Python basic
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Programs in array using SWIFT
Programs in array using SWIFTPrograms in array using SWIFT
Programs in array using SWIFT
 
PRACTICAL COMPUTING
PRACTICAL COMPUTINGPRACTICAL COMPUTING
PRACTICAL COMPUTING
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 

Dernier

Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 

Dernier (20)

Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 

Frsa

  • 1. import random from random import randrange, getrandbits from math import log10 from time import time from functools import reduce from itertools import repeat # FRSA # By: KHAN FARHAN RAFAT # This code is provided as it is. No implicit and explicit obligations # Use @ your own RISK # Credits: Author # The RSA result (output) is transposed using a key that can be made dynamic :) # Contacts: ubiquitousorpervasive@gmail.com def mInverse(p, q): def xgcd(xP, yP): #Extended Euclidean Algorithm seed1, seed0 = 0, 1 t1, t0 = 1, 0 while yP: q = xP // yP xP, yP = yP, xP % yP seed1, seed0 = seed0 - q * seed1, seed1 t1, t0 = t0 - q * t1, t1 return xP, seed0, t0 sP, tP = xgcd(p, q)[0:2] assert sP == 1
  • 2. if tP < 0: tP += q return tP def genPrime(nP): def isPrime(nP, t=7): def ifComposite(aP): if pow(aP, dP, nP) == 1: return False for i in range(s): if pow(aP, 2 ** i * dP, nP) == nP - 1: return False return True assert nP > 0 if nP < 3: return [False, False, True][nP] elif not nP & 1: return False else: s, dP = 0, nP - 1 while not dP & 1: s += 1 dP >>= 1 for _ in repeat(None, t): if ifComposite(randrange(2, n)):
  • 3. return False return True p = getrandbits(n) while not isPrime(p): p = getrandbits(n) return p # https://crypto.stackexchange.com/questions/3110/impacts-of-not-using-rsa-exponent-of-65537 def genRSA(p, q): phie, n = (p - 1) * (q - 1), p * q if n < 65537: return (3, mInverse(3, phie), n) else: return (65537, mInverse(65537, phie), n) def t2i(text): return reduce(lambda x, y: (x << 8) + y, map(ord, text)) def i2t(number, size): text = "".join([chr((number >> j) & 0xff) for j in reversed(range(0, size << 3, 8))]) return text.lstrip("x00")
  • 4. def i2l(number, size): return [(number >> j) & 0xff for j in reversed(range(0, size << 3, 8))] def l2i(listInt): return reduce(lambda x, y: (x << 8) + y, listInt) def sizeofModulous(mod): sizeofModulous = len("{:02x}".format(mod)) // 2 return sizeofModulous def encryptIt(ptext, pk, mod): size = sizeofModulous(mod) output = [] while ptext: nbytes = min(len(ptext), size - 1) aux1 = t2i(ptext[:nbytes]) assert aux1 < mod aux2 = pow(aux1, pk, mod) output += i2l(aux2, size + 2)
  • 5. ptext = ptext[size:] return output def decryptIt(ctext, sk, p, q): mod = p * q size = sizeofModulous(mod) output = "" while ctext: auxP = l2i(ctext[:size + 2]) assert auxP < mod m1 = pow(auxP, sk % (p - 1), p) m2 = pow(auxP, sk % (q - 1), q) hP = (mInverse(q, p) * (m1 - m2)) % p aux4 = m2 + hP * q output += i2t(aux4, size) ctext = ctext[size + 2:] return output def transP(matrix, words): cipher = '' length = len(matrix) blanks = ''.join(' ' for i in range(length - 1)) for x in range(0, len(words), length): # todo optimization item = words[x: x + length] + blanks
  • 6. for pos in matrix: cipher += item[pos - 1] return cipher def rotaTe(matrix): length = len(matrix) arr = [0] * length for i in range(length): arr[matrix[i] - 1] = i + 1 return arr def printHexList(intList): for index, elem in enumerate(intList): if index % 32 == 0: print() print("{:02x}".format(elem), end="") print() def printLargeInteger(number): string = "{:02x}".format(number) for jP in range(len(string)): if jP % 64 == 0: print() print(string[jP], end="")
  • 7. print() def useCase(p, q, msg): #print("Computed Key size is : {:0d} bits".format(round(log10(p * q) / log10(2)))) pk, sk, mod = genRSA(p, q) print("nPhi ",end="") printLargeInteger(mod) print("nNow Encrypting ... ... ...") st = time() cText = reduce(lambda string, item: string + chr(item), encryptIt(msg, pk, mod), "") print("nCiphertext: ") print(cText) matrix = [6, 2, 4, 1, 7, 3, 8, 5] ciphertext = transP(matrix, cText) print("nTransposed String:n", end="") print(ciphertext) en = time() print("Encryption took ", end="") print("({:0.3f}) seconds".format(round(en - st, 3))) print("-------------------------------") print("nNow Decrypting ... ... ...") st = time() secret = rotaTe(matrix)
  • 8. cText=transP(secret, ciphertext).strip() print("nReversed Transposition n", cText) k = [] for c in cText: k.append(ord(c)) cText = k pText = decryptIt(cText, sk, p, q) en = time() print("nDecrypted Text:", pText) print("nDecryption took ", end="") print("({:0.3f}) seconds".format(round(en - st, 3))) print("-------------------------------") if __name__ == "__main__": Message=input("Type in your Message! : ") n=int(input("Enter Length (in bits) for generating Primes p and q ! (256, 512, 1024, 2048) : ")) st = time() p = genPrime(n) q = genPrime(n) en = time() print("nPrime (p): ", end="") printLargeInteger(p) print("nPrime (q): ", end="") printLargeInteger(q)
  • 9. print("nTime elapsed in generating {:0d}-bit prime = ".format(n), end="") print("({:0.3f}) seconds".format(round(en - st, 3))) print("----------------------------------------------------------") useCase(p, q, Message)