SlideShare a Scribd company logo
1 of 71
Download to read offline
1
SUBMITTED AS PART OF
M.ENG INFORMATION AND NETWORK SECURITY
THESIS
Android Chat Application for secured
communication
Author: Supervisor:
Shivakumar koppad Dr.Thomas Newe
2
Declaration
I declare that this thesis is the result of my own research except as cited in the references. This
thesis has not been submitted in candidature of any other award in any other third level
institution.
Signed : _____________________________
Date : _____________________________
3
Acknowledgement
This study wouldn’t have been possible without the constant love, motivation and support of many
people during the journey of my life.
Firstly to my supervisor Dr.Thomas newe for being there always on the side sharing his expertise,
knowledge and motivating me to improvise during the academic year 2014-2015.Definetly he is
one among the very few whom I admire to get inspired with every fresh breath on every sunrise.
To my friends from across the boundaries covering more than half of the globe during my time at
University of Limerick by adding the required vigour, confidence and for being such sport during
all the times especially for person who started his carrier and spent 18 Years of life at very small
town in the north of Karnataka, India.
Nevertheless to My parents and sister who have supported and inspired me to go one step further
during all the difficult times in the roller coaster of life and inspiring me to change the world we
perceive by being the change what self-thrusts for.
4
Abstract
The goal of the thesis is to develop android chat application using eclipse for secured
communication which is compatible to all the versions of android 2.2 and above. Humans work
in collective level along with thought process and speech to convey as there standout
functionalities when compared to other living inhabitants of this planet. With the technology in
everyday life of all the people in 21st century instant chat messaging brings people together from
across the demographic locations and security is as crucial as the communication between two
entities because of the attacks and new vulnerabilities which pops up every new day. Android
being popular and most reliable open source operating system for smartphones with more than
1/6 th of user database in the world, Secured chat communication for such OS will not only make
it more trusted but also helps in elevating humans affinity towards technology. Different security
algorithms such as DES,AES,RSA are used for encryption while sending the data , received text
will be in the form of ciphers at the receivers inbox which will get decrypted once the user wants
to decrypt by copying the contents in the decryption tab.
5
Contents
Table of Figures.............................................................................................................................................7
Introduction ..................................................................................................................................................8
Chapter 2 - Cryptography..............................................................................................................................9
2.1.1 Background of cryptography........................................................................................................9
2.1.2 Cryptography ...............................................................................................................................9
2.1.3 The four building blocks of efficient cryptography are..............................................................10
2.2.1 Vulnerabilities and Exploits........................................................................................................10
2.2.2 Common Vulnerabilities.............................................................................................................10
2.3 Common attacks. ..............................................................................................................................11
2.3.1 Brute force attack – ...................................................................................................................11
2.3.2 Dictionary attacks –....................................................................................................................12
2.3.3 Denial of service attack –...........................................................................................................12
Chapter 3.....................................................................................................................................................14
Security algorithms and key exchange. ..................................................................................................14
3.1 Deffiei-hellman .................................................................................................................................14
3.2.RSA....................................................................................................................................................17
3.3 DES (Data Encryption Standard) algorithm.......................................................................................19
3.4 AES (Advanced Encryption Standard) ...............................................................................................21
3.5 MD5...................................................................................................................................................22
Chapter 4 - Android and chat application...................................................................................................23
4.1 History of Android.............................................................................................................................23
4.2 Below are the different android versions and most of them are named after desserts..................23
4.3 The different tools which android as operating system support for the smartphones are .............24
4.4 Requirements for android on Hardware level..................................................................................26
4.5 Android for chat application.............................................................................................................26
4.5.1 Whats app – ...............................................................................................................................26
4.5.2 Viber-..........................................................................................................................................27
4.5.3 Send –.........................................................................................................................................28
4.5.4 Blackberry Messenger –.............................................................................................................28
4.5.5 Facebook Messenger .................................................................................................................28
6
4.5.6 Skype –.......................................................................................................................................29
Chapter5.0 - Application framework and outlook......................................................................................29
5.1 The following show the architecture of security implementation in secure messaging..................29
5.2 User Interface Description................................................................................................................30
5.3 Use Case Diagram .............................................................................................................................35
5.4 Data flow diagram.............................................................................................................................36
Chapter 6.....................................................................................................................................................37
Application design and architecture...........................................................................................................37
6.0 Integration of JAVA and CRYPTOGRAPHY.........................................................................................37
6.1 JCA Architecture..........................................................................................................................38
6.2 JCE ...............................................................................................................................................39
6.3 Engine Classes.............................................................................................................................39
6.3.1 JCA Engines .........................................................................................................................39
6.3.2 JCA Engines .........................................................................................................................40
6.4 Security protocol...............................................................................................................................41
Chapter 7.0..................................................................................................................................................42
Implementation of Security:.......................................................................................................................42
7.1 RSA Algorithm:..................................................................................................................................42
7.2 DES Algorithm: ..................................................................................................................................44
7.3 AES Algorithm: ..................................................................................................................................47
7.4 Secure MD5 Hashing:........................................................................................................................49
Chapter 8.0 Testing and result....................................................................................................................51
References ..................................................................................................................................................52
Appendix .....................................................................................................................................................54
AESHelper.java........................................................................................................................................54
DESHelper.Java .......................................................................................................................................56
Encryptmessage.java ..............................................................................................................................59
Mainactivity.Java.....................................................................................................................................61
RSAhelper.Java........................................................................................................................................65
Showmsg.java .........................................................................................................................................67
SMSreceiver ............................................................................................................................................68
Splashscreenactivity.Java........................................................................................................................70
7
Table of Figures
Figure 1.Encryption and Decryption of Cryptography................................................................................10
Figure 2.Denial of service attacks. ..............................................................................................................13
Figure 3.Diffie Hellman key exchange.........................................................................................................15
Figure 4.Mathematical computation of Diffie hellman ..............................................................................16
Figure 5.RSA Encryption and Decryption....................................................................................................18
Figure 6.DES algorithm................................................................................................................................20
Figure 7.AES Input.......................................................................................................................................21
Figure 8.Various flavours of Android. .........................................................................................................23
Figure 9.Growth of messaging application whats app................................................................................27
Figure 10.Microsoft line..............................................................................................................................28
Figure 11.Security implementation in instant messaging...........................................................................29
Figure 12.Welcome screen of application. .................................................................................................30
Figure 13.Option to choose between simple and secure texting...............................................................31
Figure 14.Choosing the number from the contact list to send the message. ............................................32
Figure 15.Encryption before sending..........................................................................................................33
Figure 16.Decryption of Message at the receiver side. ..............................................................................34
Figure 17.Use case diagram........................................................................................................................35
Figure 18: JCA Architecture.......................................................................................................................38
8
Introduction
As the world is evolving the need for communication between the people is rising. The extreme
demand is for instant communication is leading the IT developers to come up with new means of
communication which are faster and available widely. In 21st
century internet is considered as
fastest means of communication, why not ? We can send and receive information from every
corner of this planet. Considering the flexibility of internet the service providers are leaning
towards it and coming up new products for communication. Among all the application Android
based applications are appreciated the most. There are many android applications in the market
which provide communication. Providing just communication is not enough on insecure network,
enabling strong security is important as well. The proposed application strikes perfect balance
between security and integrity. The application provides instant communication and at the same
time strong security. Users are allowed to select the security they want and exchange the messages.
The encryption algorithms used in the application are RSA, AES, DES and Deffiei-Hellman.
The message may contain sensitive information that no one should get access to apart from
authorized users. Encrypting the messages before sending over insecure network is important.
RSA is one of the top rated asymmetric encryption algorithm that has been used in the application.
Public key which is available for the sender is used to encrypt the messages and private key is kept
secret by the receiver for decryption. The above mentioned algorithm can strengthen the security
so that no unauthorized entity can learn the information that is being transferred. While sending
the public key by the destination to the sender, anyone can learn it and make use to decrypt the
secret messages. To relent this risk Deffiei-Hellman key exchange algorithm is used. Using this
algorithm two authorized entities can exchange the keys without the knowledge of eavesdropper.
As of now we have secured the message as well as the key from unauthorized entity, but anyone
can alter the encrypted data passing via insecure network. To address this risk MD5 hashing
algorithm has been used using which we can analyze whether the message has been altered. Adding
to that used is allowed to select which algorithm user want to encrypt his/her data. To make this
happen AES and DES algorithm are made available.
9
Chapter 2 - Cryptography
2.1.1 Background of cryptography.
Cryptography is one of the oldest fields of technical study having history of more than 4000 Years. (Cohen,
1990-1995)With the advancement of technology in the 21st
century, the need for secured communication
has become vital in order to secure the data while channelizing between two entities. Though the idea of
cryptography has been existed since ages specially to hide the data from enemies in wars and used by
Julius ceaser which was termed as mono-alphabetic substitution ciphers .The idea of cryptography in the
world of internet has seen exponential growth since last several decades when people started using
Internet for transmission of crucial credit card ,debit card details, personal information in all walks of life
in everyday life .Cryptography across the internet is basically applying complex computational
mathematics and logic to adhere to the protocols and server its basic purpose. The key factors which
determine elegant cryptographic implementation are Data confidentiality,Integrity,Availibility,non-
repudiation,authorization.While all the multinationals organizations with billion plus dollars in revenues
containing the information of billion people cryptography becomes vital.
2.1.2 Cryptography
Cryptography is art of science which deals with secret writing of data. It involves method of secret writing
where plane text is converted to encrypted text using cipher and is termed as Encryption. Reverse process
of data where cipher text is converted to plain text is termed as decryption. It should be hard to recover
the messages from the ciphertext when the messages are drawn from arbitrary probability distributions
defined on the set of all strings (i.e arbitrary message spaces). (Shafi Goldwasser, July 2008)
10
Figure 1.Encryption and Decryption of Cryptography.
2.1.3 The four building blocks of efficient cryptography are
1. Confidentiality – Its service which states that no one should be able to read the data except the intended
entity.
2. Integrity – Data sent from sender shouldn’t be modified or hampered while its been received at the
receiver side.
3. Authentication – Data should be authenticated where receiver is assured of sender’s identity.
4. Non-repudiation – Its protocol where sender cannot deny of the fact later of not sending the data and
receiver cannot deny of the fact of not receiving the data. Proof of origin and proof of reception is taken
care of.
2.2.1 Vulnerabilities and Exploits.
Any flaw in the application, code or software is termed as vulnerability and usage of vulnerability by the
attacker in order to perform illegitimate actions is coined as Exploits.
2.2.2 Common Vulnerabilities.
2.2.2.1. Injection Flaws – Happens when unfiltered data is injected to Sql server, browser or the LDAP
Server .The problem is attacker can inject the command henceforth malicious content once he has
access resulting in loss of data and controlling client’s browsers. (wichers, 2013)
11
Prevention – By filtering and verifying all the data which is been received without giving room for any
input to enter henceforth inject the malicious execution.
2.2.2.2.Broken authentication – When the authentication is broken ,the url might contain the session Id
and leak it in the reference header to others, the password might not be encrypted either in storage or
transit, session id’s might be predictable ,session hijacking when timeouts not implemented right or using
HTTP. (wichers, 2013)
Prevention – By using framework and educating oneself on what pitfalls are.
2.2.2.3.Cross site scripting – This happens because of widespread input sanitization failure where
attacker give tags to web application java script and when its being executed when input is returned to
user unsanitized. Which will further paves path by giving information about cookies to the attacker.
Prevention – By preventing Html tags not to return to the client. (wichers, 2013)
2.2.2.4. Insecure direct object reference – This happens by trusting user input and paying the price in
resulting security vulnerability. Direct object reference means when internal object such as file or data
base key is exposed to the user and attacker can provide reference and if authorization is not enforced
attacker can access or do things that they should be precluded from. (wichers, 2013)
Prevention – By performing user authorization properly and consistently therefore whitelisting the
choices.
2.3 Common attacks.
2.3.1 Brute force attack – Brute force attack is trial and error method used to obtain information
such as user password or personal identification number. It executes by trying out all the combinations of
password inorder to crack. It is also used by security analyst to check the organizational network security.
Prevention.
1. By using strong passwords.
2. with the help of access control while logging in.
12
3. by locking out the users who exceeds the maximum login attempts.
2.3.2 Dictionary attacks – It is method of breaking into password protected system logically by
entering all the possible combination of all the words in dictionary as a password. These dictionaries
include a diverse collection of usernames and passwords and may simply represent a conglomeration of
smaller dictionaries. The root account and various system accounts are well represented, with passwords
of varying types including common English words, proper names, keyboard patterns, and “leets,” which
replace letters with numbers or symbols that resemble the replaced letter. (matthews, 2007) It can also
be used to find the key which Is used for encryption and decryption. Often used by spammers, message
is sent to email address consisting of words and phrases followed by @symbol.
Prevention.
Can be reduced to near zero by limiting the number of attempts allowed within given amount of time and
by wisely choosing the password key. For illustration, only three attempts are allowed then gap of 15
minutes before attempting for the fourth time
2.3.3 Denial of service attack – Prevent the service being used by others by overloading
resources. When multiple host attack simultaneously is DDOS attack. It is executed by sending fake
requests to web server henceforth by increasing the load on the server. DoS attacks in the Internet
generally conquer the target by exhausting its resources that can be anything related to network
computing and service performance, such as link bandwidth, TCP connection buffers, application/service
buffer, CPU cycles, etc. (Qijun Gu) Individual attackers can also exploit vulnerability, break into target
servers, and then bring down services. Hackers have been carrying out the Denial of service attack from
decade starting from 500 MB in 2002 to 10+ GB by 2015.Flash crowd is generic term used to phrase the
huge traffic on webservers.
13
Figure 2.Denial of service attacks.
2.2.3.1 Aims of DDOS attacks.
Consuming bandwidths with large traffic volumes, Overload or crash the network handling service,
sending specific type of packets in order to consume targeted available resources.
2.2.3.2 Prevention of Dos attacks.
Attack prevention and preemption before the attack, detection and filtering during the attack, source
trace back and identification after the attack. Multiple firewalls will enable to stop the flooding attacks,
Switches provide system wide rating, traffic shaping, delayed binding to detect and remediate denial of
service attacks. By adding rules to take out flow statistics during Dos attacks they further slowdown and
complicate the attack.
14
Chapter 3
Security algorithms and key exchange.
3.1 Deffiei-hellman
First public-key type scheme proposed by Diffie & Hellman in 1976 along with the exposition of public key
concepts. (stallings) In secure message exchange system usage of encryption algorithm is quite
common which leads to data security over an unsecure network. The multiple parties participating
in information exchange has to exchange their encryption/decryption key with each other so that
the data encrypted by one can be decrypted by the authorized party. During the key exchange, an
eavesdropper (passive attack) can capture the key that is being exchanged between the authorized
parties and decrypt the information. To address this vulnerability we require a secure way for key
exchange. Deffiei-hellman algorithm provide a secure method of key exchange where the users
involved in the conversation can exchange their keys in the presence of attacker. Both the parties
agree on a common key which is used to encrypt the public key. Let’s analyze how the authorized
parties agree on same key without revealing it over the unsecured network.
Let’s start with the general example for the sake understanding, consider Alice and Bob, two
parties who are willing to agree on a key.
15
Figure 3.Diffie Hellman key exchange.
 Bob and Alice agrees on one common paint (C) which an attacked can know about.
 Bob and Alice pick one secrete color of paint, B and A respectively, which they don’t share
