Wednesday, February 24, 2016

Using OpenSSL to decrypt an encrypted message exported by Python

This tutorial involves three parts:

(1) OpenSSL: Generate a private and public key pair using. 
(2) Python: Use the public key to export an encrypted message.
(3) OpenSSL: Decrypt the message using the private key.

(1) OpenSSL

Generate an RSA private and public key pair in PEM format.

1. Generate a 1024-bit private key:

sudo openssl genrsa -out private_key.pem 1024

2. Obtain a public key from the private key:

sudo openssl rsa -in private_key.pem -pubout -out public_key.pem

(2) Python

1. Edit a Python file called encrypt.py as:


from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

f = open("public_key.pem","r")
public_key = RSA.importKey(f.read())
f.close()

# Generate a cypher using the PKCS1 v1.5 standard.
# See: GitHub: EncryptionExample/python/encrypt.py
cipher = PKCS1_v1_5.new(public_key)

message = "Secret message in Python file"

encrypted = cipher.encrypt(message)

f = open("encrypted.txt","w")
f.write(encrypted)
f.close()

print "OK"

2. Produce the  file with this command:

sudo python encrypt.py

(3) OpenSSL



Decrypt encrypted.txt with private_key.pem using this command:


openssl rsautl -in encrypted.txt -decrypt -inkey private_key.pem

Note


PKCS#1 v1.5 padding is required in encrypt.py. Without it, this error may happen with the OpenSSL decryption command:


RSA operation error

rsa routines:RSA_EAY_PRIVATE_DECRYPT:data greater than mod len:rsa_eay.c:523:

References:

Encrypt/decrypt a string with code-generated RSA public/private keys in Python
Encrypt/decrypt a string with RSA public/private PEM files using Python
OpenSSL RSA commands to encrypt/decrypt a message in terminal

Friday, February 19, 2016

Read/Write a file in Python

The Python code below shows how to write a string to a storage file and then print the file content by reading:


open("storage.txt","w").write("Hello, World!")

readStr = open("storage.txt","r").read()

print readStr

iOS version:

Read/Write a file in an iOS app (Swift 2)

Thursday, February 18, 2016

OpenSSL RSA commands to encrypt/decrypt a message in terminal

It is possible to use OpenSSL commands to:

(1) generate an RSA private/public key pair.
(2) encrypt and decrypt a message using the private/public keys generated.

Some explanations:
(1) Generate an RSA private key first. The public key can then be obtained from the private key.
(2) Use different keys of the same key pair for encrypting/decrypting. For example, encrypt a message with the public key and then decrypt the encrypted message with the private A cryptosystem using this public-private key mechanism is known as asymmetric because different keys are used for encrypting/decrypting.

The following terminal commands have been tested on a Raspberry Pi and a Mac.

For Raspberry Pi, commands may need an extra sudo word in front of openssl or executed in the desktop folder.

1. Generate an RSA private and public key pair in PEM format:

Generate a 1024-bit private key:

openssl genrsa -out private_key.pem 1024

Obtain a public key from the private key:

openssl rsa -in private_key.pem -pubout -out public_key.pem



2. Create a message.txt file and edit its content:

sudo nano message.txt



3. Encrypt message.txt with public_key.pem using this command:

openssl rsautl -in message.txt -encrypt -pubin -inkey public_key.pem > encrypted.txt



4. Decrypt encrypted.txt with private_key.pem using this command:


Tuesday, January 19, 2016

Sending an RSA encrypted message from client to Python socket server


The example below shows how to send an RSA encrypted message from a client to a Python socket server.

A Mac is used as the client, while a Raspberry Pi is used as the server. For the introduction to the Python socket server, refer to this:
Connect Mac / iPhone to a Simple Python Socket Server

Connection procedure of this example
1. Private and public keys generated in server.
2. Server enabled to listen to client.
3. Client sends "Client: OK" to server.
4. Server sends public key to client.
5. Client uses the public key to encrypt a message, which is then sent to server. 
6. Server decrypts the message and informs client "Server: OK".
7. Client tells the server to "Quit".
8. Both server and client are stopped.

Configurations for the server and client are as below:

Server (Raspberry Pi)

1. Install Python-Crypto.

sudo apt-get install python-crypto




2. Use sudo nano server_rsa.py command to edit a python file as below:

import socket
from Crypto.PublicKey import RSA
from Crypto import Random

#Generate private and public keys
random_generator = Random.new().read
private_key = RSA.generate(1024, random_generator)
public_key = private_key.publickey()

