Created
April 14, 2014 10:47
-
-
Save kozmonaut/10637077 to your computer and use it in GitHub Desktop.
Extraction of RSA keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Extract RSA keys in separate files | |
""" | |
Example of usage: | |
1. Generate your RSA keys | |
# openssl genrsa 2048 > mykeys.key | |
2. Read keys in human way and save it to a new .txt file | |
# openssl rsa -in mykeys.key -noout -text | |
3. Exclude keys in separate files with rsa-keys.py script | |
""" | |
def readN(file): | |
key = open(file, 'r') | |
counterN = 0 | |
N = '' | |
for line in key: | |
if line[:8] == "modulus:": counterN = 1 | |
if line[:15] == "publicExponent:": counterN = 0 | |
if counterN: N += line | |
N = N[9:] | |
N = N.replace(' ', '') | |
N = N.replace('\n', '') | |
N = N.replace(':','') | |
return int(N, 16) | |
def readE(file): | |
key = open(file, 'r') | |
E = '' | |
for line in key: | |
if line[:15] == "publicExponent:": E = line[16:21] | |
return int(E,10) | |
def readPrime1(file): | |
key = open(file, 'r') | |
counterPrime1 = 0 | |
prime1 = '' | |
for line in key: | |
if line[:7] == "prime1:": counterPrime1 = 1 | |
if line[:7] == "prime2:": counterPrime1 = 0 | |
if counterPrime1: prime1 += line | |
prime1 = prime1[8:] | |
prime1 = prime1.replace(' ', '') | |
prime1 = prime1.replace('\n', '') | |
prime1 = prime1.replace(':','') | |
return int(prime1, 16) | |
def readPrime2(file): | |
key = open(file, 'r') | |
counterPrime2 = 0 | |
prime2 = '' | |
for line in key: | |
if line[:7] == "prime2:": counterPrime2 = 1 | |
if line[:10] == "exponent1:": counterPrime2 = 0 | |
if counterPrime2: prime2 += line | |
prime2 = prime2[8:] | |
prime2 = prime2.replace(' ', '') | |
prime2 = prime2.replace('\n', '') | |
prime2 = prime2.replace(':','') | |
return int(prime2, 16) | |
# Greatest common divisor | |
def gcd(a,b): | |
v,v1 = 0,1 | |
u,u1 = 1,0 | |
while b: | |
q = a // b | |
u,u1 = u1, u-q * u1 | |
v,v1 = v1, v-q * v1 | |
a,b = b, a-q * b | |
return a, u, v | |
def multiInverse(b, m): | |
n,u,v = gcd(b, m) | |
if n == 1: | |
return u%m | |
else: | |
return None | |
if __name__ == "__main__": | |
file = raw_input("Type name of a keys file(Must be in .txt): ") | |
N = readN(file) | |
E = readE(file) | |
D = multiInverse(E, (readPrime1(file)-1)*(readPrime2(file)-1)) | |
data = open("KeyN.txt", "w") | |
data.write(str(N)) | |
data = open("KeyE.txt", "w") | |
data.write(str(E)) | |
data = open("KeyD.txt", "w") | |
data.write(str(D)) | |
print "Numbers E, N and D was sucessfully saved in separate files." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment