× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java Security: How to implement a basic cryptography

This article covers the basics of cryptography and how it is implemented in the Java programming language, and it offers example code to demonstrate the concepts.

The Java platform was designed with a robust prominence on the security level. In core Java, language itself is type-safe and provides instinctive garbage collection, enhancing the robustness of the application code. Generally a secure class loading and the authentication mechanism is required to ensure genuine Java code.

The initial version of the Java platform is created on a safe environment for running potentially un-trusted code, such as Java applets (web based technology) downloaded from an unrestricted network. As well as the platform has grown and widened its range of the deployment, the Java Security architecture has correspondingly evolved to support an expanding set of the services.

Modern security approaches

Currently the architecture includes a large set of programming interfaces (APIs), tools, and implementations of the commonly-used security techniques like algorithms, mechanisms, and protocols. This provides the developer a wide-ranging security framework for writing the applications, as well as also provides the user or administrator a set of tools to securely manage the applications. The Java security Application Programming Interfaces spans a wide range of areas. The Cryptographic and public key infrastructure (PKI) interfaces generally provides the underlying base for developing secure web applications. The Interfaces for performing the authentication and access control enables applications to protect unsanctioned access to threatened resources.

The application programming interfaces allow multiple interoperable implementations of the algorithms and other security services. The Services are implemented by the providers, which are plugged into the Java platform via a standard interface that makes it easy for applications to obtain security services without having to know anything about their implementations. This helps developers to focus on the integration part of security into their web applications, rather than understanding the complex security mechanisms. The Java platform has a number of providers that implement a core set of security services. It also allows additional custom security providers to be installed. This method enables the programmers to extend the existing platform with new security techniques and mechanisms. We will discuss the broad overview of security in the Java platform, from secure language based features to the security Application Programming Interfaces, tools, and built-in provider services, highlighting the key packages and classes where applicable. There are lots of platforms where we can implement our security level.

What are the secure programming techniques?

Now we know that there are a number of programming styles and techniques available to help and guarantee a secured application. Now we will discuss the following as two general examples.





Storing/deleting passwords

When a password is stored in a Java String object, the password will stay in our memory until it is either garbage collected or the process ends. If it is garbage collected then it will be stagnant in the free memory mountain until the memory space is reprocessed. The longer the password String stays in the memory the more helpless it is too nosy. Equal with worse, if the real memory runs very low, the operating system might page this password String to the disk's substitution space, so it is exposed to disk block snooping. To minimize (but not eliminate) these acquaintances, we should store the passwords in char arrays and zero them out after the use. (Strings are incontrovertible, so we cannot zero them out.)


Smart serialization

If the objects are consecutive for the storage or transmits any private fields which are by default contemporaneous in the stream then sensitive data is susceptible to change. We can use the temporary keyword to flag a characteristic so it is bounced in the streaming process.

Table 1: Sample showing examples

Security is integrated in JDK

Aforementioned to Java Development Kit, many safekeeping measures had to be added to the base Java code transmission as the extensions procedure. The tight U.S. export constraints required for parting of the function.

Nowadays, a new stress-free convention opens the door to tighter integration of the security features to the base of the language. The following packages are used as extensions prior to the JDK release that are now integrated into Java Development Kit. Some kids are

  1. JCE (Java Cryptography Extension)
  2. JSSE (Java Secure Sockets Extension)
  3. JAAS (Java Authentication and Authorization Service)

The Java Database Kit also introduces two new functions that are mentioned below.

  1. JGSS (Java General Security Service)
  2. CertPath API (Java Certification Path API)

Secure programming using Java platform

In the following table we will discuss the main features which are important to make Java a secure platform for application development.





No pointers

Pointer is the type of variable that can hold the address of the variable. Here no pointer is used that means the Java program cannot directly access arbitrary memory locations in the address space system.


A bytecode verifier

