Cryptography 456 Senior Seminar 599 USC Upstate Encrypted One...

Post on 03-Sep-2020

9 views 0 download

transcript

Cryptography 456Senior Seminar 599USC Upstate

Encrypted One-Way File Transfer on Android DevicesBy Sheldon Smith, Instructor Dr. Zhong

ContentsOne-Way File Transfer DiagramUtilizing CryptographyAsymmetric AlgorithmSymmetric AlgorithmThe Cryptosystem

The ProjectCode OverviewScreen ShotsDemonstration

One-Way File Transfer DiagramPhase 1

Client Server

Generate RSA Key Pair

Receive Server’s Public Key

Decrypt AES Key

Generate AES Key

Encrypt AES Key

Receive Encrypted AES Key

Private Key

Socket

One-Way File Transfer DiagramPhase 2

Client Server

File Input Stream

Cipher Output Stream

Cipher Output Stream

Data Input Stream

File Output Stream

Read in File to Buffer

AES Encrypt Cipher

Data Output Stream

Data Output Stream

Read in Data to Buffer

Data Input Stream

Socket

AES Decrypt Cipher

Utilizing Cryptography

Asymmetric AlgorithmRSA

Symmetric AlgorithmAES (Advanced Encryption Scheme)

Asymmetric Algorithm

RSASupported key lengths: 1,024 to 4,096 bits

Two keys: Public and PrivatePublic is used for encryption

Private is used for decryption

Used to encrypt symmetric key for transportation

Asymmetric Algorithm

RSA (ctd.)Advantages: Solves the problem of

distributing the key

Disadvantages: Impractical for encryption or decryption

Symmetric Algorithm

AES (Advanced Encryption Scheme)Supported key lengths: 128, 192, and 256

bits

Single key, typically referred to as a symmetric key or session key

Used to encrypt and decrypt data

Symmetric Algorithm

AES (ctd.)Advantages: Quick encryption and

decryption, unique key for each session

Disadvantages: Need a secure channel to transfer the key

The Cryptosystem

Implements both asymmetric and symmetric algorithmsAsymmetric algorithm is used for distributing

the symmetric key

Symmetric algorithm is used for encryption and decryption

The ProjectSocket Programming

The server opens a server socket on a unique port, and a user connects to the socket using the IP address and port number

The ProjectThread Diagram

File Transfer Thread

UI Thread (progress bar) UI Thread (UI)

Handler Handler

A thread is a concurrent unit of execution

Code Overview:Android Manifest

<uses-permissionandroid:name="android.permission.INTERNET" />

<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE" />

The manifest holds information about the app needed by the Android system

Code Overview:Android Manifest<activity android:name="com.example.filetransferclient.MenuActivity"

android:label="File Transfer"><intent-filter>

<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />

</intent-filter></activity><activity android:name="com.example.filetransferclient.ServerActivity"

android:label="Server"><intent-filter>

<action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" />

</intent-filter></activity> …..

Code Overview:Menu Activity - Overview

The menu activity was designed and incorporated to improve the flexibility of the app.Instead of a distinguished client and server app, the

menu activity allows the user to choose whether he/she wants to run the app as a server or client.

To achieve this flexibility, intents were utilizedAn intent is a passive data structure holding an abstract

description of an operation to be performed

Code Overview:Menu Activity – XML Sample

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#111111" >

<LinearLayout android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:orientation="horizontal"android:background="#111111" >

<Button android:id="@+id/client_activity”…..…..android:onClick="onClick“android:text="Start Client“android:textColor="#FFFFFF" /> …..

Code Overview:Menu Activity – Code Sample

