CHAPTER 9
Java Programming for Cybersecurity Applications

“Security depends not so much upon how much you have, as upon how much you can do without.”

—Joseph Wood Krutch

9.1 What Is Cybersecurity?

Cybersecurity is about threats from the Internet. As our lives become increasingly dependent on the Internet, cybersecurity is also becoming increasingly important. A recent example is the WannaCry virus attack in 2017, which affected more than 200,000 computers across 150 countries. The WannaCry virus targeted older Windows operating systems; it locked the affected computers and demanded ransom payments in the Bitcoin cryptocurrency. Hospitals with infected computers had to cancel operations, and factories had to halt production. Another example is the hacking of TalkTalk, a British telecommunication firm, in 2015 by a 15-year-old schoolboy in Northern Ireland. Thousands of customers' online details were stolen. The boy claimed he did this just to show off to friends. TalkTalk said the hack cost the firm £42m and lost 98,000 broadband customers.

In this era of digital technologies, cybersecurity is of paramount importance. This chapter will first introduce the key terms and technologies used in cybersecurity and then show some Java programming examples for cybersecurity applications.

Cybersecurity addresses the following key aspects:

  • Confidentiality Confidentiality means that the information transmitted between senders and receivers should be accessible only to the corresponding parties.
  • Authentication Authentication means determining that the information you're getting is from the source it claims to come from.
  • Integrity Integrity means that the information you have accessed must be original, intact, and complete.
  • Availability Availability means that the information you are authorized to access is always accessible.

The commonly used approach to improving cybersecurity is encryption.

9.2 What Is Encryption?

Encryption is one of the oldest security techniques; it dates back at least to the Roman era, when a cipher encryption, now known as the Caesar cipher, was named after the emperor Julius Caesar. In this simple shift cipher, letters in the text are shifted a fixed number of places down the alphabet to make them unreadable.

For example, if you shift each letter three places to the left in the alphabet, the following clear text:

attack london

will become the following:

xqqxzh ilkalk

The result is initially unreadable, but this kind of encryption is easy to decrypt. Modern encryption uses far more sophisticated and advanced mathematical algorithms that are much more secure. Modern encryption techniques can be classified as either private key encryption (also called symmetric key encryption) or public key encryption (also called asymmetric key encryption). The technical field of study underlying encryption and secure communication is known as cryptography.

9.2.1 Private Key Encryption

In private key encryption, the sender and the receiver use the same key to encrypt the message and to decrypt the message, as illustrated in Figure 9.1. You can imagine the private key as simply a sequence of random numbers. Because both parties use the same key, this is also called symmetric key encryption.

Schematic flow diagram depicting Private Key, Plain Text to Encrypt to Cypher Text to Decrypt to Plain Text.

Figure 9.1: Private key encryption. Sender A uses a secret key to encrypt the plain text into cipher text. Receiver B will use the same secret key to decrypt the cipher text back to plain text.

The most popular private key encryption is Advanced Encryption Standard (AES), also known as Rijndael, developed by Belgian cryptographers Vincent Rijmen and Joan Daemen. In AES, plain text is divided into 128-bit blocks. The secret key, which can be 128, 192, or 256 bits, is expanded into several round keys through a key expansion algorithm. The combined plain text and the corresponding round keys are then put through several rounds of mathematical operations, such as adding the round key (AddRoundKey), substituting bytes (SubBytes), shifting rows (ShiftRows), and mixing columns (MixColumns). The number of rounds depends on the key size: 10 rounds for 128-bit keys, 12 rounds for 192-bit keys, and 14 rounds for 256-bit keys. The cipher text will appear at the end. The beauty of this scheme is that encryption and decryption are the same operation but in reverse order, as illustrated in Figure 9.2.

Image described by caption and surrounding text.

Figure 9.2: The operation of AES. The encryption and decryption are the same operation but in reverse order.

To date, AES is more secure and more widely used than any other algorithms, including Data Encryption Standard (DES), Triple DES, Twofish, and so on. Cracking an AES 256-bit encryption by brute force—that is, searching 2256 possibilities—would take an estimated 3 × 1051 years even by 50 supercomputers that could check a billion billion (1018) AES keys per second.

The advantage of secret key encryption is that it is secure and can be used for large volumes of text. The disadvantage is that both the sender and the receiver need to use the same key, so key distribution is always an issue.