A byte code verifier operates after the compilation of the class. It verifies the files and authorizations for safety issues before the execution of the code. For illustration, the attempt to access an array component elsewhere the array size will be forbidden. The actual reason is that the buffers of the overflow attacks are responsible for most of the system issues which is a very imperative security feature for the developer.


Fine-grained control over resource access

The fine-grained control over supply access control is used for both applets (Web based and applications. For example, applets can be restricted from reading or writing to the file system, or can be authorized to read only from a specific directory system. This approval can be based who contracted the code and the http (Hypertext transfer protocol) address of the code source. These settings will be appearing in a java.policy file.


A large number of library functions

A large number of library functions for all the foremost cryptography, building blocks and SSL (Secure Socket Layer) are available. In accumulation, numerous third-party collections are accessible for the supplementary algorithms.

Table 2: Java security features

Code signing example execution

In the following example we will discuss the basic structure .Following is the code which is the Hyper Text Markup Language for this program.

Listing 1: Sample code showing security implementation

  <title> Hello Mrbool </title>
  <base code="mrbool.class" archive="mrbool.jar" width=150 height=25>

After writing the program we can execute this specimen with a browser that uses the Java plug-in as the Java virtual machine, a dialog box pops up enquiring if the user wants to install and run the signed application distributed by "Mrbool User", and also declares that the originator authenticity is verified by "Company, Inc.", nevertheless that the security was issued by a company that is not secure or trusted. The security certificate has not expired and is still valid. It attentions that “Mrbool User" emphasizes that this content is safe and secure should only be installed or viewed if you trust " Mrbool User" to make that assertion. The user is specified with the following options that are like:

  • Grant this session
  • Deny
  • Grant always
  • View certificate

Secure Sockets Layer/Transport Layer Security

The Secure Sockets Layer (SSL) and its auxiliary, the Transport Layer (Part of the OSI Model) Security (TLS), is a protocol for establishing a secure communications channel between a client and a server. It is also used to substantiate the server to the client and, less generally, used to authenticate the client to the server. Basically it is usually seen in a browser based application system, where the lock at the bottom of the browser (Internet accessing Software) window indicates SSL/TLS is in effect. The TLS 1.0 is the same as SSL 3.1. SSL/TLS uses an amalgam of three of the cryptographic building blocks. Here is a shortened version of the protocol:

  • At the time when a request is made to a site using SSL/TLS (usually with an https:// Uniform Resource Locator), a certificate is sent from the server to the client. The client first verifies the identity of the requesting server from this certificate using the installed public CA certificates, and then checks that the Internet Protocol name (machine name) matches the machine that the client is connected to.
  • The client generates some haphazard info that can be used to generate a private key for the discussion, we known as a session key, and also encrypts it with the server's public key and sends it to the server system. The server decrypts the message with its private key and also uses the random info to derive the same private session key as the client. The RSA public key process is usually used for this particular segment.
  • The client and server then communicate using the private session key and a private key algorithm, usually the RC4. A message-authentication code, using though another key, is used to warrant the integrity of the messaging system.

SSL/TLS code sample

However Now I will discuss an example. We will write an HTTPS daemon process using an SSL server socket that will return an HTML stream when a browser connects to it. This illustration also shows how to engender a machine certificate in a special keystone to support the SSL deployment.

In the base of the Java programming model, the only thing that needs to be done is to use an SSL Server Socket. The factory instead of a Socket Factory that uses lines like below:

  SSLServerSocketFacctory sslf =

Listing 2: Following is the complete code example.

  import java.io.*;
  import java.net.*;
  import javax.net.ssl.*;
  // Example of an Hypertext transfer protocol Security server to illustrate //Secure Socket Layer certificate and socket
  public class HTTPSServerepro 
  public static void main(String[] args) throws IOException 
  // SSL socket created using the factory and port 8080
  SSLServerSocketFactory sslsf =(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
  ServerSocket ss = sslsf.createServerSocket(8080);
  // loop forever
  while (true) 
  //block and wait for the client system connection
  Socket s = ss.accept();
  System.out.println( "Here the Client connection made" );
  // get client request
  BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
  // make an HTML response
  PrintWriter out = new PrintWriter(s.getOutputStream() );
  out.println("<html><head><title> Hypertext transfer protocol security example</title>" +"</head><body><h1> Hello Mrbool!</h1></body></html>\n");
  // Here close the stream and socket part
  } catch (Exception e) 

This above program is using client server accessing connection model or process.

HTTPS Server Sample Execution

We have created a Hypertext transfer protocol Security server that basically waits for a client browser connection and returns "Mrbool, World!”. This browser can also connect to this daemon through https://localhost:8080 or First, create a machine certificate and the name must match with the machine name of the computer wherever the daemon runs. For that particular situation the localhost or is used. We must have used it in the previous section as per our requirement. We need to create a detached keystore just for the machine certificate system. In the particular situation, it has the name like sslKeyStone.

c:\bcei>keytool -genkey -v -keyalg RSA -alias MachineCert

We become accustomed with such Java security and as well as we must discuss all types of the tools as per our working area.





Built-in features that facilitate secure programming

There are no pointers, a bytecode verifier; fine-grained control is present inside it for accessing applications. A large number of library functions are also available for all the major cryptographic building blocks and Secure Socket Layer).


Secure programming techniques

The proper storage and the deletion of the passwords and brainy series.


Features newly integrated in Java Development Kit

(JCE, JSSE, JAAS, JGSS, and CertPath API).


Enriching, third-party security offerings

Basically following concepts are implemented here:

  • Message digests
  • Message authentication codes
  • Private key cryptography
  • Public key cryptography
  • Digital signatures
  • Digital certificates
  • Certification authorities and paths
  • Code signing

Table 3: Sample showing tools


Authentication is a major part of the standard java Security process for determining the identity of a user. In Java runtime environment, that is the procedure of identifying the user of an implementing Java program. In such types of cases this process may depend on the services described in the “Cryptography”. The Java platform provides Application Programming Interfaces that enable to accomplish user authentication via pluggable login system modules. The Applications can call into the LoginContext class in the javax.security.auth.login package,which in turn refer a configuration. This configuration specifies the login in the module (an enactment of the javax.security.auth.spi.LoginModule interface) which is to be used to accomplish the concrete authentication process.

Nowadays subsequently the applications solely talk to the standard LoginContext Application Programming Interface. They can also remain independent from the underlying plug-in modules. The new or updated modules can be persevered in for a submission without having to modify the application itself. The following figure 1 demonstrates the unconventionality amongst submissions and fundamental login of the modules. It is very significant to note that although these login modules are pluggable to the components that can be constructed into the Java platform; they are not persevered in via sanctuary providers. Consequently they do not track the supplier-penetrating model. Now in the following figure, login modules are administered by their own irreplaceable conformation. The Java stage also delivers the following built-in LoginModules, all in the com.sun.security.auth. Module.


It is for the authentication using Kerberos protocols


It is for the username/password authentication using LDAP or NIS databases process.


It is for logging into any type of key stores. It also includes PKCS#11 token Keystore.

Table 4: Showing different authentications

Now the Authentication can also be achieved during the process of establishing a protected communicating channel between two peers. Basically the Java platform provides executions of a number of standard communication protocols.

Figure 1: Authentication login modules plugging into the authentication framework


The Java language is designed to support the safe accomplishment of web applications. The non-attendance of a well-defined as well as formal safekeeping procedure to prevent the corroboration of an application is very dangerous for any web application. We understand that the Java platform in its current form cannot easily be made protected or secure. The most significant redesign of the language, the bytecode presentation, and the runtime system appears to be compulsory steps toward building a highly secured system. Now without a formal basis, statements about a system’s safekeeping cannot be determined. The presence of the flaws in the Java does not suggest that the competing systems are more secure or protected. So the new approached have been introduced to make the Java platform more secure and stable. Hope you have understood the basic concepts of security implementation and will be able to implement it in your project.

Keep following Mrbool!!

Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login