with each other.
 Both the parties will mix their secrete paint with the common paint they agreed on. Now
Alice have AC and Bob have BC as mixed color.
 Now both the parties exchange their mix paint with each other. Alice has BC and A, Bob
has AC and B.
 Both the parties will mix their secrete color with the mixed color received from the other
party. So, Alice got ABC and Bob got ABC.
 Now both the authorized partied have same color.
 The eavesdropper cannot learn the common paint both the authorized parties agreed on as
he/she don’t know the secrete color that has been mixed with the common color.
Now let’s analyze how we can represent this method mathematically so that we can use it in real
time.
16
Figure 4.Mathematical computation of Diffie hellman
 Alice and Bob agree on one prime number P and one generator G in plain text such that
P>G and G is primitive root of P.
P=11 and G=7.
 Now Alice and Bob generate one random secrete number each.
Alice’s Secrete number XA=6.
Bob’s secrete number XB=9.
 Both parties use the formula Y = GX
mod P.
Alice: Ya = GXa
mod P
YA = 76
mod 11 = 4.
Bob: YB = GXb
mod P
YB = 79
mod 11 = 8.
 Now Alice and Bob exchange YA and YB with each other with is in plain text.
 Now both the parties can use their secrete integer and the integer received from each other.
Required Secrete number, SK = YX
mod P.
Alice: SK = (YB)XA
mod P.
SK = 86
mod 11 = 3
Bob: SK = (YA)XB
mod P.
17
SK = 49
mod 11 = 3
 Now, Both Alice and Bob got same Secrete Key which they can use to encrypt/decrypt the
key required to encrypt/decrypt the actual information.
Clearly, much larger values of a, b, and p are required. An eavesdropper cannot discover this
value even if she knows p and g and can obtain each of the messages. Suppose p is a prime of
around 300 digits, and XA and XB at least 100 digits each. Discovering the shared secret key would
take longer than the lifetime of the universe, using the best known algorithm. This is called the
discrete logarithm problem.
3.2.RSA
RSA algorithm was invented in 1977 by three scientists, namely, Ron Rivest, Adi Shamir and Len
Adleman. RSA is asymmetric encryption algorithm where two keys are generated, namely, public
key and private key. (scarvalone, 2009) The encryption of required plain text is done using public
key and the cypher text can be converted back to plain text using private key. Both the keys are
inversely proportional to each other. RSA can be used both for encryption and digital signatures.
RSA serves many protocols like SSH, SSL/TLS, S/MIME and OpenPGP. RSA derives its keys by
multiplying two large prime numbers, Rabin-Miller primality test algorithm is used to generate
prime numbers for RSA. Determining the prime numbers used from the product is extremely
difficult and time consuming even using super computers. The strength of encryption depends on
the length of public key. The keys are typically 1024 to 2048 bits long. Previously keys of length
1024 were used but as the technology developing at a rapid rate we can expect the key to be broken
at any time in near future. So the industries are switching towards keys with the length 2048 bits.
18
Figure 5.RSA Encryption and Decryption.
The party willing to receive encrypted information from authorized source will generate two keys,
namely, public key and private key. Both the keys are inversely proportional to each other. The
public key is sent to the authorized source over the unsecured using deffiei-hellman algorithm and
the privet key is kept secrete. Whenever the source want to send the information to destination, it
uses the public key of destination to encrypt the information using the formula provided by the
RSA algorithm. The genuine destination can decrypt the cyphertext using the unshared private
key.
Lets see how RSA encryption algorithm works,
Algorithm:
 Generation of two prime numbers:
Consider p and q as two prime number, compute n=pq.
 Calculate φ(n)
φ(n)=(p-1)(q-1)
 We need an exponent e, provided
It is an integer
Not be factor of n
1 < e < φ(n)
 The public key is made up of two numbers that is e and n.
 The private key is computed by the following steps
Private key, d =( 2(φ(n))+1 ) / e
19
 Encryption of information m can be done using the following formula,
c= me
mod n.
 Decryption of the cyphertext c can be decrypted by private key d using the following
formula,
m= cd
mod n.
Example:
 Generation of two prime number p and q, and n.
Consider p=53 and q=59
Compute n=pq i.e. n= 53*59 = 3127
 φ(n)= (p-1)(q-1) = (53-1)(59-1) = 3016
 Consider e = 3
 Public key is (n,e)
Public key = (3127,3)
 Private key,
d= ( 2(φ(n)) + 1 ) / e
d= ( 2(3016) + 1 ) / 3
d=2011
 Now we can encrypt the information using the public key (n,e) that is (3127,3)
Lets consider the information as m=89, so the encrypted information c is,
c= 893
mod 3127 = 1394
 The cypher text c= 1394 can be decrypted using the private key,
 m= cd
mod n = 13942011
mod 1327 = 89
3.3 DES (Data Encryption Standard) algorithm
DES is symmetric key algorithm used to encrypt/decrypt the information that has to secured from
unauthorized entity over the unsafe network. DES was developed at IBM in early 1970s based on
the design of Horst Feistel. In those days the algorithm is considered as one of the strongest
20
encryption algorithm and selected by National Bureau of Standards as an official FIPS (Federal
Information Processing Standard) of United States in 1977. DES uses 56bit key and can encrypt
64bits of plain text at a time. (Daley, 1999)
Figure 6.DES algorithm
DES algorithm uses its 56bit key to encrypt the given plain text into 64bit enciphered blocks by
means of permutation and substitutions. The process takes place in 16 rounds. Each plain text can
be encrypted individually or making the present block of information dependent on the previous
blocks. Decryption is reverse process of encryption. The same 64 bit key used in encryption is
applied to the cipher while performing decryption.
21
3.4 AES (Advanced Encryption Standard)
AES encryption algorithm is extended version of DES encryption algorithm. AES is a block
cipher. This means that the number of bytes that it encrypts is fixed. AES has 3 ciphers AES-128,
AES-192 and AES-256. The plain text of block size 128bits can be encrypted/decrypted using any
of the 126, 192 and 256 bit keys. AES uses same key for encryption as well as decryption. So the
source and destination must know the secrete key that has been used. The level of security depends
on the key length. (Federal information processing standards publications., November 26,2001)
The higher the key length, higher the security level. Depending on the key length the encryption
rounds increases. There are 10, 12, and 14 rounds of encryption is performed for the key length
128, 192 and 256 bit respectively.
Figure 7.AES Input.
Each round will consist of four processes, namely, SubByte, ShiftRows, MixColumns and
AddRoundKey. Internally the AES algorithm’s operations are performed on 2 dimension array of
bytes called states. AES algorithm process the data in Hexadecimal units.
22
3.5 MD5 (Message Digest 5)
MD5 is hashing algorithm used maintain integrity designed by Ron Rivest in 1991. MD5 is one
way encryption where it is extremely difficult to generate plain text from the cipher text. It can be
used for digital fingerprints and secure password storage. (Kozushko, 11/28/2003)
MD5 algorithm consists of 5 steps
Step 1: The original message is padded with required amount to bits to make the size of the data
block congruent to 448 modulo 512. We must follow the following rules while padding the
required amount of bits to the original message. The rules are as follows,
 Firstly, the message is padded with the bit 1.
 To bring the message length to 64 bits fewer than a multiple of 512 we should add required
amount of 0s following 1.
Step 2: Append length. A 64bit representation of the actual message is appended to the result of
previous step. The output of this step has a length that is an multiple of 512 bits.
Step 3: Now initialize the Message Digest buffer. The buffer is divided into 4 parts, namely A, B,
C and D, each of 32bit length. Word A, B, C and D are initialized to the initial value 0x67452301,
0xEFCDAB89, 0x98BADCFE, 0x10325476 respectively.
Step 4: Process message in 16 word block i.e., 512 bit block. In this step we append the message
in blocks of 512 bits each. For each input block, 4 rounds of operations are performed with 16
operations in each round.
Step 5: This is the last step used to output the content of the four words i.e. A, B, C and D. The
output will be in low order byte first sequence.
23
Chapter 4 - Android and chat application
4.1 History of Android.
Android took birth on November 2007 and November 5 has been regarded as birthday of Android
(spaight) and down the line 8 years it has been one of the most successful and powerful mobile operating
systems in the history of smartphones with more than billion users and billion plus android open source
applications in the android store. Android is currently under development by Google and Open handset
alliance since its first release.
4.2 Below are the different android versions and most of them are
named after desserts.
Figure 8.Various flavours of Android.
1. Cupcake 1.5
2. Donut 1.6
3. Éclair 2.0 - 2.1
4. Froyo 2.2- 2.3
24
5. Gingerbird 2.3 – 2.3.7
6. Honeycomb 3.0 – 3.2.
7. Ice cream sandwich 4.0
8. Jellybean 4.1 – 4.3
9. Kitkat 4.4
10.Lollipop 5.0 – 5.1
11.Marshmallow
4.3 The different tools which android as operating system support for
the smartphones are
1. Gmail synchronization with application.
2. Contacts in line with people application.
3. Google maps and street view to find the different directions on various demographic locations using
GPS.
4. Voice speech recognition on Google talk.
5. Instant messaging, text messaging, Multimedia messaging, calculator, business applications, social
media applications like Facebook, Instagram, twitter, quora, viber. (DHT Technologies.)
6. Media player which runs the audio and visual files both in the background and at the user interface.
7. Search option where people can put the query to obtain any information over the internet.
8. Different notifications which arrive at the status bar with regards to setting the alarm, brightness of the
phone, email notifications, Instant messaging notifications.
9. Voice recognition dialer which enables user to dial the contact number without using manual input.
10. Wallpaper which accounts for the different images including personal ones on the background for
marvelous ambient approach.
25
11. wi-fi and Bluetooth connections.
12. Video watching software’s such as YouTube.
13. Support for third party text prediction and dictionary for user usage.
14. Auto rotation of the screen.
15. Setting up the pictures for the contact list.
16. USB tethering and hotspot functionality where users can create own network and add different
devices to it.
17. Picture and video uploads on social networking sites.
18. Support for near field communication.
19. Power management which enables user to identify the applications which are consuming more power
and can halt them when they are not being actively used 24-7 thus improvising the battery life.
20. Video calling support using applications such as Skype to connect users from different parts of the
globe.
21. Holographic interface.
22. Multitasking where user can access different applications with one touch.
23. Encrypts all the user data using security protocols.
24. Connectivity for USB applications.
25. Provides excellent UI for gaming applications.
26. Adding additional storage on SD card where user can store huge bulk of data.
27. Able to excess Microsoft office thus making it more reliable for connectivity.
28. Keypad is available in multiple languages and user has the ease to select one of his choice.
29. Switching on to airplane mode when travelling beyond the earth’s atmosphere.
30. Facial recognition where device is unlocked once the pattern is matched.
31. Photo gallery is viewed in multiple outlooks for user experience.
26
32. Can be supportable upto 64 bit processors.
33. Multiple login accounts for the email account as in single mail application can be used by more than
one user.
34. Flashlight drawn from the camera application can also be used as torch.
4.4 Requirements for android on Hardware level.
From the rediscovery of operating systems from android version 1.6 to android 5.0 the vital hardware
requirement is ARM architecture which also includes microprocessor without interlocked pipeline stages
which is reduced instruction set computer which varies from MIPS 1 to MIPS 6 and also x86 processors.
The minimum Ram requirements for the efficient execution of operating system has been varied over
time which started with minimum 32 MB RAM,32MB flash memory and 200 MHZ ARM architecture and
now has been extended up to 4 Gb OF RAM manifested by Qualcom,mediatek 230 MB flash memory 1
GHZ ARM architecture. (Wikipedia ,Free Encyclopedia., 2015)
4.5 Android for chat application
The best part of android chat application are they enable to send/receive the text,image,video between
two users across the globe without spending penny on telecommunication network. Provided the little
data charges which user has to account while using it.They are becoming increasingly popular in never
seen before rate in last several years due to the ease, reliability, productivity and user addiction over the
smartphone.
Whatsapp, Viber, Skype, Line, Wechat,facebook messenger are the frontiers in this field considering other
thousands of applications which make the demand get executed.
4.5.1 Whats app – Whats app as company started by former yahoo employee Brian Acton and Jan
korum in 2009 which works on subscription model consisting just over 50 Employees was acquired by
Facebook for whopping 19 billion US dollars which now has around 900 active users in the world. This is
the best example why instant messaging application is such at apex boom in the market of Information
27
technology. Easy setup, automatic synchronization with phone contacts,ad free experience ,automatic
synchronization with phone contacts makes the whats app best in the business which charges 0. 99USD
every year after free subscription for the first year.
Figure 9.Growth of messaging application whats app
4.5.2 Viber- The basic functionality of viber includes instant messaging, Pic sharing with added
emotions and sticker sharing. What makes viber one of the leading application in android store is its ability
to call to anyone on their phone without carrier charges for the telecommunication network which varies
with the location you are dialing with automatic synchronization of contacts and also letting to know
about the people who use Viber on their contact list. Viber is hassle free of pin input when user logs into
the app and uses telephone number as the input.
28
4.5.3 Send –Microsofts send is one of the other instant messaging app which stands out in with feature
of beginning instant messaging application on the email without the need for user to login in to Email
account everytime.Its highly recommended for the official trans/receive of information as its makes it
more quick, handy and saves lot of time user puts in during email communication.
Figure 10.Microsoft line
4.5.4 Blackberry Messenger –Thought Blackberry messenger was proprietary based application
which was restricted to black berry users which enables user to send/receive texts, images, videos,
location sharing, automatic voice recognition until it was released in 2013 on android store and IOS.A pin
system allows user to share BBM contacts without having to share phone or email details while the 2 way
opts in for communication allows user to control the text which are being received to the inbox.
4.5.5 Facebook Messenger – Facebook messenger is brought up by Social networking giant
Facebook. Where user contact list is automatically synchronized by the connections he/she has in their
friend list. Application enables to send/receive text, images, voice, Emotions, stickers, URL’s, files, folders
29
Figure 11.Security implementation in instant messaging.
etc. It’s quite handy when compared to other applications is of the fact that there is chat pop up on the
front end of the screen of the smartphone which user can use even when other applications are being
used. Facebook has introduced dialing facilities on the chat application where user can other people in
their friend list and even can do video chat. User can block the other persons profile when he/she doesn’t
want to receive any text/image/video/files from the users as sometimes malicious contents/spam are
being sent by unknown entities over the internet.
4.5.6 Skype – Besides being known for the video calling and send/receive of the short video
functionality ,skype does has strong instant messaging facilities in its application. With the help of skype
credits users can call to any part of the world to the people who are in there contact list. Though the vb
instant messaging facility isn’t that popular in day – day lives of the users but skype does provide ease and
reliability for the users to communicate
Chapter5.0 - Application framework and outlook
The proposed application is designed to send and receive encrypted text messages and
decrypt at the receiver side.
5.1 The following show the architecture of security implementation in
secure messaging.
Insecure Network
Sender/receiver Sender/receiver
Messaging Messaging
Send/Receive Cypher text
30
5.2 User Interface Description
Application is designed using Android 4.0 using eclipse IDE, This application uses multiple
encryption and decryption algorithms to ensure secured message exchange.
1. The application starts with welcome screen which is as follows
5
2. Application consists of two types of texting options, one is plain texting, and another is
secure texting. As soon as the application opens we find the above figure and it takes us to
select the type of messaging activity whether secure texting or simple texting. The screen
is as follows
Figure 12.Welcome screen of
application.
31
Figure 13.Option to choose between simple and secure texting.
32
3. If we select Simple texting we can make simple messages where there is no security for
outgoing messages Its just like normal messages. The following is the screen to show the
simple messages.
Figure 14.Choosing the number from the contact list to send the message.
33
4. If we select Secure Texting we can make secure messages where we are encrypting the
outgoint messages which different kinds of algorithms available in android. Namely AES,
DES, RSA
Figure 15.Encryption before sending.
34
5. And the main screen is having one more option called Decrypt Inbox messages which helps
you to decrypt the message which are already received in inbox.
Figure 16.Decryption of Message at the receiver side.
35
Figure 17.Use case diagram.
5.3 Use Case Diagram
Select Contact
Generate Random Number
Hash Random numbers
Generate Key with Hash Data
Use As Key for Selected Algo
Send Message
Select Algorithm
Sender
Receiver
36
5.4 Data flow diagram
Sender/
Reciever
Select Type
Simple
Secured
Simple TextSecured Text
Select Contact
Select Algorithm
Send Message
Select Contact
Send Message
37
Chapter 6.
Application design and architecture.
6.0 Integration of JAVA and CRYPTOGRAPHY
The chat application is built on JAVA platform as it strongly emphasize on security. Cryptography
is integrated with Java to achieve secure communication. Java application can be developed using
either of the below library:
 JCA and JCE APIs (Application programming interface).
