Microservices Expo Authors: Liz McMillan, Elizabeth White, Pat Romanski, Astadia CloudGPS, Automic Blog

Related Topics: Java IoT, Microservices Expo, Machine Learning , Agile Computing, Recurring Revenue, Cloud Security, SDN Journal

Java IoT: Article

Java Cryptography | Part 3

Decryption and verifying signatures

After you have secured your private electronic information using encryption and learned how to encrypt and digitally sign files for others, how do you extract the information and determine who encrypted the file? Asymmetric public/private key encryption allows you to decipher the information and verify the accompanying digital signature if it exists.

This article illustrates how to decrypt and verify the digital signature on files encrypted using a hybrid combination of asymmetric public/private key encryption and symmetric encryption. A symmetric key is used to encrypt the file and the asymmetric public key encrypts the symmetric key. The asymmetric private key decrypts the symmetric key which in turn is used to decrypt the encrypted file.

Figure1: Asymmetric Key Encryption Functions

The same pair of keys can be used with digital signatures. The private key is used to sign a file and generate a digital signature. The public key is used to verify the authenticity of the signature.

Figure 2: Asymmetric Key Signature Functions

The decryption technique requires the Java libraries developed by the Legion of the Bouncy Castle (www.bouncycastle.org). The Bouncy Castle jars, bcprov-jdk15on-147.jar and bcpkix-jdk15on-147.jar, contains all the methods required to encrypt, decrypt, sign and verify a digital signature. The following Java code snippet loads the BouncyCastle provider, which implements the Java Cryptography Security services such as algorithms and key generation.

import org.bouncycastle.jce.provider.*;
java.security.Security.addProvider(new BouncyCastleProvider());

Decryption for Files or Java Objects
Once a file has been encrypted and/or signed using the DocuArmor application, it can be deciphered by the owner of the matching asymmetric private key. The process involves reading the header, extracting the symmetric key and deciphering the appended encrypted data. The following steps along with the Java code snippets illustrate the process used to decrypt an encrypted file.

Step 1: Assume you want to decrypt the encrypted file, C:\sampleFile.txt.jxdoe_nnnn.asg and the String variable, tUniqueAlias = "jxdoe_nnnn", holds the alias associated to the encrypted file. Read the header from the encrypted file and determine decrypted output name.

File tSrcFile = new File("C:\\sampleFile.txt." + tUniqueAlias + ".aes");
String tDecryptFile = tSrcFile.getName();
tDecryptFile = tDecryptFile.substring(0, tDecryptFile.lastIndexOf('.'));
tDecryptFile = tDecryptFile.substring(0, tDecryptFile.lastIndexOf('.'));
OutputStream tFileOStream = new FileOutputStream(tDecryptFile);
DataInputStream tDInStream =
new DataInputStream(new FileInputStream(tSrcFile));
Object tRC = CryptoHeader.readHeader(tDInStream);
CryptoHeader tHead = (CryptoHeader)tRC;

Step 2: The private key is stored in a Java key store and is password protected. Load the key store using your password. Retrieve the asymmetric private key from the key store using the same password. The asymmetric private key will be used to decrypt the symmetric key.

FileInputStream tFIStream = new FileInputStream("C:\\jxdoe_nnnn.jks");
KeyStore tMyKStore = KeyStore.getInstance("JKS", "SUN");
char[] tPW = "password".toCharArray();
tMyKStore.load(tFIStream, tPW);
PrivateKey tPrivKey = (PrivateKey)tMyKStore.getKey("jxdoe_nnnn", tPW);

Figure 3: Private Key

Step 3: Generate a Java Cipher object using the asymmetric private key and set its mode to "Cipher.UNWRAP_MODE".

Cipher tCipherRSA = Cipher.getInstance("RSA", "BC");
tCipherRSA.init(Cipher.UNWRAP_MODE, (PrivateKey)tPrivKey);

Step 4: Use the Java Cipher and asymmetric private key to unwrap the symmetric key. It's located in the header at the instance variable, wrappedSymKey or wrappedSymKeyOther, along with symmetric algorithm at symKeyAlgDesc. The symmetric key will be used to decrypt the file.

String tAlg = tHead.symKeyAlgDesc();
Key tSymmetricKey =
tCipherRSA.unwrap(tHead.wrappedSymKey(),tAlg, Cipher.SECRET_KEY);

