# Demo entry 6787009

RSA

Submitted by boram on Apr 08, 2019 at 16:17
Language: Python. Code size: 1.6 kB.

```# -*- coding: utf-8 -*-
"""
Created on Mon Apr  8 21:13:19 2019

@author: BORAM
"""
def gcd(a, b):
while b!=0:
a, b = b, a%b
return a

def decrypt(pk, ciphertext):
key, n = pk

#복호화 = (Encrypted message)^(private key) mod N
plain = [int((char ** key) % n) for char in ciphertext]

return plain

def encrypt(pk, plaintext):
key, n = pk
#암호화 = (plain text)^(public key) mod N
cipher = [(int(char) ** key) % n for char in plaintext]

return cipher

def get_private_key(e, tot):
k=1
while (e*k)%tot != 1 or k == e:
k+=1
return k

def get_public_key(tot):
e=2
while e<totient and gcd(e, totient)!=1:
e += 1
return e

print("Student ID : 2015125064")
m = input("Enter the text to be encrypted:")

split_msg = m.split(',')

# Step 1. Choose two prime numbers
p = 7
q = 17

print("Two prime numbers(p and q) are:", str(p), "and", str(q))

# Step 2. Compute n = pq which is the modulus of both the keys
n = p*q
print("N(p*q) = ", str(p), "*", str(q), "=", str(n))

# Step 3. Calculate totient
totient = (p-1)*(q-1)
print("(p-1)*(q-1)=", str(totient))

# Step 4. Find public key e
e = get_public_key(totient)
print("Public key(N, e):("+str(n)+","+str(e)+")")

# Step 5. Find private key d
d = get_private_key(e, totient)
print("Private key(N, d):("+str(n)+","+str(d)+")")

# Step 6.Encrypt message
encrypted_msg = encrypt((e,n), split_msg)
print('Encrypted Messages :', encrypted_msg)

# Step 7.Decrypt message
print('Decrypted Messages:', decrypt((d,n),encrypted_msg))
```

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.