JCA and JCE are the two main APIs which helps in Cryptographic operations(Oracle 2011).
By using these APIs Java provides the cryptographic functionality.
 Java Cryptography Architecture (JCA)
- It is a security framework which is integrated with the core JAVA API
 Java Cryptography Extension (JCE)
- This is the extension of JCA for strong encryption.
38
6.1 JCA Architecture
Figure 18: JCA Architecture
 JCA/JCE provides the functionalities of various cryptographic services.
 Cryptographic implementation is actually provided by service providers.
 JCA/JCE is structured with “Engine” classes and these classes provide a standard interface
into the cryptographic service provides.
JCA provides two provider classes:
 Provider (Cryptographic Service Provider): It has methods which are used to get
information about provider’s name and version number.
 Security: It manages the installed service providers and security properties. Basically used
to add, remove or modify providers.
39
6.2 JCE
 It provides many functions which JCA doesn’t provide such as encryption/decryption and
symmetric key generation.
 It uses the provider class of JCA.
6.3 Engine Classes
They actually provide an interface for every specific cryptographic operation such as Digital
signature, Encryption, Message Digest etc.
Cryptographic operations are categorized into classes in JCA/JCE. These classes are named as
engines.
 JCA Engines/Classes
 JCE Engines/Classes
6.3.1 JCA Engines
 MessageDigest: Produces hash value(MD5,SHA)
 Signature: Produces digital signatures
– KeyPairGenerator: Produces pairs of keys
 KeyFactory: breaks down a key
 KeyStore: Manages and stores keys
 SecureRandom: Produces random/pseudo-random numbers
– AlgorithmParameters: Maintains the security parameters for specific algorithms
– AlgorithmParameterGenerator: Creates parameters
 CertificateFactory: Generate certificates and revocation
 CertPathBuilder: Establishs relationship chains between certificates
 CertStore: It stores certificates and revocation.
40
6.3.2 JCA Engines
 Cipher: Encryption and Decryption
 KeyGenerator: Produces secret keys used by ciphers for encryption/decrypton.
 SecretKeyFactory: Operates on Secret Key objects
 KeyAgreement: Key agreement protocol
 MAC: Provides Message authentication code functionality