Figure 4: Unwrap Symmetric Key

Step 5: Re-initialize the same Cipher to Cipher.DECRYPT_MODE. Use the Cipher and the asymmetric private key to decrypt the initialization vector stored within the header at the instance variable initVector or initVectorOther.

tCipher.init(Cipher.DECRYPT_MODE, (PrivateKey)tPrivKey);
byte[] tInitVector = tCipher.doFinal(tHead.initVector());
IvParameterSpec tIvParmSpec = new IvParameterSpec(tInitVector);

Figure 5: Unwrap Initialization Vector

Step 6: Generate a Java Cipher object using the symmetric key and initialization vector and set its mode to "Cipher.DECRYPT_MODE". The string representing the symmetric algorithm, mode and padding can be extracted from the Cryptography header using the "transformation" method.

tCipherDecrypt = Cipher.getInstance("AES/CTR/PKCS7Padding", "BC");
or tCipherDecrypt = Cipher.getInstance(tHead.transformation(), "BC");
tCipherDecrypt.init(Cipher.DECRYPT_MODE, tSymmetricKey, tIvParmSpec);

Step 7: Use the Java Cipher to decrypt the rest of the file to a Java FileOutputStream. The DataInputStream points to the start of the encrypted data after reading the header. The end result is a decrypted file.