#Declartion
mysocket = socket.socket()
host = socket.gethostbyname(socket.getfqdn())
port = 7777
encrypt_str = "encrypted_message="

if host == "127.0.1.1":
    import commands
    host = commands.getoutput("hostname -I")
print "host = " + host

#Prevent socket.error: [Errno 98] Address already in use
mysocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

mysocket.bind((host, port))

mysocket.listen(5)

c, addr = mysocket.accept()

while True:

    #Wait until data is received.
    data = c.recv(1024)
    data = data.replace("\r\n", '') #remove new line character

    if data == "Client: OK":
        c.send("public_key=" + public_key.exportKey() + "\n")
        print "Public key sent to client."

    elif encrypt_str in data: #Reveive encrypted message and decrypt it.
        data = data.replace(encrypt_str, '')
        print "Received:\nEncrypted message = "+str(data)
        encrypted = eval(data)
        decrypted = private_key.decrypt(encrypted)
        c.send("Server: OK")
        print "Decrypted message = " + decrypted

    elif data == "Quit": break

#Server to stop
c.send("Server stopped\n")
print "Server stopped"
c.close()

Client (Mac)

1. Install Python-Crypto.

sudo easy_install pycrypto

2. Use sudo nano client_rsa.py command to edit a python file as below:

import socket
from Crypto.PublicKey import RSA

server = socket.socket()
host = "192.168.xx.xx"
port = 7777

server.connect((host, port))

#Tell server that connection is OK
server.sendall("Client: OK")

#Receive public key string from server
server_string = server.recv(1024)

#Remove extra characters
server_string = server_string.replace("public_key=", '')
server_string = server_string.replace("\r\n", '')

#Convert string to key
server_public_key = RSA.importKey(server_string)

#Encrypt message and send to server
message = "This is my secret message."
encrypted = server_public_key.encrypt(message, 32)
server.sendall("encrypted_message="+str(encrypted))

#Server's response
server_response = server.recv(1024)
server_response = server_response.replace("\r\n", '')
if server_response == "Server: OK":
    print "Server decrypted message successfully"

#Tell server to finish connection
server.sendall("Quit")
print(server.recv(1024)) #Quit server response
server.close()

Result

1. Type this command at the server:

python server_rsa.py

2. Type this command at the client:

python client_rsa.py

3. Result at the server:

host = 192.168.xx.xx 
Public key sent to client.
Received:
Encrypted message = ('\x9a\xe0\x08\xa1\xb6\x86?\xc7\xde\xb6\xa0\xbe\xa7!\xecem.\xb1R\xc5h\x19cv]{\xd3\x04\xcf\x0e\xf0\xfe\xc50\x1e\xc9U\xff\xd5\xf2\xb1,EQ\xdf2\x89![\xb7s\x84:C\xbdg\xbf$\x05\'\xb8@GK\x18Q\xd5N\xe9\x13\x12e\x8c\xe7F\xc8+\x95\xcdj\xb6\xcc9\xc8-t\x17-\xb8\xdei\x8f\x90\xdd\xcf\xd9@\xa0\xf8\xe8\xe5\xcci\xea"M\x82\xb8%\xf7\xfccc G{\x16A)\xf2\xcb"\x15\xa8\x16\xd3M',)
Decrypted message = This is my secret message.
Server stopped

4. Result at the client:

Server decrypted message successfully
Server stopped


References:

Connect Mac / iPhone to a Simple Python Socket Server
Encrypt / decrypt a string with RSA public / private keys in PHP
Encrypt / decrypt a string with RSA public / private PEM files using Python
Encrypt / decrypt a string with code-generated RSA public / private keys in Python

iOS:
Encrypt / decrypt a string with RSA public / private keys in Swift

Encrypt/decrypt a string with code-generated RSA public/private keys in Python

This post shows how to:

- generate private and public RSA keys in Python.
- encrypt and decrypt a string using Python.

1. Install Python-Crypto.

sudo apt-get install python-crypto

2. Use sudo nano rsa_generate.py command to edit a python file as below:


from Crypto.PublicKey import RSA
from Crypto import Random

#Generate private and public keys
random_generator = Random.new().read
private_key = RSA.generate(1024, random_generator)
public_key = private_key.publickey()

message = "The quick brown fox jumps over the lazy dog."

#Encrypt with public key
encrypted = public_key.encrypt(message, 32)