6.3.2.1 JCA/JCE Engine location:
JCA Engine: Located in java.security package
JCE Engine: Located in javax.crypto package
Example Codes(Oracle 2011):
1. Generating the key:
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecretKey aesKey = keygen.generateKey();
2. To generate the cipher object from the key generated above:
Cipher aesCipher;
// Create the cipher
aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
We use the generated aesKey from above to initialize the Cipher object for encryption:
// Initialize the cipher for encryption
aesCipher.init(Cipher.ENCRYPT_MODE, aesKey);
// Our cleartext
byte[] cleartext = "This is just an example".getBytes();
// Encrypt the cleartext
byte[] ciphertext = aesCipher.doFinal(cleartext);
// Initialize the same cipher for decryption
41
aesCipher.init(Cipher.DECRYPT_MODE, aesKey);
// Decrypt the ciphertext
byte[] cleartext1 = aesCipher.doFinal(ciphertext);
Plaintext Input:
Hello, Welcome to the world of Encryption and Decryption
Cipher Text Output:
07f7d720f351119ed651836585e40dea0d873f08223cf3f5fd1c81fbe42986eb1b1100b7133f75b2f
83800013dbd6bdb6d300497f605713540fe6003f53d7594
6.4 Security protocol
Here in the proposed system we designed a secure protocol to send text messages which can not
be broken by any hackers in the network the protocol is as follows
Here the protocol works at both the Sender and the Reciever
Step 1:
First the plain text is encrypted with RSA algorithm we are using big integer algorithm to
encrypt the message then encrypted message is taken out.
Step 2:
We are creating a 16 digit random numbers and random number will be hashed using secure
md5 hash algorithm
Step 3:
The RSA encrypted data is again encrypted with DES algorithm using hash data as a secure
key.
Step 4:
Here again DES encrypted data will be taken out and again encryped with AES algorithm
and the key is hash data. Then
42
Step 5:
Final Encrypted data is sent to the receiver and receiver side the algorithm information is
obtained using key term which is sent in the message along with secured data then using the key
term the application understand the type of algorithms used in the encryption based on the type of
key term decryption will be stated for the incoming message on demand and then final plain text
will be given to receiver.
Chapter 7.0
Implementation of Security:
The application works on several cryptographic functionalities using the supported types of
cryptography from android we designed a secure protocol to send and receive text messages.
7.1 RSA Algorithm:
public RSAHelper(int bits) {
bitlen = bits;
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bitlen / 2, 100, r);
BigInteger q = new BigInteger(bitlen / 2, 100, r);
n = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q
.subtract(BigInteger.ONE));
e = new BigInteger("3");
while (m.gcd(e).intValue() > 1) {
e = e.add(new BigInteger("2"));
}
d = e.modInverse(m);
}
/** Encrypt the given plaintext message. */
43
public synchronized String encrypt(String message) {
return (new BigInteger(message.getBytes())).modPow(e, n).toString();
}
/** Encrypt the given plaintext message. */
public synchronized BigInteger encrypt(BigInteger message) {
return message.modPow(e, n);
}
/** Decrypt the given ciphertext message. */
public synchronized String decrypt(String message) {
return new String((new BigInteger(message)).modPow(d, n).toByteArray());
}
/** Decrypt the given ciphertext message. */
public synchronized BigInteger decrypt(BigInteger message) {
return message.modPow(d, n);
}
/** Generate a new public and private key set. */
public synchronized void generateKeys() {
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bitlen / 2, 100, r);
BigInteger q = new BigInteger(bitlen / 2, 100, r);
n = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q
.subtract(BigInteger.ONE));
e = new BigInteger("3");
while (m.gcd(e).intValue() > 1) {
e = e.add(new BigInteger("2"));
}
44
d = e.modInverse(m);
}
/** Return the modulus. */
public synchronized BigInteger getN() {
return n;
}
/** Return the public key. */
public synchronized BigInteger getE() {
return e;
}
7.2 DES Algorithm:
public class DESHelper {
public static String encrypt(String seed, String cleartext)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
45
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("DES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(seed);
kgen.init(64, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
46
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
47
7.3 AES Algorithm:
public class AESHelper {
public static String encrypt(String seed, String cleartext)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
48
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
49
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
7.4 Secure MD5 Hashing:
public class PasswordHash {
public String hashPassword(String password){
String passwordToHash = password;
String generatedPassword = null;
try {
// Create MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance("MD5");
//Add password bytes to digest
md.update(passwordToHash.getBytes());
//Get the hash's bytes
byte[] bytes = md.digest();
50
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 32).substring(1));
}
//Get complete hashed password in hex format
generatedPassword = sb.toString();
System.out.println(generatedPassword);
return generatedPassword;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return null;
}
}
}
51
Chapter 8.0 Testing and result
The aim of the project is to develop an application which can send encrypted message to the
receiver from the android device since android devices or any mobile the text messages are having
limitations in the size around 160 characters per message so because of that reason the security
protocol will not be working with big text messages but still we have implemented to show the
application is more in need for the todays software world due the heavy growth of hackers in the
network and this application can be enhanced to send big text messages in the future.
52
References
Cohen, F. (1990-1995). Specialising in Information protection since 1977. Fred chohen and assosiates.
Daley, W. (1999). Data encryption standard. Gaithersburg.: U.S department of Commerce.
DHT Technologies. (n.d.). www.dhtusa.com. Retrieved from
http://www.dhtusa.com/media/AndroidInternals.pdf:
http://www.dhtusa.com/media/AndroidInternals.pdf
Federal information processing standards publications. (November 26,2001). Advanced Encryption
standard. National institute of standards and Technology.
Kozushko, H. (11/28/2003). MD5 Algoritham.
matthews, J. o. (2007). A study of passwords and Methods used in Brute force SSH attacks. New York :
Department of computer science , Clarkson University.
Qijun Gu, P. L. (n.d.). Denial of service attacks. Texas.: Department of computer science , Texas state
university.
scarvalone, M. (2009). RSA Encryption and DIffie Hellman key exchange. RSA Encryption .
Shafi Goldwasser, M. B. (July 2008). Lecture notes on cryptography. Cryptography, 14.
spaight, J. (n.d.). Google android operating system.
stallings, W. (n.d.). Cryptography and Network security.
Tom. (2015). Toms guide. Retrieved from www.tomsguide.com: http://www.tomsguide.com/us/pictures-
story/654-best-messaging-apps.html
wichers, D. (2013). OWASP Top 10 . Creative Commons attribution share.
Bishop, M. (2003) “What is computer security?,” Security & Privacy, IEEE, 1(1), 67–69.
Bishop, M. (2004) Introduction to Computer Security, Addison-Wesley Professional.
53
Choo, K.-K.R., service), S. (Online (2009) Secure Key Establishment [online], Springer Science+Business
Media, LLC: Boston, MA, available:
http://ul.summon.serialssolutions.com/2.0.0/link/0/eLvHCXMwY2AwNtIz0EUrE1IM0yyNU0zNjV
ITzY2NLJOSgRwTw2RLYAVibmIA3m6BuOIYqYB3E2JgSs0TZZBwcw1x9tAtzYmHjmrEm1qC
Dp8zFGPgTQQtBc8rAW8ZS5FgUDC3TDRKMTKzsEiySDRJTTW2SDNKMgel7KS0NIPUZGM
AOxwoaw.
Coffey, T., Saidha, P. (1996) “Non-repudiation with mandatory proof of receipt,” ACM SIGCOMM
Computer Communication Review, 26(1), 6–17, available:
http://portal.acm.org/citation.cfm?doid=232335.232338.
Diffie, W., Hellman, M.E. (1979) “Privacy and authentication: An introduction to cryptography,”
Proceedings of the IEEE.
Eskicioglu, A.M., Litwin, L. (2001) “Cryptography,” Potentials, IEEE.
Ganesan, P., Venugopalan, R., Peddabachagari, P., Dean, A., Mueller, F., Sichitiu, M. (2003) “Analyzing
and modeling encryption overhead for sensor network nodes,” Proceedings of the 2nd ACM
international conference on Wireless sensor networks and applications - WSNA ’03, 151, available:
http://portal.acm.org/citation.cfm?doid=941350.941372.
Ganley, M. (2006) “Introduction – Cryptography,” Information Security Technical Report, 11(2), 67,
available: http://www.sciencedirect.com/science/article/pii/S1363412706000227 [accessed 23 Aug
2014].
GitHub, I. (2014a) Multiparty Protocol Specification [online], available:
https://github.com/cryptocat/cryptocat/wiki/Multiparty-Protocol-Specification.
GitHub, I. (2014b) Design and Functionality [online], available:
https://github.com/cryptocat/cryptocat/wiki/Design-and-Functionality.
54
Appendix
AESHelper.java
package com.proj.myapp;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESHelper {
public static String encrypt(String seed, String cleartext)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
}
public static String decrypt(String seed, String encrypted)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
55
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
56
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}
DESHelper.Java
package com.proj.myapp;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class DESHelper {
public static String encrypt(String seed, String cleartext)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] result = encrypt(rawKey, cleartext.getBytes());
return toHex(result);
57
}
public static String decrypt(String seed, String encrypted)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
byte[] result = decrypt(rawKey, enc);
return new String(result);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("DES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
sr.setSeed(seed);
kgen.init(64, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
private static byte[] decrypt(byte[] raw, byte[] encrypted)
throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static String toHex(String txt) {
58
return toHex(txt.getBytes());
}
public static String fromHex(String hex) {
return new String(toByte(hex));
}
public static byte[] toByte(String hexString) {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
public static String toHex(byte[] buf) {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
private final static String HEX = "0123456789ABCDEF";
private static void appendHex(StringBuffer sb, byte b) {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}
59
Encryptmessage.java
package com.proj.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class EncryptMessage extends Activity{
EditText edtEncryptedata;
TextView txtDecrypteShow;
Button btnDecrypte;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.encryptmessage);
edtEncryptedata = (EditText) findViewById(R.id.edtencryptedata);
txtDecrypteShow = (TextView) findViewById(R.id.txtDecrypteShow);
btnDecrypte = (Button) findViewById(R.id.btn_decryptedata);
btnDecrypte.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
if (!edtEncryptedata.getText().toString().equals("")) {
String msg =edtEncryptedata.getText().toString();
60
try {
String strMessage = AESHelper.decrypt("BREAK", msg);
txtDecrypteShow.setText(strMessage);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
Toast.makeText(EncryptMessage.this, "Not an encrypte
text", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(EncryptMessage.this, "Please enter encrypte
text", Toast.LENGTH_LONG).show();
}
}
});
}
}
61
Mainactivity.Java
ackage com.proj.myapp;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.telephony.gsm.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
@SuppressWarnings("deprecation")
public class MainActivity extends Activity implements OnClickListener {
String algo[];
EditText etEnterNumber, etTextMsg;
Button btnSend, btnDecrypt, btnSelectcontact;
String plainText, cipherText, strPhoneNum;
private static final int PICK_CONTACT = 11;
Spinner spinner1;
62
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etEnterNumber = (EditText) findViewById(R.id.etEnterNumber);
etTextMsg = (EditText) findViewById(R.id.etTextMsg);
btnSend = (Button) findViewById(R.id.btnSend);
btnDecrypt = (Button) findViewById(R.id.btnDecrypt);
btnSelectcontact = (Button) findViewById(R.id.btn_selectcontact);
spinner1 = (Spinner) findViewById(R.id.spinner1);
algo = getResources().getStringArray(R.array.alog);
ArrayAdapter<String> algoAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, algo);
spinner1.setAdapter(algoAdapter);
btnSend.setOnClickListener(this);
btnDecrypt.setOnClickListener(this);
btnSelectcontact.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.btnSend:
plainText = etTextMsg.getText().toString();
strPhoneNum = etEnterNumber.getText().toString();
if (!plainText.equalsIgnoreCase("") &&
!strPhoneNum.equalsIgnoreCase("")) {
try {
63
cipherText = AESHelper.encrypt("BREAK", plainText);
sendSMS(strPhoneNum, cipherText);
Log.d("", cipherText);
} catch (Exception e) {
e.printStackTrace();
sendSMS(strPhoneNum, plainText);
}
} else {
Toast.makeText(getApplicationContext(),
"Please fill all the fields", Toast.LENGTH_LONG)
.show();
}
break;
case R.id.btnDecrypt:
Intent intent1 = new Intent(MainActivity.this, EncryptMessage.class);
startActivity(intent1);
break;
case R.id.btn_selectcontact:
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
break;
}
}
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(getApplicationContext(),
"Message sent", Toast.LENGTH_LONG)
.show();
}
@Override
64
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_CONTACT:
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
try {
Cursor cursor = getContentResolver().query(contactData,
null, null, null, null);
if (cursor.moveToFirst()) {
String id = cursor
.getString(cursor
.getColumnIndexOrThrow(ContactsContra
ct.Contacts._ID));
String hasPhone = cursor
.getString(cursor
.getColumnIndex(ContactsContract.Cont
acts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver()
.query(ContactsContract.CommonDataKinds.P
hone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.
Phone.CONTACT_ID
+ " = " + id, null, null);
phones.moveToFirst();
String cNumber = phones.getString(phones
.getColumnIndex("data1"));
etEnterNumber.setText(cNumber);
}
}
65
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
}
RSAhelper.Java
package com.proj.myapp;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import javax.crypto.Cipher;
public class RSAHelper {
KeyPair kp;
Key publicKey = null;
Key privateKey = null;
byte[] decodedBytes = null;
byte[] encodedBytes = null;
66
RSAHelper() {
// Original text
// Generate key pair for 1024-bit RSA encryption and decryption
try {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(256);
kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
} catch (Exception e) {
}
}
public void encrypt(String text) {
// Encode the original data with RSA private key
try {
Cipher c = Cipher.getInstance("RSA");
c.init(Cipher.ENCRYPT_MODE, privateKey);
encodedBytes = c.doFinal(text.getBytes());
} catch (Exception e) {
}
// tvencoded.setText("[ENCODED]:n" +
// Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "n");
}
// Decode the encoded data with RSA public key
public String decrypt() {
try {
Cipher c = Cipher.getInstance("RSA");
c.init(Cipher.DECRYPT_MODE, publicKey);
decodedBytes = c.doFinal(encodedBytes);
return new String(decodedBytes);
} catch (Exception e) {
return null;
}
67
}
// TextView tvdecoded = (TextView)findViewById(R.id.tvdecoded);
// tvdecoded.setText("[DECODED]:n" + new String(decodedBytes) + "n");
}
Showmsg.java
package com.proj.myapp;
import java.security.Key;
import java.security.KeyPair;
import java.security.spec.X509EncodedKeySpec;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.widget.EditText;
public class ShowMsg extends Activity{
String bodytext;
EditText etrecmsg;
TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.recmsg);
etrecmsg = (EditText) findViewById(R.id.etrecmsg);
Intent intent = getIntent();
bodytext = intent.getExtras().getString("message");
68
try {
//String message = AESHelper.decrypt("BREAK", bodytext);
//etrecmsg.setText(message);
if(bodytext.contains("-")){
String[] parts = bodytext.split("-");
}
} catch (Exception e) {
e.printStackTrace();
etrecmsg.setText("Not an encrypted Message:n" + bodytext);
}
}
}
SMSreceiver
package com.proj.myapp;
import java.util.ArrayList;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
public class SmsReciever extends BroadcastReceiver {
String address;
69
String body;
// @TargetApi(Build.VERSION_CODES.DONUT)
@Override
public void onReceive(Context context, Intent intent) {
List<SmsMessage> smsMessages = getSmsMessages(intent);
for (SmsMessage smsMessage : smsMessages) {
address = smsMessage.getOriginatingAddress();
body = smsMessage.getMessageBody();
Intent intent2 = new Intent(context, ShowMsg.class);
intent2.putExtra("phone", address);
intent2.putExtra("message", body);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);
}
}
private List<SmsMessage> getSmsMessages(Intent intent) {
List<SmsMessage> smsMessages = new ArrayList<SmsMessage>();
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdus.length; i++) {
SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]);
smsMessages.add(msg);
}
}
return smsMessages;
}
}
70
Splashscreenactivity.Java
package com.proj.myapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Window;
public class SplashScreenActivity extends Activity {
private static int SPLASH_TIME_OUT = 3000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splashscreen);
if (!isTaskRoot()) {
Intent intent = getIntent();
String action = intent.getAction();
if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null
&& action.equals(Intent.ACTION_MAIN)) {
finish();
return;
}
} else {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// Create an intent that will start the main activity.
Intent intentLogin = new Intent(SplashScreenActivity.this,
MainActivity.class);
SplashScreenActivity.this.startActivity(intentLogin);
71
// Finish splash activity so user can't go back to it.
SplashScreenActivity.this.finish();
}
}, SPLASH_TIME_OUT);
}
}
@Override
public void onBackPressed() {
}
}

More Related Content

Similar to Shivkumar_koppad_14043513_EE6093_FInal Ecopy submission.

CS499_JULIUS_J_FINAL_YEAR_PROJETCT_L_DRAFT
CS499_JULIUS_J_FINAL_YEAR_PROJETCT_L_DRAFTCS499_JULIUS_J_FINAL_YEAR_PROJETCT_L_DRAFT
CS499_JULIUS_J_FINAL_YEAR_PROJETCT_L_DRAFTJosephat Julius
 
Computing Science Dissertation
Computing Science DissertationComputing Science Dissertation
Computing Science Dissertationrmc1987
 
phd_thesis_with_corrections_v1-00
phd_thesis_with_corrections_v1-00phd_thesis_with_corrections_v1-00
phd_thesis_with_corrections_v1-00Martin Emms
 
Master thesis 14023164
Master thesis 14023164Master thesis 14023164
Master thesis 14023164Thivya Devaraj
 
Essay On Tourism
Essay On TourismEssay On Tourism
Essay On TourismWanda Buck
 
Android Face Recognition App Locker
Android Face Recognition App LockerAndroid Face Recognition App Locker
Android Face Recognition App LockerAnkur Mogra
 
Creating Transmedia Narratives: The Structure & Design of Stories Told Across...
Creating Transmedia Narratives: The Structure & Design of Stories Told Across...Creating Transmedia Narratives: The Structure & Design of Stories Told Across...
Creating Transmedia Narratives: The Structure & Design of Stories Told Across...Peter von Stackelberg
 
The Green Evolution of EMOTIVE Cloud EMOTIVE Cloud: The BSC’s IaaS open-sourc...
The Green Evolution of EMOTIVE Cloud EMOTIVE Cloud: The BSC’s IaaS open-sourc...The Green Evolution of EMOTIVE Cloud EMOTIVE Cloud: The BSC’s IaaS open-sourc...
The Green Evolution of EMOTIVE Cloud EMOTIVE Cloud: The BSC’s IaaS open-sourc...Alex Vaqué
 
Communications Technology Essay
Communications Technology EssayCommunications Technology Essay
Communications Technology EssayAshley Hargrove
 
SELF-STUDY MATERIAL FOR THE USERS OF EUROSTAT MICRODATA SETS
SELF-STUDY MATERIAL FOR THE USERS OF EUROSTAT MICRODATA SETSSELF-STUDY MATERIAL FOR THE USERS OF EUROSTAT MICRODATA SETS
SELF-STUDY MATERIAL FOR THE USERS OF EUROSTAT MICRODATA SETSСветла Иванова
 
Design_Thinking_CA1_N00147768
Design_Thinking_CA1_N00147768Design_Thinking_CA1_N00147768
Design_Thinking_CA1_N00147768Stephen Norman
 
Design and Development of a Knowledge Community System
Design and Development of a Knowledge Community SystemDesign and Development of a Knowledge Community System
Design and Development of a Knowledge Community SystemHuu Bang Le Phan
 
Talks submitted
Talks submittedTalks submitted
Talks submittedKim Minh
 

Similar to Shivkumar_koppad_14043513_EE6093_FInal Ecopy submission. (20)

Distributed system - Student book
Distributed system - Student bookDistributed system - Student book
Distributed system - Student book
 
CS499_JULIUS_J_FINAL_YEAR_PROJETCT_L_DRAFT
CS499_JULIUS_J_FINAL_YEAR_PROJETCT_L_DRAFTCS499_JULIUS_J_FINAL_YEAR_PROJETCT_L_DRAFT
CS499_JULIUS_J_FINAL_YEAR_PROJETCT_L_DRAFT
 
MYINT OO ID BIT COURSEWORK
MYINT OO ID BIT COURSEWORKMYINT OO ID BIT COURSEWORK
MYINT OO ID BIT COURSEWORK
 
Computing Science Dissertation
Computing Science DissertationComputing Science Dissertation
Computing Science Dissertation
 
DMDI
DMDIDMDI
DMDI
 
phd_thesis_with_corrections_v1-00
phd_thesis_with_corrections_v1-00phd_thesis_with_corrections_v1-00
phd_thesis_with_corrections_v1-00
 
Master thesis 14023164
Master thesis 14023164Master thesis 14023164
Master thesis 14023164
 
Dissertation
DissertationDissertation
Dissertation
 
Essay On Tourism
Essay On TourismEssay On Tourism
Essay On Tourism
 
Android Face Recognition App Locker
Android Face Recognition App LockerAndroid Face Recognition App Locker
Android Face Recognition App Locker
 