public void onClick(View v){try{

switch(v.getId()){case R.id.client_activity:

Intent i = new Intent(MenuActivity.this, ClientActivity.class);startActivity(i);break;

case R.id.server_activity:Intent j = new Intent(MenuActivity.this, ServerActivity.class);startActivity(j); …..

Code Overview:Client and Server Activities - Overview

Methods:onCreate()

(Client side only) onClick()

uiHandler()

progressBarHandler()

getLocalIpAddress()

(Server side only) isExternalStorageUsable()

Code Overview:Client and Server Activities – XML Sample

<TextView android:id="@+id/progress_bar_status"android:layout_width="fill_parent" android:layout_height="wrap_content"android:gravity="center_vertical|center_horizontal“…..…..android:textColor="#00FF00"android:visibility="gone" />

<ProgressBar android:id="@+id/progressbar"style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="fill_parent"android:layout_height="30dp".....….android:progressDrawable="@drawable/greenprogress"android:visibility="gone" /> …..

Code Overview:Client and Server Activities – Methods

onCreate()Find all our views by their XML id

mStatusMessagesTv = (TextView) findViewById(R.id.client_local_ip_status_tv);

(Client side only) Instantiate an Alert Dialog to manually input the server device’s IP addressalert = new AlertDialog.Builder(this);

(Server side only) Creates and starts an instance of the File Transfer Server class

fTransferServer = new FileTransferServer(…)fTransferServer.start();

Code Overview:Client and Server Activities – Methods

(Client side only) onClick()Contains the hardcoded file name and retrieves

the file size on the client side

Creates and starts an instance of the File Transfer Client classfTransferClient = new FileTransferClient(SERVERIP,

serverPort, new uiHandler(), new progressBarHandler(), fileName, fileSize, progressBar, progressStatus);

fTransferClient.start();

Code Overview:Client and Server Activities - Methods

uiHandler()Extends the handler class

Handles messages sent back from the File Transfer Client or Server Thread

message = msg.getData().getString("message");mChatBoxTv.setText(mChatBoxTv.getText().toString() + "\n" + message);

Code Overview:Client and Server Activities – Methods

progressBarHandler()Extends the handler class

Handles updates sent back from the File Transfer Client or Server Thread

int progress = msg.getData().getInt("int");progressBar.setProgress(progress);progressStatus.setText(progress + " %");

Code Overview:Client and Server Activities – Methods

getLocalIpAddress()Returns a String representation of a device’s IPv4

address or null if none was found

(Server side only) isExternalStorageUsable()Returns true if external storage can be read and

written to

Returns false for any other combination of access permissions

Code Overview:File Transfer Client and File Transfer Server - Overview

The File Transfer Client and File Transfer Server classes are where all the work is done

They run alongside the uiHandler and progressBarHandler threads

Methods:updateUI()

updateProgressBar()

run()

Code Overview:File Transfer Client and File Transfer Server - Methods

updateUI()Sends bundled message back to the UI handler

Message msg = mHandler.obtainMessage();Bundle b = new Bundle();b.putString("message", message);b.putString("type", "message_display_status");msg.setData(b);mHandler.sendMessage(msg);

Code Overview:File Transfer Client and File Transfer Server - Methods

updateProgressBar()Sends bundled message back to the progress bar

handler

Message msg = pHandler.obtainMessage();Bundle b = new Bundle();b.putInt("int", percent);msg.setData(b);pHandler.sendMessage(msg);

Code Overview:File Transfer Client – run()

run()Connect to the server socket

socket = new Socket(serverIP, serverPort);

Create data input and output streams

DataOutputStream dos = new DataOutputStream(socket.getOutputStream());

Read in server’s public key bytes from socket

int keyLength = dis.readInt();byte[] serverPubKey = new byte[keyLength];dis.readFully(serverPubKey);

Code Overview:File Transfer Client – run()

run() (ctd.)Generate server’s public key using key bytes

X509EncodedKeySpec keySpec = new X509EncodedKeySpec(serverPubKey);

KeyFactory myFactory = KeyFactory.getInstance("RSA");PublicKey pubKey = myFactory.generatePublic(keySpec);

Create AES key and IVKey symmetricKey = CryptoUtils.createAESKey(256,

random);IvParameterSpec ivSpec =

CryptoUtils.createAESCtrIv(random);

Code Overview:File Transfer Client – run()

run() (ctd.)Initialize RSA cipher for encryption

Cipher pubCipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA1AndMGF1Padding");

pubCipher.init(Cipher.ENCRYPT_MODE, pubKey);

Encrypt the AES key for transmissionbyte[] encrAESBytes =

pubCipher.doFinal(symmetricKey.getEncoded());

Code Overview:File Transfer Client – run()

run() (ctd.)Send the encrypted AES key and the IV bytes over

the socketdos.writeInt(encrAESBytes.length);

dos.write(encrAESBytes);dos.write(ivSpec.getIV());

Create and initialize the AES cipher for encryptingCipher symCipher =

Cipher.getInstance("AES/CBC/PKCS5Padding");symCipher.init(Cipher.ENCRYPT_MODE, symmetricKey, ivSpec);

Code Overview:File Transfer Client – run()

run() (ctd.)Create a data input stream

DataInputStream file = new DataInputStream(new FileInputStream(fileName));

Send the packet size and file size over the socketdos.writeInt(FILESEND_PACKET_SIZE);

dos.writeInt(bytesToSend);

Create a cipher output streamCipherOutputStream cos = new CipherOutputStream(dos,

symCipher);

Code Overview:File Transfer Client – run()

run() (ctd.)Transfer the file, simultaneously update the progress

barwhile((bytesRead = file.read(data)) != -1) {

cos.write(data, 0, bytesRead);store += bytesRead;progress = ((float)store/(float)fileSize)*100;pHandler.post(new Runnable(){

public void run() {updateProgressBar((int)progress);

}});

}

Code Overview:File Transfer Server – run()

run()Create the server socket

serverSocket = new ServerSocket(serverPort);

Wait for the client to connect

client = serverSocket.accept();

Create the data input and output streams

DataOutputStream dos = new DataOutputStream(client.getOutputStream());

Code Overview:File Transfer Server – run()

run() (ctd.)Create the RSA key pair generator

KeyPairGenerator generator = KeyPairGenerator.getInstance(“RSA”, “BC”);

generator.initialize(1024, random);

Create an RSA key pair

KeyPair pair = generator.generateKeyPair();PublicKey pubKey = pair.getPublic();PrivateKey privKey = pair.getPrivate();

Code Overview:File Transfer Server – run()

run() (ctd.)Send the RSA public key over the socket

dos.writeInt(pubKey.getEncoded().length);dos.write(pubKey.getEncoded());

Read in the encrypted AES key bytes from the socketbyte[] encrAESKey = new byte[dis.readInt()];

dis.readFully(encrAESKey);

Read in the IV bytes from the socketbyte[] IV = new byte[16];

dis.readFully(IV);

Code Overview:File Transfer Server – run()

run() (ctd.)Initialize the RSA cipher for decryption

Cipher privCipher = Cipher.getInstance(“RSA/NONE/OAEPWITHSHA1ANDMGF1Padding”);

privCipher.init(Cipher.DECRYPT_MODE, privKey);

Decrypt the AES key bytesbyte[] AESKey = privCipher.doFinal(encrAESKey);

Recreate the AES key and IVSecretKeySpec keySpec = new SecretKeySpec(AESKey,

“AES”); …

Code Overview:File Transfer Server – run()

run() (ctd.)Initialize the AES cipher for decryption

Cipher aesCipher = Cipher.getInstance(“AES/CBC/PKCS5Padding”);

aesCipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

Create a data output streamDataOutputStream file = new DataOutputStream(new

FileOutputStream(fileName));Create a cipher output stream

CipherOutputStream cos = new CipherOutputStream(file, aesCipher);

Code Overview:File Transfer Server – run()

run() (ctd.)Receive the file, simultaneously update the progress bar

while((bytesRead = dis.read(data)) != -1){cos.write(data, 0, bytesRead);bytesWritten += bytesRead;progress = ((float)bytesWritten/(float)fileSize)*100;pHandler.post(new Runnable() {

public void run() {updateProgressBar((int)progress);

}});

}

Screenshots

This is the menu activity.

Client: Manual inputting server

IP address.

Server: Waiting for a connection

to be established.

Client: Connected to

server.

Server: Connection has

been established.

Client: Reading in server’s RSA

public key.

Server: Creating and sending

RSA public key.

Client: Generate AES key and IV. Send both over

the socket.

Server: Read in encrypted AES

key and IV. Recreate both

of them.

Client: Initialize AES cipher for

encryption. Create file input

stream and cipher output

stream.

Server: Initialize AES cipher for

decryption. Create file

output stream and cipher

output stream.

Client and Server: File transfer is

complete.