#Decrypt with private key
decrypted = private_key.decrypt(encrypted)


print decrypted

3. Execute the file with this command:


python rsa_generate.py

References:

Encrypt/decrypt a string with RSA public/private keys in PHP
Encrypt/decrypt a string with RSA public/private PEM files using Python
Sending an RSA encrypted message from client to Python socket server

iOS:
Encrypt/decrypt a string with code-generated RSA public/private keys in Swift

Go back to Communication between iOS device (Client) and Raspberry Pi (Server)

Monday, January 18, 2016

Encrypt/decrypt a string with RSA public/private PEM files using Python

This post shows how to:

- generate private and public RSA keys using OpenSSL command.
- encrypt and decrypt a string using Python.

Public Key and Private Key Generation


1. Generate a 1024-bit private key:

openssl genrsa -out private_key.pem 1024

2. Obtain a public key from the private key:

openssl rsa -in private_key.pem -pubout -out public_key.pem

Encrypt and decrypt a string using Python

1. Install Python-Crypto.

sudo apt-get install python-crypto




2. Use sudo nano rsa.py command to edit a python file as below:


from Crypto.PublicKey import RSA

public_key_string = open("public_key.pem","r").read()
public_key = RSA.importKey(public_key_string)

private_key_string = open("private_key.pem","r").read()
private_key = RSA.importKey(private_key_string)

message = "The quick brown fox jumps over the lazy dog."

#Encrypt with public key
encrypted = public_key.encrypt(message, 32)

#Decrypt with private key
decrypted = private_key.decrypt(encrypted)

print decrypted


3. Execute the file with this command:

python rsa.py


References:
Encrypt/decrypt a string with RSA public/private keys in PHP
Encrypt/decrypt a string with code-generated RSA public/private keys in Python
Sending an RSA encrypted message from client to Python socket server

iOS:
Encrypt/decrypt a string with RSA public/private keys in Swift
Encrypt/decrypt a string with public/private keys imported from PEM files (Swift)

Go back to Communication between iOS device (Client) and Raspberry Pi (Server)

Encrypt/decrypt a string with RSA public/private keys in PHP

This post shows how to:

- generate private and public RSA keys using OpenSSL.
- encrypt and decrypt a string in PHP.

Requirements

Install these on a Raspberry Pi:
- Apache HTTP server
- PHP

Public Key and Private Key Generation

1. Create a folder to hold the public and private keys under /var/www:

mkdir RSA

Enter the folder:

cd RSA

2. Check man pages below and type Q to quit:

- Generate a RSA private key:

man genrsa

- RSA key processing tool:

man rsa

Check for the -pubout option. A public key will be output with this option.


3. Generate a 1024-bit private key:

openssl genrsa -out private_key.pem 1024

4. Obtain a public key from the private key:

openssl rsa -in private_key.pem -pubout -out public_key.pem



Encrypt and decrypt a string in PHP

1. Go back to the /var/www directory:

cd ..

2. Edit a PHP file with this command:

sudo nano rsa.php

3. Modify the rsa.php file as:


<?php
$fopen_private = fopen("rsa/private_key.pem","r");
$private_key = fread($fopen_private,8192);
fclose($fopen_private);

$fopen_public = fopen("rsa/public_key.pem","r");
$public_key = fread($fopen_public,8192);
fclose($fopen_public);

$pkey_private = openssl_pkey_get_private($private_key);
$pkey_public = openssl_pkey_get_public($public_key);

$data = "<P>My information";
$encrypted = "";
$decrypted = "";

//Encrypt with private key
openssl_private_encrypt($data, $encrypted, $pkey_private);
$encrypted = base64_encode($encrypted);

//Decrypt with public key
openssl_public_decrypt(base64_decode($encrypted), $decrypted, $pkey_public);
print $decrypted;

$encrypted = "";
$decrypted = "";

//Encrypt with public key
openssl_public_encrypt($data, $encrypted, $pkey_public);
$encrypted = base64_encode($encrypted);

//Decrypt with private key
openssl_private_decrypt(base64_decode($encrypted), $decrypted, $pkey_private);
print $decrypted;


?>

4. Open the php file from a browser of a remote computer.




References:
Encrypt/decrypt a string with RSA public/private PEM files using Python
Encrypt/decrypt a string with code-generated RSA public/private keys in Python
php rsa加密解密實例
php rsa加密解密实例
OPENSSL入門

iOS:
Encrypt/decrypt a string with RSA public/private keys in Swift