Creating Transmedia Narratives: The Structure & Design of Stories Told Across...
Creating Transmedia Narratives: The Structure & Design of Stories Told Across...Creating Transmedia Narratives: The Structure & Design of Stories Told Across...
Creating Transmedia Narratives: The Structure & Design of Stories Told Across...
 
Steganography.pdf
Steganography.pdfSteganography.pdf
Steganography.pdf
 
The Green Evolution of EMOTIVE Cloud EMOTIVE Cloud: The BSC’s IaaS open-sourc...
The Green Evolution of EMOTIVE Cloud EMOTIVE Cloud: The BSC’s IaaS open-sourc...The Green Evolution of EMOTIVE Cloud EMOTIVE Cloud: The BSC’s IaaS open-sourc...
The Green Evolution of EMOTIVE Cloud EMOTIVE Cloud: The BSC’s IaaS open-sourc...
 
Communications Technology Essay
Communications Technology EssayCommunications Technology Essay
Communications Technology Essay
 
SELF-STUDY MATERIAL FOR THE USERS OF EUROSTAT MICRODATA SETS
SELF-STUDY MATERIAL FOR THE USERS OF EUROSTAT MICRODATA SETSSELF-STUDY MATERIAL FOR THE USERS OF EUROSTAT MICRODATA SETS
SELF-STUDY MATERIAL FOR THE USERS OF EUROSTAT MICRODATA SETS
 
EMDT_2
EMDT_2EMDT_2
EMDT_2
 
Design_Thinking_CA1_N00147768
Design_Thinking_CA1_N00147768Design_Thinking_CA1_N00147768
Design_Thinking_CA1_N00147768
 
Design and Development of a Knowledge Community System
Design and Development of a Knowledge Community SystemDesign and Development of a Knowledge Community System
Design and Development of a Knowledge Community System
 
Talks submitted
Talks submittedTalks submitted
Talks submitted
 
Book
BookBook
Book
 