See the following resources for more information about AES:

https://parsiya.net/blog/2015-01-06-tales-from-the-crypto---leaking-aes-keys/

https://www.tutorialspoint.com/cryptography/advanced_encryption_standard.htm

https://iis-people.ee.ethz.ch/~kgf/acacia/c3.html#tth_sEc3.2

9.2.2 Public Key Encryption

In contrast to private key encryption, with public key encryption the sender and receiver use different keys to encrypt the message and to decrypt the message, as illustrated Figure 9.3. First, everyone needs to generate a pair of their own keys, one private key and one public key. They will keep the private key to themselves and give the public key to everyone else. Then, if A wants to send a secret message to B only, A will use B's public key to encrypt the message, and B will use B's private key to decrypt the message. In this case, only B can decrypt the message. Because senders and receivers use different keys, this is also called asymmetric key encryption. The beauty of this encryption method is that there is no key distribution issue; others can never figure out what your private key is from your public key.

Image described by caption and surrounding text.

Figure 9.3: Public key encryption. Sender A uses B's public key to encrypt the message, and receiver B uses B's private key to decrypt the message.

Public key encryption can also be used for authentication purposes. For example, to prove that the message is coming from A, sender A can encrypt the message using A's private key, and receiver B will know it is indeed coming from A if B can decrypt the message using A's public key, as shown in Figure 9.4.

Image described by caption and surrounding text.

Figure 9.4: Public key encryption for authentication. Sender A uses A's private key to encrypt the message, and receiver B uses A's public key to decrypt the message. This proves the message is coming from A.

The most popular public key encryption is Rivest–Shamir–Adelman (RSA), designed by Ron Rivest, Adi Shamir, and Leonard Adelman in 1977. The RSA algorithm involves three key steps: key generation, encryption, and decryption.

Key Generation

  • Select two distinct prime numbers p and q.
  • Calculate equation.
  • Calculate equation.
  • Select integer equation, where equation.
  • Select integer equation, so that (equation) is exactly divisible by equation.
  • Public key: (equation).
  • Private key: (equation).

Here gcd is the greatest common divisor, and mod is the modulus operator, which calculates the remainder of the division of two numbers. The public key is (equation), and the private key is (equation).

Encryption

  • Plain text:     equation
  • Cipher text:   equation

Decryption

  • Cipher text:   equation
  • Cipher text:   equation

Let's use an example to illustrate how RSA work. To create your public and private keys, you need to pick two distinct prime numbers, equation, and equation. Then calculate equation, calculate equation, select equation so that the greatest common divisor of z and e is one, and finally select equation, as equation. Your public key is (equation), and your private key is (equation).

Imagine you want to send the number 5 (letters can also be treated as numbers) to encrypt the plain-text M (equation). Using the public key, you can have the cipher text equation. This is the cipher text you send out. To decrypt the cipher message, you have equation.

Ta-da! The original message! It can also work the other way around; that is, you can encrypt the message with the private key and decrypt it using the public key. This is the beauty of mathematics at its best.

The advantage of public key encryption is the ease of key management. Everyone can publish their public keys while keeping the private keys secret. There are no security issues in this process. The disadvantage of public key encryption is that it is computationally expensive, as it needs to calculate the power of the numbers. Public key encryption cannot work on large texts.

So, in reality, public key encryption and private key encryption are often used together. A sender first uses public key encryption to set up the connection and shares a temporary session private key. This temporary session private key is randomly generated and valid only for the current session. Then the two parties will use this shared temporary session private key encryption to encrypt the subsequent messages, as illustrated in Figure 9.5.

Image described by caption and surrounding text.

Figure 9.5: Sender A first uses public key encryption to share a temporary session private key with receiver B. Then A and B can use private key encryption to encrypt all their subsequent messages using the shared temporary private key.