byte[] tInBuffer = new byte[4096];
byte[] tOutBuffer = new byte[4096];
int tNumOfBytesRead = tDInStream.read(tInBuffer);
while (tNumOfBytesRead == tInBuffer.length) {
//-Encrypt the input buffer data and store in the output buffer
int tNumOfBytesUpdated =
tCipherDecrypt.update(tInBuffer, 0, tInBuffer.length, tOutBuffer);
tFileOStream.write(tOutBuffer, 0, tNumOfBytesUpdated);
tNumOfBytesRead = tDInStream.read(tInBuffer);
//-Process the remaining bytes in the input file.
if (tNumOfBytesRead > 0) {
tOutBuffer = tCipherDecrypt.doFinal(tInBuffer, 0, tNumOfBytesRead);
} else {
tOutBuffer = tCipherDecrypt.doFinal();
tFileOStream.write(tOutBuffer, 0, tOutBuffer.length);

Figure 6: Decipher the Encrypted File

Step 7a: If the encrypted file contains a Java object, use the Java Cipher to decrypt the rest of the file to a Java ByteArrayOutputStream instead of a FileOutputStream. The end result can be converted to an instance of its original Java class.

ByteArrayInputStream tBAIS = new ByteArrayInputStream(tBAOS.toByteArray());  
ObjectInput tOIS = new ObjectInputStream(tBAIS);
Object tObject = tOIS.readObject();  //-Original Java object

Alternatively, the same technique can be used to decrypt the encrypted file using the symmetric key that was wrapped with the CA or owner's asymmetric public key. If the file was encrypted for another user, the owner can decrypt it using the additionally wrapped symmetric key. If the file was encrypted for oneself, the CA can decrypt it using the additionally wrapped symmetric key in the enterprise version.

Signature Verification
When a file has been digitally signed with a user's asymmetric private key, the signature is stored in the Cryptography header. The signature can be validated with the user's matching asymmetric public key stored in a certificate. The process involves reading the header, extracting the digital signature and validating it against the rest of the signed file and the asymmetric public key. The following steps describe the process used to verify a digital signature.

Step 1: Assume you want to verify the signature on the encrypted and digitally signed file, "C:\sampleFile.txt.jxdoe_nnnn.asg" and the String variable, tUniqueAlias = "jxdoe_nnnn", holds the alias associated to the file. Read the header from the signed file. After the header is read, keep in mind that the DataInputStream now points to the beginning of the encrypted data.

File tSrcFile = new File("C:\\sampleFile.txt." + tUniqueAlias + ".asg");
DataInputStream tDInStream =
new DataInputStream(new FileInputStream(tSrcFile));
Object tRC = CryptoHeader.readHeader(tDInStream);
CryptoHeader tHead = (CryptoHeader)tRC;
byte[] tCurrSignature = tHead.signature();

Step 2: Retrieve the certificate whose name is stored in the header and contains the asymmetric public key needed for verification. Retrieve the asymmetric public key from the certificate associated with the digital signature.

String tCertName = "C:\\" + tHead.verifySigCertName();
InputStream tInStream = new FileInputStream(tCertName);
CertificateFactory tFactory = CertificateFactory.getInstance("X.509","BC");
X509Certificate tCert =
PublicKey tPubKey = tCert.getPublicKey();

Figure 7: Extract Public Key

Step 3: Instantiate a Java signature engine and initialize it with the signature algorithm stored in the header and the asymmetric public key. The default value is "SHA512WithRSAEncryption".

Signature tSgnVerifyEngine = null;
String tSigAlg = tHead.signatureAlgDesc();
tSgnVerifyEngine = Signature.getInstance(tSigAlg,"BC");

Step 4: Use the Java signature engine to process the rest of the signed file and calculate a hash number that will be compared with the signature stored in the header.

int tBlockSize = 4096;
byte[] tBuffer = new byte[tBlockSize];
int tLength = tDInStream.read(tBuffer);
while (tLength == tBlockSize) {
tSgnVerifyEngine.update(tBuffer, 0, tBlockSize);
tLength = tDInStream.read(tBuffer);

if (tLength > 0) {
tSgnVerifyEngine.update(tBuffer, 0, tLength);

Step 5: After the file has been processed, use the Java signature engine to verify its result with the digital signature. A Boolean result is returned on whether the signature was valid.

Boolean tResult = tSgnVerifyEngine.verify(tCurrSignature);

The article demonstrates how to decrypt and verify the digit signature of and encrypted file using Java Cryptography methods and the Cryptography libraries from Bouncy Castle organization. Using the information provided within the Cryptography header, the user can validate who encrypted its contents and/or decipher the encrypted file. The header also provides the flexibility to expand the usage of Cryptography such as allowing multiple recipients to decrypt a file by using each of their public keys to encrypt the same symmetric key. As society adopts file encryption as a standard way of protection, more creative uses will be invented by future Cyber warriors.

The source code (LaCryptoJarSample.java) is available on the Logical Answers Inc. website under the education web page as an individual file and also within the zip file, laCrypto-4.2.0.zipx.

References and Other Technical Notes
Software requirements:

  • Computer running Windows XP or higher...
  • Java Runtime (JRE V1.7 or higher)

Recommended reading:

  • "Beginning Cryptography with Java" by David Hook.
  • "The Code Book" by Simon Singh

More Stories By James H. Wong

James H. Wong has been involved in the technology field for over 30 years and has dual MS degrees in mathematics and computer science from the University of Michigan. He worked for IBM for almost 10 years designing and implementing software. Founding Logical Answers Corp in 1992, he has provided technical consulting/programming services to clients, providing their business with a competitive edge. With his partner they offer a Java developed suite of “Secure Applications” that protect client’s data using the standard RSA (asymmetric) and AES (symmetric) encryption algorithms.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

@MicroservicesExpo Stories
"We focus on SAP workloads because they are among the most powerful but somewhat challenging workloads out there to take into public cloud," explained Swen Conrad, CEO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"As we've gone out into the public cloud we've seen that over time we may have lost a few things - we've lost control, we've given up cost to a certain extent, and then security, flexibility," explained Steve Conner, VP of Sales at Cloudistics,in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"Peak 10 is a hybrid infrastructure provider across the nation. We are in the thick of things when it comes to hybrid IT," explained , Chief Technology Officer at Peak 10, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"I think DevOps is now a rambunctious teenager – it’s starting to get a mind of its own, wanting to get its own things but it still needs some adult supervision," explained Thomas Hooker, VP of marketing at CollabNet, in this SYS-CON.tv interview at DevOps Summit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"I will be talking about ChatOps and ChatOps as a way to solve some problems in the DevOps space," explained Himanshu Chhetri, CTO of Addteq, in this SYS-CON.tv interview at @DevOpsSummit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
In his session at 20th Cloud Expo, Mike Johnston, an infrastructure engineer at Supergiant.io, discussed how to use Kubernetes to set up a SaaS infrastructure for your business. Mike Johnston is an infrastructure engineer at Supergiant.io with over 12 years of experience designing, deploying, and maintaining server and workstation infrastructure at all scales. He has experience with brick and mortar data centers as well as cloud providers like Digital Ocean, Amazon Web Services, and Rackspace. H...
Your homes and cars can be automated and self-serviced. Why can't your storage? From simply asking questions to analyze and troubleshoot your infrastructure, to provisioning storage with snapshots, recovery and replication, your wildest sci-fi dream has come true. In his session at @DevOpsSummit at 20th Cloud Expo, Dan Florea, Director of Product Management at Tintri, provided a ChatOps demo where you can talk to your storage and manage it from anywhere, through Slack and similar services with...
If you are thinking about moving applications off a mainframe and over to open systems and the cloud, consider these guidelines to prioritize what to move and what to eliminate. On the surface, mainframe architecture seems relatively simple: A centrally located computer processes data through an input/output subsystem and stores its computations in memory. At the other end of the mainframe are printers and terminals that communicate with the mainframe through protocols. For all of its apparen...
DevOps at Cloud Expo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to w...
With continuous delivery (CD) almost always in the spotlight, continuous integration (CI) is often left out in the cold. Indeed, it's been in use for so long and so widely, we often take the model for granted. So what is CI and how can you make the most of it? This blog is intended to answer those questions. Before we step into examining CI, we need to look back. Software developers often work in small teams and modularity, and need to integrate their changes with the rest of the project code b...
There is a huge demand for responsive, real-time mobile and web experiences, but current architectural patterns do not easily accommodate applications that respond to events in real time. Common solutions using message queues or HTTP long-polling quickly lead to resiliency, scalability and development velocity challenges. In his session at 21st Cloud Expo, Ryland Degnan, a Senior Software Engineer on the Netflix Edge Platform team, will discuss how by leveraging a reactive stream-based protocol,...
Many organizations are now looking to DevOps maturity models to gauge their DevOps adoption and compare their maturity to their peers. However, as enterprise organizations rush to adopt DevOps, moving past experimentation to embrace it at scale, they are in danger of falling into the trap that they have fallen into time and time again. Unfortunately, we've seen this movie before, and we know how it ends: badly.
SYS-CON Events announced today that Calligo has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Calligo is an innovative cloud service provider offering mid-sized companies the highest levels of data privacy. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalized support service from its globally located cloud platfor...
"Outscale was founded in 2010, is based in France, is a strategic partner to Dassault Systémes and has done quite a bit of work with divisions of Dassault," explained Jackie Funk, Digital Marketing exec at Outscale, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
From personal care products to groceries and movies on demand, cloud-based subscriptions are fulfilling the needs of consumers across an array of market sectors. Nowhere is this shift to subscription services more evident than in the technology sector. By adopting an Everything-as-a-Service (XaaS) delivery model, companies are able to tailor their computing environments to shape the experiences they want for customers as well as their workforce.
If you read a lot of business and technology publications, you might think public clouds are universally preferred over all other cloud options. To be sure, the numbers posted by Amazon Web Services (AWS) and Microsoft’s Azure platform are nothing short of impressive. Statistics reveal that public clouds are growing faster than private clouds and analysts at IDC predict that public cloud growth will be 3 times that of private clouds by 2019.
"DivvyCloud as a company set out to help customers automate solutions to the most common cloud problems," noted Jeremy Snyder, VP of Business Development at DivvyCloud, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"At the keynote this morning we spoke about the value proposition of Nutanix, of having a DevOps culture and a mindset, and the business outcomes of achieving agility and scale, which everybody here is trying to accomplish," noted Mark Lavi, DevOps Solution Architect at Nutanix, in this SYS-CON.tv interview at @DevOpsSummit at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
For over a decade, Application Programming Interface or APIs have been used to exchange data between multiple platforms. From social media to news and media sites, most websites depend on APIs to provide a dynamic and real-time digital experience. APIs have made its way into almost every device and service available today and it continues to spur innovations in every field of technology. There are multiple programming languages used to build and run applications in the online world. And just li...
Data reduction delivers compelling cost reduction that substantially improves the business case in every cloud deployment model. No matter which cloud approach you choose, the cost savings benefits from data reduction should not be ignored and must be a component of your cloud strategy. IT professionals are finding that the future of IT infrastructure lies in the cloud. Data reduction technologies enable clouds — public, private, and hybrid — to deliver business agility and elasticity at the lo...