Shivkumar_koppad_14043513_EE6093_FInal Ecopy submission.

  • 1. 1 SUBMITTED AS PART OF M.ENG INFORMATION AND NETWORK SECURITY THESIS Android Chat Application for secured communication Author: Supervisor: Shivakumar koppad Dr.Thomas Newe
  • 2. 2 Declaration I declare that this thesis is the result of my own research except as cited in the references. This thesis has not been submitted in candidature of any other award in any other third level institution. Signed : _____________________________ Date : _____________________________
  • 3. 3 Acknowledgement This study wouldn’t have been possible without the constant love, motivation and support of many people during the journey of my life. Firstly to my supervisor Dr.Thomas newe for being there always on the side sharing his expertise, knowledge and motivating me to improvise during the academic year 2014-2015.Definetly he is one among the very few whom I admire to get inspired with every fresh breath on every sunrise. To my friends from across the boundaries covering more than half of the globe during my time at University of Limerick by adding the required vigour, confidence and for being such sport during all the times especially for person who started his carrier and spent 18 Years of life at very small town in the north of Karnataka, India. Nevertheless to My parents and sister who have supported and inspired me to go one step further during all the difficult times in the roller coaster of life and inspiring me to change the world we perceive by being the change what self-thrusts for.
  • 4. 4 Abstract The goal of the thesis is to develop android chat application using eclipse for secured communication which is compatible to all the versions of android 2.2 and above. Humans work in collective level along with thought process and speech to convey as there standout functionalities when compared to other living inhabitants of this planet. With the technology in everyday life of all the people in 21st century instant chat messaging brings people together from across the demographic locations and security is as crucial as the communication between two entities because of the attacks and new vulnerabilities which pops up every new day. Android being popular and most reliable open source operating system for smartphones with more than 1/6 th of user database in the world, Secured chat communication for such OS will not only make it more trusted but also helps in elevating humans affinity towards technology. Different security algorithms such as DES,AES,RSA are used for encryption while sending the data , received text will be in the form of ciphers at the receivers inbox which will get decrypted once the user wants to decrypt by copying the contents in the decryption tab.
  • 5. 5 Contents Table of Figures.............................................................................................................................................7 Introduction ..................................................................................................................................................8 Chapter 2 - Cryptography..............................................................................................................................9 2.1.1 Background of cryptography........................................................................................................9 2.1.2 Cryptography ...............................................................................................................................9 2.1.3 The four building blocks of efficient cryptography are..............................................................10 2.2.1 Vulnerabilities and Exploits........................................................................................................10 2.2.2 Common Vulnerabilities.............................................................................................................10 2.3 Common attacks. ..............................................................................................................................11 2.3.1 Brute force attack – ...................................................................................................................11 2.3.2 Dictionary attacks –....................................................................................................................12 2.3.3 Denial of service attack –...........................................................................................................12 Chapter 3.....................................................................................................................................................14 Security algorithms and key exchange. ..................................................................................................14 3.1 Deffiei-hellman .................................................................................................................................14 3.2.RSA....................................................................................................................................................17 3.3 DES (Data Encryption Standard) algorithm.......................................................................................19 3.4 AES (Advanced Encryption Standard) ...............................................................................................21 3.5 MD5...................................................................................................................................................22 Chapter 4 - Android and chat application...................................................................................................23 4.1 History of Android.............................................................................................................................23 4.2 Below are the different android versions and most of them are named after desserts..................23 4.3 The different tools which android as operating system support for the smartphones are .............24 4.4 Requirements for android on Hardware level..................................................................................26 4.5 Android for chat application.............................................................................................................26 4.5.1 Whats app – ...............................................................................................................................26 4.5.2 Viber-..........................................................................................................................................27 4.5.3 Send –.........................................................................................................................................28 4.5.4 Blackberry Messenger –.............................................................................................................28 4.5.5 Facebook Messenger .................................................................................................................28
  • 6. 6 4.5.6 Skype –.......................................................................................................................................29 Chapter5.0 - Application framework and outlook......................................................................................29 5.1 The following show the architecture of security implementation in secure messaging..................29 5.2 User Interface Description................................................................................................................30 5.3 Use Case Diagram .............................................................................................................................35 5.4 Data flow diagram.............................................................................................................................36 Chapter 6.....................................................................................................................................................37 Application design and architecture...........................................................................................................37 6.0 Integration of JAVA and CRYPTOGRAPHY.........................................................................................37 6.1 JCA Architecture..........................................................................................................................38 6.2 JCE ...............................................................................................................................................39 6.3 Engine Classes.............................................................................................................................39 6.3.1 JCA Engines .........................................................................................................................39 6.3.2 JCA Engines .........................................................................................................................40 6.4 Security protocol...............................................................................................................................41 Chapter 7.0..................................................................................................................................................42 Implementation of Security:.......................................................................................................................42 7.1 RSA Algorithm:..................................................................................................................................42 7.2 DES Algorithm: ..................................................................................................................................44 7.3 AES Algorithm: ..................................................................................................................................47 7.4 Secure MD5 Hashing:........................................................................................................................49 Chapter 8.0 Testing and result....................................................................................................................51 References ..................................................................................................................................................52 Appendix .....................................................................................................................................................54 AESHelper.java........................................................................................................................................54 DESHelper.Java .......................................................................................................................................56 Encryptmessage.java ..............................................................................................................................59 Mainactivity.Java.....................................................................................................................................61 RSAhelper.Java........................................................................................................................................65 Showmsg.java .........................................................................................................................................67 SMSreceiver ............................................................................................................................................68 Splashscreenactivity.Java........................................................................................................................70
  • 7. 7 Table of Figures Figure 1.Encryption and Decryption of Cryptography................................................................................10 Figure 2.Denial of service attacks. ..............................................................................................................13 Figure 3.Diffie Hellman key exchange.........................................................................................................15 Figure 4.Mathematical computation of Diffie hellman ..............................................................................16 Figure 5.RSA Encryption and Decryption....................................................................................................18 Figure 6.DES algorithm................................................................................................................................20 Figure 7.AES Input.......................................................................................................................................21 Figure 8.Various flavours of Android. .........................................................................................................23 Figure 9.Growth of messaging application whats app................................................................................27 Figure 10.Microsoft line..............................................................................................................................28 Figure 11.Security implementation in instant messaging...........................................................................29 Figure 12.Welcome screen of application. .................................................................................................30 Figure 13.Option to choose between simple and secure texting...............................................................31 Figure 14.Choosing the number from the contact list to send the message. ............................................32 Figure 15.Encryption before sending..........................................................................................................33 Figure 16.Decryption of Message at the receiver side. ..............................................................................34 Figure 17.Use case diagram........................................................................................................................35 Figure 18: JCA Architecture.......................................................................................................................38
  • 8. 8 Introduction As the world is evolving the need for communication between the people is rising. The extreme demand is for instant communication is leading the IT developers to come up with new means of communication which are faster and available widely. In 21st century internet is considered as fastest means of communication, why not ? We can send and receive information from every corner of this planet. Considering the flexibility of internet the service providers are leaning towards it and coming up new products for communication. Among all the application Android based applications are appreciated the most. There are many android applications in the market which provide communication. Providing just communication is not enough on insecure network, enabling strong security is important as well. The proposed application strikes perfect balance between security and integrity. The application provides instant communication and at the same time strong security. Users are allowed to select the security they want and exchange the messages. The encryption algorithms used in the application are RSA, AES, DES and Deffiei-Hellman. The message may contain sensitive information that no one should get access to apart from authorized users. Encrypting the messages before sending over insecure network is important. RSA is one of the top rated asymmetric encryption algorithm that has been used in the application. Public key which is available for the sender is used to encrypt the messages and private key is kept secret by the receiver for decryption. The above mentioned algorithm can strengthen the security so that no unauthorized entity can learn the information that is being transferred. While sending the public key by the destination to the sender, anyone can learn it and make use to decrypt the secret messages. To relent this risk Deffiei-Hellman key exchange algorithm is used. Using this algorithm two authorized entities can exchange the keys without the knowledge of eavesdropper. As of now we have secured the message as well as the key from unauthorized entity, but anyone can alter the encrypted data passing via insecure network. To address this risk MD5 hashing algorithm has been used using which we can analyze whether the message has been altered. Adding to that used is allowed to select which algorithm user want to encrypt his/her data. To make this happen AES and DES algorithm are made available.
  • 9. 9 Chapter 2 - Cryptography 2.1.1 Background of cryptography. Cryptography is one of the oldest fields of technical study having history of more than 4000 Years. (Cohen, 1990-1995)With the advancement of technology in the 21st century, the need for secured communication has become vital in order to secure the data while channelizing between two entities. Though the idea of cryptography has been existed since ages specially to hide the data from enemies in wars and used by Julius ceaser which was termed as mono-alphabetic substitution ciphers .The idea of cryptography in the world of internet has seen exponential growth since last several decades when people started using Internet for transmission of crucial credit card ,debit card details, personal information in all walks of life in everyday life .Cryptography across the internet is basically applying complex computational mathematics and logic to adhere to the protocols and server its basic purpose. The key factors which determine elegant cryptographic implementation are Data confidentiality,Integrity,Availibility,non- repudiation,authorization.While all the multinationals organizations with billion plus dollars in revenues containing the information of billion people cryptography becomes vital. 2.1.2 Cryptography Cryptography is art of science which deals with secret writing of data. It involves method of secret writing where plane text is converted to encrypted text using cipher and is termed as Encryption. Reverse process of data where cipher text is converted to plain text is termed as decryption. It should be hard to recover the messages from the ciphertext when the messages are drawn from arbitrary probability distributions defined on the set of all strings (i.e arbitrary message spaces). (Shafi Goldwasser, July 2008)
  • 10. 10 Figure 1.Encryption and Decryption of Cryptography. 2.1.3 The four building blocks of efficient cryptography are 1. Confidentiality – Its service which states that no one should be able to read the data except the intended entity. 2. Integrity – Data sent from sender shouldn’t be modified or hampered while its been received at the receiver side. 3. Authentication – Data should be authenticated where receiver is assured of sender’s identity. 4. Non-repudiation – Its protocol where sender cannot deny of the fact later of not sending the data and receiver cannot deny of the fact of not receiving the data. Proof of origin and proof of reception is taken care of. 2.2.1 Vulnerabilities and Exploits. Any flaw in the application, code or software is termed as vulnerability and usage of vulnerability by the attacker in order to perform illegitimate actions is coined as Exploits. 2.2.2 Common Vulnerabilities. 2.2.2.1. Injection Flaws – Happens when unfiltered data is injected to Sql server, browser or the LDAP Server .The problem is attacker can inject the command henceforth malicious content once he has access resulting in loss of data and controlling client’s browsers. (wichers, 2013)
  • 11. 11 Prevention – By filtering and verifying all the data which is been received without giving room for any input to enter henceforth inject the malicious execution. 2.2.2.2.Broken authentication – When the authentication is broken ,the url might contain the session Id and leak it in the reference header to others, the password might not be encrypted either in storage or transit, session id’s might be predictable ,session hijacking when timeouts not implemented right or using HTTP. (wichers, 2013) Prevention – By using framework and educating oneself on what pitfalls are. 2.2.2.3.Cross site scripting – This happens because of widespread input sanitization failure where attacker give tags to web application java script and when its being executed when input is returned to user unsanitized. Which will further paves path by giving information about cookies to the attacker. Prevention – By preventing Html tags not to return to the client. (wichers, 2013) 2.2.2.4. Insecure direct object reference – This happens by trusting user input and paying the price in resulting security vulnerability. Direct object reference means when internal object such as file or data base key is exposed to the user and attacker can provide reference and if authorization is not enforced attacker can access or do things that they should be precluded from. (wichers, 2013) Prevention – By performing user authorization properly and consistently therefore whitelisting the choices. 2.3 Common attacks. 2.3.1 Brute force attack – Brute force attack is trial and error method used to obtain information such as user password or personal identification number. It executes by trying out all the combinations of password inorder to crack. It is also used by security analyst to check the organizational network security. Prevention. 1. By using strong passwords. 2. with the help of access control while logging in.
  • 12. 12 3. by locking out the users who exceeds the maximum login attempts. 2.3.2 Dictionary attacks – It is method of breaking into password protected system logically by entering all the possible combination of all the words in dictionary as a password. These dictionaries include a diverse collection of usernames and passwords and may simply represent a conglomeration of smaller dictionaries. The root account and various system accounts are well represented, with passwords of varying types including common English words, proper names, keyboard patterns, and “leets,” which replace letters with numbers or symbols that resemble the replaced letter. (matthews, 2007) It can also be used to find the key which Is used for encryption and decryption. Often used by spammers, message is sent to email address consisting of words and phrases followed by @symbol. Prevention. Can be reduced to near zero by limiting the number of attempts allowed within given amount of time and by wisely choosing the password key. For illustration, only three attempts are allowed then gap of 15 minutes before attempting for the fourth time 2.3.3 Denial of service attack – Prevent the service being used by others by overloading resources. When multiple host attack simultaneously is DDOS attack. It is executed by sending fake requests to web server henceforth by increasing the load on the server. DoS attacks in the Internet generally conquer the target by exhausting its resources that can be anything related to network computing and service performance, such as link bandwidth, TCP connection buffers, application/service buffer, CPU cycles, etc. (Qijun Gu) Individual attackers can also exploit vulnerability, break into target servers, and then bring down services. Hackers have been carrying out the Denial of service attack from decade starting from 500 MB in 2002 to 10+ GB by 2015.Flash crowd is generic term used to phrase the huge traffic on webservers.
  • 13. 13 Figure 2.Denial of service attacks. 2.2.3.1 Aims of DDOS attacks. Consuming bandwidths with large traffic volumes, Overload or crash the network handling service, sending specific type of packets in order to consume targeted available resources. 2.2.3.2 Prevention of Dos attacks. Attack prevention and preemption before the attack, detection and filtering during the attack, source trace back and identification after the attack. Multiple firewalls will enable to stop the flooding attacks, Switches provide system wide rating, traffic shaping, delayed binding to detect and remediate denial of service attacks. By adding rules to take out flow statistics during Dos attacks they further slowdown and complicate the attack.
  • 14. 14 Chapter 3 Security algorithms and key exchange. 3.1 Deffiei-hellman First public-key type scheme proposed by Diffie & Hellman in 1976 along with the exposition of public key concepts. (stallings) In secure message exchange system usage of encryption algorithm is quite common which leads to data security over an unsecure network. The multiple parties participating in information exchange has to exchange their encryption/decryption key with each other so that the data encrypted by one can be decrypted by the authorized party. During the key exchange, an eavesdropper (passive attack) can capture the key that is being exchanged between the authorized parties and decrypt the information. To address this vulnerability we require a secure way for key exchange. Deffiei-hellman algorithm provide a secure method of key exchange where the users involved in the conversation can exchange their keys in the presence of attacker. Both the parties agree on a common key which is used to encrypt the public key. Let’s analyze how the authorized parties agree on same key without revealing it over the unsecured network. Let’s start with the general example for the sake understanding, consider Alice and Bob, two parties who are willing to agree on a key.
  • 15. 15 Figure 3.Diffie Hellman key exchange.  Bob and Alice agrees on one common paint (C) which an attacked can know about.  Bob and Alice pick one secrete color of paint, B and A respectively, which they don’t share with each other.  Both the parties will mix their secrete paint with the common paint they agreed on. Now Alice have AC and Bob have BC as mixed color.  Now both the parties exchange their mix paint with each other. Alice has BC and A, Bob has AC and B.  Both the parties will mix their secrete color with the mixed color received from the other party. So, Alice got ABC and Bob got ABC.  Now both the authorized partied have same color.  The eavesdropper cannot learn the common paint both the authorized parties agreed on as he/she don’t know the secrete color that has been mixed with the common color. Now let’s analyze how we can represent this method mathematically so that we can use it in real time.
  • 16. 16 Figure 4.Mathematical computation of Diffie hellman  Alice and Bob agree on one prime number P and one generator G in plain text such that P>G and G is primitive root of P. P=11 and G=7.  Now Alice and Bob generate one random secrete number each. Alice’s Secrete number XA=6. Bob’s secrete number XB=9.  Both parties use the formula Y = GX mod P. Alice: Ya = GXa mod P YA = 76 mod 11 = 4. Bob: YB = GXb mod P YB = 79 mod 11 = 8.  Now Alice and Bob exchange YA and YB with each other with is in plain text.  Now both the parties can use their secrete integer and the integer received from each other. Required Secrete number, SK = YX mod P. Alice: SK = (YB)XA mod P. SK = 86 mod 11 = 3 Bob: SK = (YA)XB mod P.
  • 17. 17 SK = 49 mod 11 = 3  Now, Both Alice and Bob got same Secrete Key which they can use to encrypt/decrypt the key required to encrypt/decrypt the actual information. Clearly, much larger values of a, b, and p are required. An eavesdropper cannot discover this value even if she knows p and g and can obtain each of the messages. Suppose p is a prime of around 300 digits, and XA and XB at least 100 digits each. Discovering the shared secret key would take longer than the lifetime of the universe, using the best known algorithm. This is called the discrete logarithm problem. 3.2.RSA RSA algorithm was invented in 1977 by three scientists, namely, Ron Rivest, Adi Shamir and Len Adleman. RSA is asymmetric encryption algorithm where two keys are generated, namely, public key and private key. (scarvalone, 2009) The encryption of required plain text is done using public key and the cypher text can be converted back to plain text using private key. Both the keys are inversely proportional to each other. RSA can be used both for encryption and digital signatures. RSA serves many protocols like SSH, SSL/TLS, S/MIME and OpenPGP. RSA derives its keys by multiplying two large prime numbers, Rabin-Miller primality test algorithm is used to generate prime numbers for RSA. Determining the prime numbers used from the product is extremely difficult and time consuming even using super computers. The strength of encryption depends on the length of public key. The keys are typically 1024 to 2048 bits long. Previously keys of length 1024 were used but as the technology developing at a rapid rate we can expect the key to be broken at any time in near future. So the industries are switching towards keys with the length 2048 bits.
  • 18. 18 Figure 5.RSA Encryption and Decryption. The party willing to receive encrypted information from authorized source will generate two keys, namely, public key and private key. Both the keys are inversely proportional to each other. The public key is sent to the authorized source over the unsecured using deffiei-hellman algorithm and the privet key is kept secrete. Whenever the source want to send the information to destination, it uses the public key of destination to encrypt the information using the formula provided by the RSA algorithm. The genuine destination can decrypt the cyphertext using the unshared private key. Lets see how RSA encryption algorithm works, Algorithm:  Generation of two prime numbers: Consider p and q as two prime number, compute n=pq.  Calculate φ(n) φ(n)=(p-1)(q-1)  We need an exponent e, provided It is an integer Not be factor of n 1 < e < φ(n)  The public key is made up of two numbers that is e and n.  The private key is computed by the following steps Private key, d =( 2(φ(n))+1 ) / e
  • 19. 19  Encryption of information m can be done using the following formula, c= me mod n.  Decryption of the cyphertext c can be decrypted by private key d using the following formula, m= cd mod n. Example:  Generation of two prime number p and q, and n. Consider p=53 and q=59 Compute n=pq i.e. n= 53*59 = 3127  φ(n)= (p-1)(q-1) = (53-1)(59-1) = 3016  Consider e = 3  Public key is (n,e) Public key = (3127,3)  Private key, d= ( 2(φ(n)) + 1 ) / e d= ( 2(3016) + 1 ) / 3 d=2011  Now we can encrypt the information using the public key (n,e) that is (3127,3) Lets consider the information as m=89, so the encrypted information c is, c= 893 mod 3127 = 1394  The cypher text c= 1394 can be decrypted using the private key,  m= cd mod n = 13942011 mod 1327 = 89 3.3 DES (Data Encryption Standard) algorithm DES is symmetric key algorithm used to encrypt/decrypt the information that has to secured from unauthorized entity over the unsafe network. DES was developed at IBM in early 1970s based on the design of Horst Feistel. In those days the algorithm is considered as one of the strongest
  • 20. 20 encryption algorithm and selected by National Bureau of Standards as an official FIPS (Federal Information Processing Standard) of United States in 1977. DES uses 56bit key and can encrypt 64bits of plain text at a time. (Daley, 1999) Figure 6.DES algorithm DES algorithm uses its 56bit key to encrypt the given plain text into 64bit enciphered blocks by means of permutation and substitutions. The process takes place in 16 rounds. Each plain text can be encrypted individually or making the present block of information dependent on the previous blocks. Decryption is reverse process of encryption. The same 64 bit key used in encryption is applied to the cipher while performing decryption.
  • 21. 21 3.4 AES (Advanced Encryption Standard) AES encryption algorithm is extended version of DES encryption algorithm. AES is a block cipher. This means that the number of bytes that it encrypts is fixed. AES has 3 ciphers AES-128, AES-192 and AES-256. The plain text of block size 128bits can be encrypted/decrypted using any of the 126, 192 and 256 bit keys. AES uses same key for encryption as well as decryption. So the source and destination must know the secrete key that has been used. The level of security depends on the key length. (Federal information processing standards publications., November 26,2001) The higher the key length, higher the security level. Depending on the key length the encryption rounds increases. There are 10, 12, and 14 rounds of encryption is performed for the key length 128, 192 and 256 bit respectively. Figure 7.AES Input. Each round will consist of four processes, namely, SubByte, ShiftRows, MixColumns and AddRoundKey. Internally the AES algorithm’s operations are performed on 2 dimension array of bytes called states. AES algorithm process the data in Hexadecimal units.
  • 22. 22 3.5 MD5 (Message Digest 5) MD5 is hashing algorithm used maintain integrity designed by Ron Rivest in 1991. MD5 is one way encryption where it is extremely difficult to generate plain text from the cipher text. It can be used for digital fingerprints and secure password storage. (Kozushko, 11/28/2003) MD5 algorithm consists of 5 steps Step 1: The original message is padded with required amount to bits to make the size of the data block congruent to 448 modulo 512. We must follow the following rules while padding the required amount of bits to the original message. The rules are as follows,  Firstly, the message is padded with the bit 1.  To bring the message length to 64 bits fewer than a multiple of 512 we should add required amount of 0s following 1. Step 2: Append length. A 64bit representation of the actual message is appended to the result of previous step. The output of this step has a length that is an multiple of 512 bits. Step 3: Now initialize the Message Digest buffer. The buffer is divided into 4 parts, namely A, B, C and D, each of 32bit length. Word A, B, C and D are initialized to the initial value 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476 respectively. Step 4: Process message in 16 word block i.e., 512 bit block. In this step we append the message in blocks of 512 bits each. For each input block, 4 rounds of operations are performed with 16 operations in each round. Step 5: This is the last step used to output the content of the four words i.e. A, B, C and D. The output will be in low order byte first sequence.
  • 23. 23 Chapter 4 - Android and chat application 4.1 History of Android. Android took birth on November 2007 and November 5 has been regarded as birthday of Android (spaight) and down the line 8 years it has been one of the most successful and powerful mobile operating systems in the history of smartphones with more than billion users and billion plus android open source applications in the android store. Android is currently under development by Google and Open handset alliance since its first release. 4.2 Below are the different android versions and most of them are named after desserts. Figure 8.Various flavours of Android. 1. Cupcake 1.5 2. Donut 1.6 3. Éclair 2.0 - 2.1 4. Froyo 2.2- 2.3
  • 24. 24 5. Gingerbird 2.3 – 2.3.7 6. Honeycomb 3.0 – 3.2. 7. Ice cream sandwich 4.0 8. Jellybean 4.1 – 4.3 9. Kitkat 4.4 10.Lollipop 5.0 – 5.1 11.Marshmallow 4.3 The different tools which android as operating system support for the smartphones are 1. Gmail synchronization with application. 2. Contacts in line with people application. 3. Google maps and street view to find the different directions on various demographic locations using GPS. 4. Voice speech recognition on Google talk. 5. Instant messaging, text messaging, Multimedia messaging, calculator, business applications, social media applications like Facebook, Instagram, twitter, quora, viber. (DHT Technologies.) 6. Media player which runs the audio and visual files both in the background and at the user interface. 7. Search option where people can put the query to obtain any information over the internet. 8. Different notifications which arrive at the status bar with regards to setting the alarm, brightness of the phone, email notifications, Instant messaging notifications. 9. Voice recognition dialer which enables user to dial the contact number without using manual input. 10. Wallpaper which accounts for the different images including personal ones on the background for marvelous ambient approach.
  • 25. 25 11. wi-fi and Bluetooth connections. 12. Video watching software’s such as YouTube. 13. Support for third party text prediction and dictionary for user usage. 14. Auto rotation of the screen. 15. Setting up the pictures for the contact list. 16. USB tethering and hotspot functionality where users can create own network and add different devices to it. 17. Picture and video uploads on social networking sites. 18. Support for near field communication. 19. Power management which enables user to identify the applications which are consuming more power and can halt them when they are not being actively used 24-7 thus improvising the battery life. 20. Video calling support using applications such as Skype to connect users from different parts of the globe. 21. Holographic interface. 22. Multitasking where user can access different applications with one touch. 23. Encrypts all the user data using security protocols. 24. Connectivity for USB applications. 25. Provides excellent UI for gaming applications. 26. Adding additional storage on SD card where user can store huge bulk of data. 27. Able to excess Microsoft office thus making it more reliable for connectivity. 28. Keypad is available in multiple languages and user has the ease to select one of his choice. 29. Switching on to airplane mode when travelling beyond the earth’s atmosphere. 30. Facial recognition where device is unlocked once the pattern is matched. 31. Photo gallery is viewed in multiple outlooks for user experience.
  • 26. 26 32. Can be supportable upto 64 bit processors. 33. Multiple login accounts for the email account as in single mail application can be used by more than one user. 34. Flashlight drawn from the camera application can also be used as torch. 4.4 Requirements for android on Hardware level. From the rediscovery of operating systems from android version 1.6 to android 5.0 the vital hardware requirement is ARM architecture which also includes microprocessor without interlocked pipeline stages which is reduced instruction set computer which varies from MIPS 1 to MIPS 6 and also x86 processors. The minimum Ram requirements for the efficient execution of operating system has been varied over time which started with minimum 32 MB RAM,32MB flash memory and 200 MHZ ARM architecture and now has been extended up to 4 Gb OF RAM manifested by Qualcom,mediatek 230 MB flash memory 1 GHZ ARM architecture. (Wikipedia ,Free Encyclopedia., 2015) 4.5 Android for chat application The best part of android chat application are they enable to send/receive the text,image,video between two users across the globe without spending penny on telecommunication network. Provided the little data charges which user has to account while using it.They are becoming increasingly popular in never seen before rate in last several years due to the ease, reliability, productivity and user addiction over the smartphone. Whatsapp, Viber, Skype, Line, Wechat,facebook messenger are the frontiers in this field considering other thousands of applications which make the demand get executed. 4.5.1 Whats app – Whats app as company started by former yahoo employee Brian Acton and Jan korum in 2009 which works on subscription model consisting just over 50 Employees was acquired by Facebook for whopping 19 billion US dollars which now has around 900 active users in the world. This is the best example why instant messaging application is such at apex boom in the market of Information
  • 27. 27 technology. Easy setup, automatic synchronization with phone contacts,ad free experience ,automatic synchronization with phone contacts makes the whats app best in the business which charges 0. 99USD every year after free subscription for the first year. Figure 9.Growth of messaging application whats app 4.5.2 Viber- The basic functionality of viber includes instant messaging, Pic sharing with added emotions and sticker sharing. What makes viber one of the leading application in android store is its ability to call to anyone on their phone without carrier charges for the telecommunication network which varies with the location you are dialing with automatic synchronization of contacts and also letting to know about the people who use Viber on their contact list. Viber is hassle free of pin input when user logs into the app and uses telephone number as the input.
  • 28. 28 4.5.3 Send –Microsofts send is one of the other instant messaging app which stands out in with feature of beginning instant messaging application on the email without the need for user to login in to Email account everytime.Its highly recommended for the official trans/receive of information as its makes it more quick, handy and saves lot of time user puts in during email communication. Figure 10.Microsoft line 4.5.4 Blackberry Messenger –Thought Blackberry messenger was proprietary based application which was restricted to black berry users which enables user to send/receive texts, images, videos, location sharing, automatic voice recognition until it was released in 2013 on android store and IOS.A pin system allows user to share BBM contacts without having to share phone or email details while the 2 way opts in for communication allows user to control the text which are being received to the inbox. 4.5.5 Facebook Messenger – Facebook messenger is brought up by Social networking giant Facebook. Where user contact list is automatically synchronized by the connections he/she has in their friend list. Application enables to send/receive text, images, voice, Emotions, stickers, URL’s, files, folders
  • 29. 29 Figure 11.Security implementation in instant messaging. etc. It’s quite handy when compared to other applications is of the fact that there is chat pop up on the front end of the screen of the smartphone which user can use even when other applications are being used. Facebook has introduced dialing facilities on the chat application where user can other people in their friend list and even can do video chat. User can block the other persons profile when he/she doesn’t want to receive any text/image/video/files from the users as sometimes malicious contents/spam are being sent by unknown entities over the internet. 4.5.6 Skype – Besides being known for the video calling and send/receive of the short video functionality ,skype does has strong instant messaging facilities in its application. With the help of skype credits users can call to any part of the world to the people who are in there contact list. Though the vb instant messaging facility isn’t that popular in day – day lives of the users but skype does provide ease and reliability for the users to communicate Chapter5.0 - Application framework and outlook The proposed application is designed to send and receive encrypted text messages and decrypt at the receiver side. 5.1 The following show the architecture of security implementation in secure messaging. Insecure Network Sender/receiver Sender/receiver Messaging Messaging Send/Receive Cypher text
  • 30. 30 5.2 User Interface Description Application is designed using Android 4.0 using eclipse IDE, This application uses multiple encryption and decryption algorithms to ensure secured message exchange. 1. The application starts with welcome screen which is as follows 5 2. Application consists of two types of texting options, one is plain texting, and another is secure texting. As soon as the application opens we find the above figure and it takes us to select the type of messaging activity whether secure texting or simple texting. The screen is as follows Figure 12.Welcome screen of application.
  • 31. 31 Figure 13.Option to choose between simple and secure texting.
  • 32. 32 3. If we select Simple texting we can make simple messages where there is no security for outgoing messages Its just like normal messages. The following is the screen to show the simple messages. Figure 14.Choosing the number from the contact list to send the message.
  • 33. 33 4. If we select Secure Texting we can make secure messages where we are encrypting the outgoint messages which different kinds of algorithms available in android. Namely AES, DES, RSA Figure 15.Encryption before sending.
  • 34. 34 5. And the main screen is having one more option called Decrypt Inbox messages which helps you to decrypt the message which are already received in inbox. Figure 16.Decryption of Message at the receiver side.
  • 35. 35 Figure 17.Use case diagram. 5.3 Use Case Diagram Select Contact Generate Random Number Hash Random numbers Generate Key with Hash Data Use As Key for Selected Algo Send Message Select Algorithm Sender Receiver
  • 36. 36 5.4 Data flow diagram Sender/ Reciever Select Type Simple Secured Simple TextSecured Text Select Contact Select Algorithm Send Message Select Contact Send Message
  • 37. 37 Chapter 6. Application design and architecture. 6.0 Integration of JAVA and CRYPTOGRAPHY The chat application is built on JAVA platform as it strongly emphasize on security. Cryptography is integrated with Java to achieve secure communication. Java application can be developed using either of the below library:  JCA and JCE APIs (Application programming interface). JCA and JCE are the two main APIs which helps in Cryptographic operations(Oracle 2011). By using these APIs Java provides the cryptographic functionality.  Java Cryptography Architecture (JCA) - It is a security framework which is integrated with the core JAVA API  Java Cryptography Extension (JCE) - This is the extension of JCA for strong encryption.
  • 38. 38 6.1 JCA Architecture Figure 18: JCA Architecture  JCA/JCE provides the functionalities of various cryptographic services.  Cryptographic implementation is actually provided by service providers.  JCA/JCE is structured with “Engine” classes and these classes provide a standard interface into the cryptographic service provides. JCA provides two provider classes:  Provider (Cryptographic Service Provider): It has methods which are used to get information about provider’s name and version number.  Security: It manages the installed service providers and security properties. Basically used to add, remove or modify providers.
  • 39. 39 6.2 JCE  It provides many functions which JCA doesn’t provide such as encryption/decryption and symmetric key generation.  It uses the provider class of JCA. 6.3 Engine Classes They actually provide an interface for every specific cryptographic operation such as Digital signature, Encryption, Message Digest etc. Cryptographic operations are categorized into classes in JCA/JCE. These classes are named as engines.  JCA Engines/Classes  JCE Engines/Classes 6.3.1 JCA Engines  MessageDigest: Produces hash value(MD5,SHA)  Signature: Produces digital signatures – KeyPairGenerator: Produces pairs of keys  KeyFactory: breaks down a key  KeyStore: Manages and stores keys  SecureRandom: Produces random/pseudo-random numbers – AlgorithmParameters: Maintains the security parameters for specific algorithms – AlgorithmParameterGenerator: Creates parameters  CertificateFactory: Generate certificates and revocation  CertPathBuilder: Establishs relationship chains between certificates  CertStore: It stores certificates and revocation.
  • 40. 40 6.3.2 JCA Engines  Cipher: Encryption and Decryption  KeyGenerator: Produces secret keys used by ciphers for encryption/decrypton.  SecretKeyFactory: Operates on Secret Key objects  KeyAgreement: Key agreement protocol  MAC: Provides Message authentication code functionality 6.3.2.1 JCA/JCE Engine location: JCA Engine: Located in java.security package JCE Engine: Located in javax.crypto package Example Codes(Oracle 2011): 1. Generating the key: KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecretKey aesKey = keygen.generateKey(); 2. To generate the cipher object from the key generated above: Cipher aesCipher; // Create the cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); We use the generated aesKey from above to initialize the Cipher object for encryption: // Initialize the cipher for encryption aesCipher.init(Cipher.ENCRYPT_MODE, aesKey); // Our cleartext byte[] cleartext = "This is just an example".getBytes(); // Encrypt the cleartext byte[] ciphertext = aesCipher.doFinal(cleartext); // Initialize the same cipher for decryption
  • 41. 41 aesCipher.init(Cipher.DECRYPT_MODE, aesKey); // Decrypt the ciphertext byte[] cleartext1 = aesCipher.doFinal(ciphertext); Plaintext Input: Hello, Welcome to the world of Encryption and Decryption Cipher Text Output: 07f7d720f351119ed651836585e40dea0d873f08223cf3f5fd1c81fbe42986eb1b1100b7133f75b2f 83800013dbd6bdb6d300497f605713540fe6003f53d7594 6.4 Security protocol Here in the proposed system we designed a secure protocol to send text messages which can not be broken by any hackers in the network the protocol is as follows Here the protocol works at both the Sender and the Reciever Step 1: First the plain text is encrypted with RSA algorithm we are using big integer algorithm to encrypt the message then encrypted message is taken out. Step 2: We are creating a 16 digit random numbers and random number will be hashed using secure md5 hash algorithm Step 3: The RSA encrypted data is again encrypted with DES algorithm using hash data as a secure key. Step 4: Here again DES encrypted data will be taken out and again encryped with AES algorithm and the key is hash data. Then
  • 42. 42 Step 5: Final Encrypted data is sent to the receiver and receiver side the algorithm information is obtained using key term which is sent in the message along with secured data then using the key term the application understand the type of algorithms used in the encryption based on the type of key term decryption will be stated for the incoming message on demand and then final plain text will be given to receiver. Chapter 7.0 Implementation of Security: The application works on several cryptographic functionalities using the supported types of cryptography from android we designed a secure protocol to send and receive text messages. 7.1 RSA Algorithm: public RSAHelper(int bits) { bitlen = bits; SecureRandom r = new SecureRandom(); BigInteger p = new BigInteger(bitlen / 2, 100, r); BigInteger q = new BigInteger(bitlen / 2, 100, r); n = p.multiply(q); BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q .subtract(BigInteger.ONE)); e = new BigInteger("3"); while (m.gcd(e).intValue() > 1) { e = e.add(new BigInteger("2")); } d = e.modInverse(m); } /** Encrypt the given plaintext message. */
  • 43. 43 public synchronized String encrypt(String message) { return (new BigInteger(message.getBytes())).modPow(e, n).toString(); } /** Encrypt the given plaintext message. */ public synchronized BigInteger encrypt(BigInteger message) { return message.modPow(e, n); } /** Decrypt the given ciphertext message. */ public synchronized String decrypt(String message) { return new String((new BigInteger(message)).modPow(d, n).toByteArray()); } /** Decrypt the given ciphertext message. */ public synchronized BigInteger decrypt(BigInteger message) { return message.modPow(d, n); } /** Generate a new public and private key set. */ public synchronized void generateKeys() { SecureRandom r = new SecureRandom(); BigInteger p = new BigInteger(bitlen / 2, 100, r); BigInteger q = new BigInteger(bitlen / 2, 100, r); n = p.multiply(q); BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q .subtract(BigInteger.ONE)); e = new BigInteger("3"); while (m.gcd(e).intValue() > 1) { e = e.add(new BigInteger("2")); }
  • 44. 44 d = e.modInverse(m); } /** Return the modulus. */ public synchronized BigInteger getN() { return n; } /** Return the public key. */ public synchronized BigInteger getE() { return e; } 7.2 DES Algorithm: public class DESHelper { public static String encrypt(String seed, String cleartext) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } public static String decrypt(String seed, String encrypted) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); }
  • 45. 45 private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("DES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); sr.setSeed(seed); kgen.init(64, sr); // 192 and 256 bits may not be available SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; } private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; } private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } public static String toHex(String txt) { return toHex(txt.getBytes()); }
  • 46. 46 public static String fromHex(String hex) { return new String(toByte(hex)); } public static byte[] toByte(String hexString) { int len = hexString.length() / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue(); return result; } public static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private final static String HEX = "0123456789ABCDEF"; private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); }
  • 47. 47 7.3 AES Algorithm: public class AESHelper { public static String encrypt(String seed, String cleartext) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } public static String decrypt(String seed, String encrypted) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); } private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); sr.setSeed(seed); kgen.init(128, sr); // 192 and 256 bits may not be available SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; } private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES");
  • 48. 48 cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; } private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } public static String toHex(String txt) { return toHex(txt.getBytes()); } public static String fromHex(String hex) { return new String(toByte(hex)); } public static byte[] toByte(String hexString) { int len = hexString.length() / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue(); return result; }
  • 49. 49 public static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private final static String HEX = "0123456789ABCDEF"; private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); } 7.4 Secure MD5 Hashing: public class PasswordHash { public String hashPassword(String password){ String passwordToHash = password; String generatedPassword = null; try { // Create MessageDigest instance for MD5 MessageDigest md = MessageDigest.getInstance("MD5"); //Add password bytes to digest md.update(passwordToHash.getBytes()); //Get the hash's bytes byte[] bytes = md.digest();
  • 50. 50 //This bytes[] has bytes in decimal format; //Convert it to hexadecimal format StringBuilder sb = new StringBuilder(); for(int i=0; i< bytes.length ;i++) { sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 32).substring(1)); } //Get complete hashed password in hex format generatedPassword = sb.toString(); System.out.println(generatedPassword); return generatedPassword; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } }
  • 51. 51 Chapter 8.0 Testing and result The aim of the project is to develop an application which can send encrypted message to the receiver from the android device since android devices or any mobile the text messages are having limitations in the size around 160 characters per message so because of that reason the security protocol will not be working with big text messages but still we have implemented to show the application is more in need for the todays software world due the heavy growth of hackers in the network and this application can be enhanced to send big text messages in the future.
  • 52. 52 References Cohen, F. (1990-1995). Specialising in Information protection since 1977. Fred chohen and assosiates. Daley, W. (1999). Data encryption standard. Gaithersburg.: U.S department of Commerce. DHT Technologies. (n.d.). www.dhtusa.com. Retrieved from http://www.dhtusa.com/media/AndroidInternals.pdf: http://www.dhtusa.com/media/AndroidInternals.pdf Federal information processing standards publications. (November 26,2001). Advanced Encryption standard. National institute of standards and Technology. Kozushko, H. (11/28/2003). MD5 Algoritham. matthews, J. o. (2007). A study of passwords and Methods used in Brute force SSH attacks. New York : Department of computer science , Clarkson University. Qijun Gu, P. L. (n.d.). Denial of service attacks. Texas.: Department of computer science , Texas state university. scarvalone, M. (2009). RSA Encryption and DIffie Hellman key exchange. RSA Encryption . Shafi Goldwasser, M. B. (July 2008). Lecture notes on cryptography. Cryptography, 14. spaight, J. (n.d.). Google android operating system. stallings, W. (n.d.). Cryptography and Network security. Tom. (2015). Toms guide. Retrieved from www.tomsguide.com: http://www.tomsguide.com/us/pictures- story/654-best-messaging-apps.html wichers, D. (2013). OWASP Top 10 . Creative Commons attribution share. Bishop, M. (2003) “What is computer security?,” Security & Privacy, IEEE, 1(1), 67–69. Bishop, M. (2004) Introduction to Computer Security, Addison-Wesley Professional.
  • 53. 53 Choo, K.-K.R., service), S. (Online (2009) Secure Key Establishment [online], Springer Science+Business Media, LLC: Boston, MA, available: http://ul.summon.serialssolutions.com/2.0.0/link/0/eLvHCXMwY2AwNtIz0EUrE1IM0yyNU0zNjV ITzY2NLJOSgRwTw2RLYAVibmIA3m6BuOIYqYB3E2JgSs0TZZBwcw1x9tAtzYmHjmrEm1qC Dp8zFGPgTQQtBc8rAW8ZS5FgUDC3TDRKMTKzsEiySDRJTTW2SDNKMgel7KS0NIPUZGM AOxwoaw. Coffey, T., Saidha, P. (1996) “Non-repudiation with mandatory proof of receipt,” ACM SIGCOMM Computer Communication Review, 26(1), 6–17, available: http://portal.acm.org/citation.cfm?doid=232335.232338. Diffie, W., Hellman, M.E. (1979) “Privacy and authentication: An introduction to cryptography,” Proceedings of the IEEE. Eskicioglu, A.M., Litwin, L. (2001) “Cryptography,” Potentials, IEEE. Ganesan, P., Venugopalan, R., Peddabachagari, P., Dean, A., Mueller, F., Sichitiu, M. (2003) “Analyzing and modeling encryption overhead for sensor network nodes,” Proceedings of the 2nd ACM international conference on Wireless sensor networks and applications - WSNA ’03, 151, available: http://portal.acm.org/citation.cfm?doid=941350.941372. Ganley, M. (2006) “Introduction – Cryptography,” Information Security Technical Report, 11(2), 67, available: http://www.sciencedirect.com/science/article/pii/S1363412706000227 [accessed 23 Aug 2014]. GitHub, I. (2014a) Multiparty Protocol Specification [online], available: https://github.com/cryptocat/cryptocat/wiki/Multiparty-Protocol-Specification. GitHub, I. (2014b) Design and Functionality [online], available: https://github.com/cryptocat/cryptocat/wiki/Design-and-Functionality.
  • 54. 54 Appendix AESHelper.java package com.proj.myapp; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AESHelper { public static String encrypt(String seed, String cleartext) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result); } public static String decrypt(String seed, String encrypted) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); } private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); sr.setSeed(seed); kgen.init(128, sr); // 192 and 256 bits may not be available SecretKey skey = kgen.generateKey();
  • 55. 55 byte[] raw = skey.getEncoded(); return raw; } private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; } private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } public static String toHex(String txt) { return toHex(txt.getBytes()); } public static String fromHex(String hex) { return new String(toByte(hex)); } public static byte[] toByte(String hexString) { int len = hexString.length() / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue(); return result; }
  • 56. 56 public static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private final static String HEX = "0123456789ABCDEF"; private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); } } DESHelper.Java package com.proj.myapp; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class DESHelper { public static String encrypt(String seed, String cleartext) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] result = encrypt(rawKey, cleartext.getBytes()); return toHex(result);
  • 57. 57 } public static String decrypt(String seed, String encrypted) throws Exception { byte[] rawKey = getRawKey(seed.getBytes()); byte[] enc = toByte(encrypted); byte[] result = decrypt(rawKey, enc); return new String(result); } private static byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("DES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); sr.setSeed(seed); kgen.init(64, sr); // 192 and 256 bits may not be available SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; } private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; } private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } public static String toHex(String txt) {
  • 58. 58 return toHex(txt.getBytes()); } public static String fromHex(String hex) { return new String(toByte(hex)); } public static byte[] toByte(String hexString) { int len = hexString.length() / 2; byte[] result = new byte[len]; for (int i = 0; i < len; i++) result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2), 16).byteValue(); return result; } public static String toHex(byte[] buf) { if (buf == null) return ""; StringBuffer result = new StringBuffer(2 * buf.length); for (int i = 0; i < buf.length; i++) { appendHex(result, buf[i]); } return result.toString(); } private final static String HEX = "0123456789ABCDEF"; private static void appendHex(StringBuffer sb, byte b) { sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f)); } }
  • 59. 59 Encryptmessage.java package com.proj.myapp; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class EncryptMessage extends Activity{ EditText edtEncryptedata; TextView txtDecrypteShow; Button btnDecrypte; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.encryptmessage); edtEncryptedata = (EditText) findViewById(R.id.edtencryptedata); txtDecrypteShow = (TextView) findViewById(R.id.txtDecrypteShow); btnDecrypte = (Button) findViewById(R.id.btn_decryptedata); btnDecrypte.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (!edtEncryptedata.getText().toString().equals("")) { String msg =edtEncryptedata.getText().toString();
  • 60. 60 try { String strMessage = AESHelper.decrypt("BREAK", msg); txtDecrypteShow.setText(strMessage); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); Toast.makeText(EncryptMessage.this, "Not an encrypte text", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(EncryptMessage.this, "Please enter encrypte text", Toast.LENGTH_LONG).show(); } } }); } }
  • 61. 61 Mainactivity.Java ackage com.proj.myapp; import android.net.Uri; import android.os.Bundle; import android.provider.ContactsContract; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.telephony.gsm.SmsManager; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; @SuppressWarnings("deprecation") public class MainActivity extends Activity implements OnClickListener { String algo[]; EditText etEnterNumber, etTextMsg; Button btnSend, btnDecrypt, btnSelectcontact; String plainText, cipherText, strPhoneNum; private static final int PICK_CONTACT = 11; Spinner spinner1;
  • 62. 62 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etEnterNumber = (EditText) findViewById(R.id.etEnterNumber); etTextMsg = (EditText) findViewById(R.id.etTextMsg); btnSend = (Button) findViewById(R.id.btnSend); btnDecrypt = (Button) findViewById(R.id.btnDecrypt); btnSelectcontact = (Button) findViewById(R.id.btn_selectcontact); spinner1 = (Spinner) findViewById(R.id.spinner1); algo = getResources().getStringArray(R.array.alog); ArrayAdapter<String> algoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, algo); spinner1.setAdapter(algoAdapter); btnSend.setOnClickListener(this); btnDecrypt.setOnClickListener(this); btnSelectcontact.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onClick(View arg0) { // TODO Auto-generated method stub switch (arg0.getId()) { case R.id.btnSend: plainText = etTextMsg.getText().toString(); strPhoneNum = etEnterNumber.getText().toString(); if (!plainText.equalsIgnoreCase("") && !strPhoneNum.equalsIgnoreCase("")) { try {
  • 63. 63 cipherText = AESHelper.encrypt("BREAK", plainText); sendSMS(strPhoneNum, cipherText); Log.d("", cipherText); } catch (Exception e) { e.printStackTrace(); sendSMS(strPhoneNum, plainText); } } else { Toast.makeText(getApplicationContext(), "Please fill all the fields", Toast.LENGTH_LONG) .show(); } break; case R.id.btnDecrypt: Intent intent1 = new Intent(MainActivity.this, EncryptMessage.class); startActivity(intent1); break; case R.id.btn_selectcontact: Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT); break; } } private void sendSMS(String phoneNumber, String message) { SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNumber, null, message, null, null); Toast.makeText(getApplicationContext(), "Message sent", Toast.LENGTH_LONG) .show(); } @Override
  • 64. 64 protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case PICK_CONTACT: if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); try { Cursor cursor = getContentResolver().query(contactData, null, null, null, null); if (cursor.moveToFirst()) { String id = cursor .getString(cursor .getColumnIndexOrThrow(ContactsContra ct.Contacts._ID)); String hasPhone = cursor .getString(cursor .getColumnIndex(ContactsContract.Cont acts.HAS_PHONE_NUMBER)); if (hasPhone.equalsIgnoreCase("1")) { Cursor phones = getContentResolver() .query(ContactsContract.CommonDataKinds.P hone.CONTENT_URI, null, ContactsContract.CommonDataKinds. Phone.CONTACT_ID + " = " + id, null, null); phones.moveToFirst(); String cNumber = phones.getString(phones .getColumnIndex("data1")); etEnterNumber.setText(cNumber); } }
  • 65. 65 } catch (Exception e) { e.printStackTrace(); } } break; } } } RSAhelper.Java package com.proj.myapp; import java.security.Key; import java.security.KeyPair; import java.security.KeyPairGenerator; import javax.crypto.Cipher; public class RSAHelper { KeyPair kp; Key publicKey = null; Key privateKey = null; byte[] decodedBytes = null; byte[] encodedBytes = null;
  • 66. 66 RSAHelper() { // Original text // Generate key pair for 1024-bit RSA encryption and decryption try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(256); kp = kpg.genKeyPair(); publicKey = kp.getPublic(); privateKey = kp.getPrivate(); } catch (Exception e) { } } public void encrypt(String text) { // Encode the original data with RSA private key try { Cipher c = Cipher.getInstance("RSA"); c.init(Cipher.ENCRYPT_MODE, privateKey); encodedBytes = c.doFinal(text.getBytes()); } catch (Exception e) { } // tvencoded.setText("[ENCODED]:n" + // Base64.encodeToString(encodedBytes, Base64.DEFAULT) + "n"); } // Decode the encoded data with RSA public key public String decrypt() { try { Cipher c = Cipher.getInstance("RSA"); c.init(Cipher.DECRYPT_MODE, publicKey); decodedBytes = c.doFinal(encodedBytes); return new String(decodedBytes); } catch (Exception e) { return null; }
  • 67. 67 } // TextView tvdecoded = (TextView)findViewById(R.id.tvdecoded); // tvdecoded.setText("[DECODED]:n" + new String(decodedBytes) + "n"); } Showmsg.java package com.proj.myapp; import java.security.Key; import java.security.KeyPair; import java.security.spec.X509EncodedKeySpec; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.widget.EditText; public class ShowMsg extends Activity{ String bodytext; EditText etrecmsg; TextToSpeech tts; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.recmsg); etrecmsg = (EditText) findViewById(R.id.etrecmsg); Intent intent = getIntent(); bodytext = intent.getExtras().getString("message");
  • 68. 68 try { //String message = AESHelper.decrypt("BREAK", bodytext); //etrecmsg.setText(message); if(bodytext.contains("-")){ String[] parts = bodytext.split("-"); } } catch (Exception e) { e.printStackTrace(); etrecmsg.setText("Not an encrypted Message:n" + bodytext); } } } SMSreceiver package com.proj.myapp; import java.util.ArrayList; import java.util.List; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.telephony.SmsMessage; public class SmsReciever extends BroadcastReceiver { String address;
  • 69. 69 String body; // @TargetApi(Build.VERSION_CODES.DONUT) @Override public void onReceive(Context context, Intent intent) { List<SmsMessage> smsMessages = getSmsMessages(intent); for (SmsMessage smsMessage : smsMessages) { address = smsMessage.getOriginatingAddress(); body = smsMessage.getMessageBody(); Intent intent2 = new Intent(context, ShowMsg.class); intent2.putExtra("phone", address); intent2.putExtra("message", body); intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent2); } } private List<SmsMessage> getSmsMessages(Intent intent) { List<SmsMessage> smsMessages = new ArrayList<SmsMessage>(); // ---get the SMS message passed in--- Bundle bundle = intent.getExtras(); if (bundle != null) { // ---retrieve the SMS message received--- Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage msg = SmsMessage.createFromPdu((byte[]) pdus[i]); smsMessages.add(msg); } } return smsMessages; } }
  • 70. 70 Splashscreenactivity.Java package com.proj.myapp; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.Window; public class SplashScreenActivity extends Activity { private static int SPLASH_TIME_OUT = 3000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.splashscreen); if (!isTaskRoot()) { Intent intent = getIntent(); String action = intent.getAction(); if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && action != null && action.equals(Intent.ACTION_MAIN)) { finish(); return; } } else { new Handler().postDelayed(new Runnable() { @Override public void run() { // Create an intent that will start the main activity. Intent intentLogin = new Intent(SplashScreenActivity.this, MainActivity.class); SplashScreenActivity.this.startActivity(intentLogin);
  • 71. 71 // Finish splash activity so user can't go back to it. SplashScreenActivity.this.finish(); } }, SPLASH_TIME_OUT); } } @Override public void onBackPressed() { } }