Figure 9.6 shows an interesting online RSA key generator (http://travistidwell.com/jsencrypt/demo/), where you can generate a pair of private and public keys of different size, give a plain-text message, and convert it into a cypher text.

Image described by caption and surrounding text.

Figure 9.6: An online RSA key generator

9.3 Hash Functions and Message Digests

A hash function is one that can turn a large, long text message into a short, fixed-length message, called a message digest, as illustrated in Figure 9.7. Hash functions and message digests are important and are widely used in cryptography. The simplest hash function is a checksum calculation, in which the long message is first cut into many small pieces of the same fixed length, and then all the pieces are added together. A hash function is a many-to-one function; and one important feature is that when the long text message changes, the short message digest will also change. With hash functions and message digests we can introduce the concept of digital signatures and digital certificates.

Image described by caption and surrounding text.

Figure 9.7: A long message is turned into a short fixed-length message digest using a hash function.

One of the most commonly used hash functions is Secure Hash Algorithm (SHA), designed by the United States National Security Agency (NSA). There are three versions: SHA-1, the original version; SHA-2, the second version, currently in use; and SHA-3, the planned newest version. SHA-2 supports hash values of 224, 256, 384, or 512 bits in length. The most commonly used are SHA-256 and SHA-512. For example, Bitcoin, the most popular cryptocurrency, uses SHA-256 for verifying transactions and calculating proof of work. More details about cryptocurrency and the use of hash functions can be found in the next chapter.

Figure 9.8 shows an interesting online SHA-256 hash generator, where you can type in the text, and it will generate corresponding hash values (https://passwordsgenerator.net/sha256-hash-generator/).

Image described by caption and surrounding text.

Figure 9.8: An online SHA256 hash generator

Another widely used hash function is the message-digest algorithm (MD5), version 5. MD5 was initially designed as a cryptographic hash function, but because of its many vulnerabilities, MD5 is commonly used as a checksum to verify data integrity. MD5 produces a 128-bit hash value. When you download files from the Internet, many web sites also provide the corresponding MD5 message digest for you to check the integrity of the downloaded files.

9.4 Digital Signatures

When you write a paper letter, you sign it at the bottom to prove that you have written the letter. So, how do you sign a digital text message? The answer is to use a digital signature, as illustrated in Figure 9.9. When sender A wants to send a long text message to receiver B, sender A uses a hash function to generate a message digest from the long text message, then uses A's private key to encrypt the message digest to create the digital signature. The combined long text and digital signature are then sent to receiver B.

Image described by caption and surrounding text.

Figure 9.9: When sender A wants to send a long text message, A uses a hash function to generate a message digest and then uses A's private key to encrypt the message digest to create the digital signature. The combined long text and digital signature are then sent to receiver B.

When receiver B receives the combined message, it first separates out the long text message and digital signature and then uses the same hash function to generate a message digest and uses A's public key to decrypt the message digest from the digital signature. Finally, receiver B compares the calculated message digest with the received message digest. If the two match, then you know the message is authentic; otherwise it is fake, as shown in Figure 9.10.

Image described by caption and surrounding text.

Figure 9.10: When receiver B receives the combined message, it first separates out the long text message and digital signature and then uses the same hash function to generate a message digest and uses A's public key to decrypt the message digest from the digital signature. Finally, receiver B compares the calculated message digest with the received message digest.

9.5 Digital Certificates

When you receive a public key from someone, how do you know it is the true public key from that person? The answer is to use digital certificates. ITU X.509, developed by International Telecommunications Union (ITU) in 1988, is the most commonly used digital certificate standard. ITU X.509 certificates are used in many Internet protocols, including Hyper Text Transfer Protocol Secure (HTTPS), which is the secure version of Hypertext Transfer Protocol (HTTP). While HTTP is for standard World Wide Web (WWW) services, HTTPS is for online banking, online shopping, and so on, where secure communications are required.

Figure 9.11 shows how ITU X.509 digital certificates work. In this case, you need a third party, called the certificate authority (CA), that both A and B can trust.

Schematic diagram depicting operation of ITU X.509 digital certificate standard with A’s Public Key, A’s Identification Information, and Certificate Authority (CA), and B.

Figure 9.11: The operation of ITU X.509 digital certificate standard

If sender A wants a signed digital certificate, sender A needs to do this via a certificate signing request (CSR), using the following steps:

  1. Sender A generates a pair of keys (a private key and a public key).
  2. Sender A sends A's identification information (name, organization, address, and so on) and A's public key to CA. A also signs this message using A's private key.
  3. The CA verifies A's information and A's public key and then uses CA's private key to generate a digital signature.
  4. The CA combines A's original message with its own signature, creating what is called a digital certificate, and sends them to receiver B.

When receiver B receives the digital certificate, receiver B will then be able to get sender A's information and public key with the CA's public key using the steps shown in Figure 9.9 earlier.

Figure 9.12 shows the contents of an ITU X.509 digital certificate.

Schematic diagram depicting contents of an ITU X.509 digital certificate with Signing ALGORITHM, CA Digital Signature, CA’s Identity, Certificate Lifetime.

Figure 9.12: The contents of an ITU X.509 digital certificate

9.6 Case Study 1: Secure Email

Next, you will look at two case studies demonstrating how to use the encryption technologies in real life. The first example is secure email. Traditional email sends and receives a message as clear, plain text. However, this is not desirable for business communications, where messages need to be sent and received securely. You can secure your emails by using Pretty Good Privacy (PGP), an encryption program that was developed by Phil Zimmermann in 1991. PGP is mainly used for encrypting, decrypting, and signing emails or files. PGP follows the OpenPGP standard (RFC 4880) for encrypting and decrypting data. In PGP, the sender uses a randomly generated key to encrypt the email (or data) and uses receiver's public key and RSA algorithm to encrypt the randomly generated key. The sender then sends both to receiver. The receiver uses its private key and RSA algorithm to decrypt the randomly generated key, and then it uses the randomly generated key to decrypt the email (or data). Figure 9.13 shows how PGP works (https://en.wikipedia.org/wiki/Pretty_Good_Privacy).

Schematic flow diagram depicting how PGP works with Encrypt and Decrypt sides to the left and right, respectively.

Figure 9.13: How PGP works

9.7 Case Study 2: Secure Web

The second example is secure web. Like email, traditional web services, built on the HTTP, use clear, plain text to send and receive messages. Again, this is not desirable for business applications such as online banking and online shopping. This is where Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), are needed. Secure web uses HTTPS based on TLS or SSL to provide secure web communications. The following are the steps.

  1. The web client sends a ClientHello message to the web server; the message contents include the highest TLS protocol version the client supports, a random number, and a list of preferred encryption methods.
  2. The web server replies with a ServerHello message, which includes the chosen TLS protocol version and the encryption method, all from the choices offered by the client. It also includes a random number and the web server's digital certificate. The digital certificate includes the web server's public key and is certified by a CA.
  3. The web server sends a ServerHelloDone message, indicating the conclusion of this initial handshake.
  4. The web client has a list of entrusted CAs and a public key for each CA. First, the web client verifies the web server's digital certificate and generates a symmetric session key. Then the web client encrypts the key with the web server's public key and sends the encrypted symmetric session key to the web server.
  5. The web server decrypts the symmetric session key using its private key.
  6. The web client sends another message to indicate that all subsequent messages will be encrypted with the symmetric session key.
  7. The web server replies with a message to confirm that all future messages will be encrypted with the same symmetric session key.
  8. The web client and web server can now securely communicate with encrypted messages.

9.8 Java Private Key Encryption Example

Example 9.1 is a Java program demonstrating encryption and decryption using a private key—a symmetric key. It is based on a code example from the following web site:

http://jexp.ru/index.php/Java_Tutorial/Security/Key_Generator

It first generates a private key based on the AES algorithm, and then encrypts and decrypts a clear text message, “Hello World.” It also displays the private key information. Figure 9.14 shows the compilation and execution of the program.

Screen capture depicting code of compilation and execution of the PrivateKeyDemo1.java program.

Figure 9.14: The compilation and execution of the PrivateKeyDemo1.java program

9.9 Java Public Key Encryption Example

Example 9.2 is a Java program demonstrating encryption and decryption using asymmetric keys. It is based on a code example from the following web site:

http://www.javacirecep.com/java-security/java-rsa-encryption-decryption-example/

It first generates a public/private key pair based on the RSA algorithm and then encrypts a clear text message, “Hello World,” using the public key, and then decrypts the message using the private key. It also displays the public/private key information. Figure 9.15 shows the compilation and execution of the program.

Screen capture depicting code of compilation and execution of the PublicKeyDemo1.java program.

Figure 9.15: The compilation and execution of the PublicKeyDemo1.java program

For more examples of using Java for asymmetric cryptography, please visit the following resources:

https://www.mkyong.com/java/java-asymmetric-cryptography-example/

https://www.devglan.com/java8/rsa-encryption-decryption-java

https://javadigest.wordpress.com/2012/08/26/rsa-encryption-example/

9.10 Java Digital Signature/Message Digest Example

Example 9.3 shows how to create a message digest using the SHA-256 hash function in Java. Figure 9.16 shows the compilation and execution of the program.

Screen capture depicting code of compilation and execution of the MessageDigestDemo1.java program.

Figure 9.16: The compilation and execution of the MessageDigestDemo1.java program

Example 9.4 shows a variation of the previous application. Here a bytesToHex() method is used to convert the message digest into hex values. Figure 9.17 shows the compilation and execution of the program.

Screen capture depicting code of compilation and execution of the MessageDigestDemo2.java program.

Figure 9.17: The compilation and execution of the MessageDigestDemo2.java program

Example 9.5 is a Java program demonstrating digital signatures. It is based on examples from the following web site:

http://tutorials.jenkov.com/java-cryptography/signature.html

It first generates a public/private key pair and uses the private key to create a digital signature based on the SHA256WithDSA algorithm and then uses the digital signature to sign a clear text message, “Hello World,” and finally uses the public key to create another digital signature to validate the original signature. This process is similar to the diagram shown in Figure 9.18 (https://en.wikipedia.org/wiki/Digital_signature).

Image described by caption and surrounding text.

Figure 9.18: Example of using digital signatures to verify a message

Figure 9.19 shows the compilation and execution of the program.

Screen capture depicting code of compilation and execution of the DigitalSignatureDemo1.java program.

Figure 9.19: The compilation and execution of the DigitalSignatureDemo1.java program

More examples of digital signatures are available from

https://www.mkyong.com/java/java-digital-signatures-example/

Figure 9.20 shows an illustrative online private key encryption demonstration tool from Tools4noobs (https://www.tools4noobs.com/online_tools/encrypt/), which has two pages, one for encrypting the message and one for decrypting the message. You can choose your key values, choose the message content, and choose the algorithms for the encryption and decryption.

Image described by caption and surrounding text.

Figure 9.20: The online private key encryption tool from Tools4noobs, which has two pages, one for encrypting the message (top) and one for decrypting the message (bottom)

Figure 9.21 shows a public-key encryption demo from the Computer Science Department of the University of Georgia in the United States (http://cobweb.cs.uga.edu/~dme/csci6300/Encryption/Crypto.html).

Screen capture depicting web page for public-key encryption demo from the Computer Science Department of the University of Georgia in the United States.

Figure 9.21: The public-key encryption demo

Figure 9.22 shows an online RSA key generator demo from Travis Tidwell, in which you can specify the key size, 512, 1024, 2048, or 4096 bits (http://travistidwell.com/jsencrypt/demo/).

Image described by caption and surrounding text.

Figure 9.22: The online RSA key generator demo

Figure 9.23 shows an interesting JavaScript-based online hash function demo, which implements the entire family of SHA hashes as defined in FIPS PUB 180-4 and FIPS PUB 202 (SHA-1, SHA-224, SHA3-224, SHA-256, SHA3-256, SHA-384, SHA3-384, SHA-512, SHA3-512, SHAKE128, and SHAKE256) (https://caligatio.github.io/jsSHA/).

Image described by caption and surrounding text.

Figure 9.23: The JavaScript-based online SHA hash function demo

9.11 Java Digital Certificate Example

Figure 9.24 shows a typical example of a digital certificate. A user provides their details and the public key to the certificate authority and gets the corresponding certificate.

Schematic diagram depicting A giving Digital certificate to B when CERTIFICATE AUTHORITY (CA) VERIFIES the INFORMATION and ENCRYPTS IT with ITS PRIVATE KEY.

Figure 9.24: The digital certificate for a user and its public key

In Java you can create a digital certificate using the keytool command from the SUN certificate authority. Take the following steps to try an example:

  1. Create a self-signed server digital certificate by typing the following command all on one line. It uses RSA to generate the public key, the server alias is LSBU, the store password is storepassword, the store type is PKCS12, and the Java key store file name is keystore.pfx. The filename extension for PKCS12 files is .pfx or .p12.
    keytool -genkey -alias LSBU -keyalg RSA -storepass storepassword -storetype PKCS12 -keystore keystore.pfx 

    When you press Enter, keytool prompts you to enter the server name, organizational unit, organization, locality, state, and country code. You must type the server name in response to keytool's first prompt, in which it asks for first and last names; in this case, it is www.lsbu.ac.uk. See Figure 9.25 for the details.

    Image described by caption and surrounding text.

    Figure 9.25: Creating a self-signed digital certificate using keytool

  2. Use the following command to verify the keystore file generated. Figure 9.26 shows the output.
    Image described by caption and surrounding text.
    Figure 9.26: Verifying the digital certificate store file using keytool
    keytool -list -v -keystore keystore.pfx -storetype pkcs12
  3. Export the generated self-signed server certificate in the keystore.pfx file into the server.cer file, as shown in Figure 9.27.
    Image described by caption and surrounding text.
    Figure 9.27: Exporting the generated self-signed server certificate in the keystore.pfx file into the server.cer file using keytool
    keytool -export -alias LSBU -storepass storepassword -file server.cer -keystore keystore.pfx -storetype pkcs12
  4. Add the server certificate to the truststore file cacerts.pfx. Type yes when prompted, and press Enter, as shown in Figure 9.28.
    Image described by caption and surrounding text.
    Figure 9.28: Adding the server certificate to the truststore file cacerts.pfx using keytool
    keytool -import -v -trustcacerts -alias LSBU -file server.cer -keystore cacerts.pfx -storepass storepassword -storetype pkcs12 

Example 9.6 shows the Java program to read information from the keystore.jks file. Figure 9.29 shows the beginning and the ending of the output of the program; the full output is too large to display.

Image described by caption and surrounding text.

Figure 9.29: The output from the PKCS12Example.java program

For more details on digital certificates using keytool, see the following Oracle article:

https://docs.oracle.com/cd/E19798-01/821-1841/gjrgy/

Figure 9.30 shows how to view the certificate of a web site in the Google Chrome browser. Just click the lock icon next to the web site URL, and select Certificate.

Image described by caption and surrounding text.

Figure 9.30: Viewing the certificate of a web site in Google Chrome browser

Figure 9.31 shows how to view a list of trusted CAs in the Google Chrome browser. From the top-right corner of the browser, select Settings ➪ Advanced ➪ Privacy And Security ➪ Manage Certificates.

Image described by caption and surrounding text.

Figure 9.31: Viewing a list of trusted CAs in Google Chrome

9.12 Other Java Examples

Here are some other Java examples:

  • The following is the web site of the book Beginning Cryptography with Java, by David Hook (Wrox, 2005). This book gives an interesting introduction to cryptography, illustrated with simple Java code, and is suitable for beginners.

www.wrox.com/WileyCDA/WroxTitle/productCd-0764596330,descCd-DOWNLOAD.html

  • The following is the corresponding GitHub web site of the book, where you can download all the Java example code:

https://github.com/boeboe/be.boeboe.spongycastle

  • The Java example code in Beginning Cryptography with Java is developed by using the Legion of the Bouncy Castle Java Cryptography APIs:

https://www.bouncycastle.org/java.html

  • The following is a comprehensive Java security tutorial from Java2S:

www.java2s.com/Tutorial/Java/0490__Security/Catalog0490__Security.htm

9.13 Summary

This chapter introduced the concept of cybersecurity, explaining key concepts such as encryption, hash functions, message digests, digital signatures, and digital certificates. You looked at both private key encryption and public key encryption. The chapter also presented some Java examples for private key encryption, public key encryption, digital signatures, a message digest, and a digital certificate. Finally, you saw some interesting Java security programming resources.

9.14 Chapter Review Questions

Q9.1.What is cybersecurity?
Q9.2.Find two recent examples of cybersecurity breaches in the news.
Q9.3.What is encryption?
Q9.4.What is private key encryption (or symmetric key encryption)?
Q9.5.What is public key encryption (or asymmetric key encryption)?
Q9.6.What is a hash function?
Q9.7.What is a message digest?
Q9.8.What is a digital signature?
Q9.9.What is a digital certificate?
Q9.10.What is PGP?
Q9.11.What is the difference between TTL and SSL?
Q9.12.What is the difference between HTTP and HTTPS?
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset