Web 2.0 Authors: Liz McMillan, Sandeep Kumar, Bob Gourley, Elizabeth White, Jnan Dash

Related Topics: Java, SOA & WOA, AJAX & REA, Web 2.0, Oracle, Security, SDN Journal

Java: 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.

@ThingsExpo Stories
The Internet of Things (IoT) promises to evolve the way the world does business; however, understanding how to apply it to your company can be a mystery. Most people struggle with understanding the potential business uses or tend to get caught up in the technology, resulting in solutions that fail to meet even minimum business goals. In his session at @ThingsExpo, Jesse Shiah, CEO / President / Co-Founder of AgilePoint Inc., showed what is needed to leverage the IoT to transform your business. He discussed opportunities and challenges ahead for the IoT from a market and technical point of vie...
IoT is still a vague buzzword for many people. In his session at @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, discussed the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. He also discussed how IoT is perceived by investors and how venture capitalist access this space. Other topics discussed were barriers to success, what is new, what is old, and what the future may hold. Mike Kavis is Vice President & Principal Cloud Architect at Cloud Technology Pa...
Dale Kim is the Director of Industry Solutions at MapR. His background includes a variety of technical and management roles at information technology companies. While his experience includes work with relational databases, much of his career pertains to non-relational data in the areas of search, content management, and NoSQL, and includes senior roles in technical marketing, sales engineering, and support engineering. Dale holds an MBA from Santa Clara University, and a BA in Computer Science from the University of California, Berkeley.
The Internet of Things (IoT) is rapidly in the process of breaking from its heretofore relatively obscure enterprise applications (such as plant floor control and supply chain management) and going mainstream into the consumer space. More and more creative folks are interconnecting everyday products such as household items, mobile devices, appliances and cars, and unleashing new and imaginative scenarios. We are seeing a lot of excitement around applications in home automation, personal fitness, and in-car entertainment and this excitement will bleed into other areas. On the commercial side, m...
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
An entirely new security model is needed for the Internet of Things, or is it? Can we save some old and tested controls for this new and different environment? In his session at @ThingsExpo, New York's at the Javits Center, Davi Ottenheimer, EMC Senior Director of Trust, reviewed hands-on lessons with IoT devices and reveal a new risk balance you might not expect. Davi Ottenheimer, EMC Senior Director of Trust, has more than nineteen years' experience managing global security operations and assessments, including a decade of leading incident response and digital forensics. He is co-author of t...
Performance is the intersection of power, agility, control, and choice. If you value performance, and more specifically consistent performance, you need to look beyond simple virtualized compute. Many factors need to be considered to create a truly performant environment. In his General Session at 15th Cloud Expo, Harold Hannon, Sr. Software Architect at SoftLayer, discussed how to take advantage of a multitude of compute options and platform features to make cloud the cornerstone of your online presence.
SYS-CON Media announced that Splunk, a provider of the leading software platform for real-time Operational Intelligence, has launched an ad campaign on Big Data Journal. Splunk software and cloud services enable organizations to search, monitor, analyze and visualize machine-generated big data coming from websites, applications, servers, networks, sensors and mobile devices. The ads focus on delivering ROI - how improved uptime delivered $6M in annual ROI, improving customer operations by mining large volumes of unstructured data, and how data tracking delivers uptime when it matters most.
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. 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 wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, discussed how for this to be effective you not only need to have infrastructure and operational models capable of utilizing this new phenomenon, but increasingly service providers will need to convince a skeptical public to participate. Get ready to show them the money!
How do APIs and IoT relate? The answer is not as simple as merely adding an API on top of a dumb device, but rather about understanding the architectural patterns for implementing an IoT fabric. There are typically two or three trends: Exposing the device to a management framework Exposing that management framework to a business centric logic Exposing that business layer and data to end users. This last trend is the IoT stack, which involves a new shift in the separation of what stuff happens, where data lives and where the interface lies. For instance, it's a mix of architectural styles ...
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The Internet of Things will put IT to its ultimate test by creating infinite new opportunities to digitize products and services, generate and analyze new data to improve customer satisfaction, and discover new ways to gain a competitive advantage across nearly every industry. In order to help corporate business units to capitalize on the rapidly evolving IoT opportunities, IT must stand up to a new set of challenges. In his session at @ThingsExpo, Jeff Kaplan, Managing Director of THINKstrategies, will examine why IT must finally fulfill its role in support of its SBUs or face a new round of...
The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

Advanced Persistent Threats (APTs) are increasing at an unprecedented rate. The threat landscape of today is drastically different than just a few years ago. Attacks are much more organized and sophisticated. They are harder to detect and even harder to anticipate. In the foreseeable future it's going to get a whole lot harder. Everything you know today will change. Keeping up with this changing landscape is already a daunting task. Your organization needs to use the latest tools, methods and expertise to guard against those threats. But will that be enough? In the foreseeable future attacks w...
As enterprises move to all-IP networks and cloud-based applications, communications service providers (CSPs) – facing increased competition from over-the-top providers delivering content via the Internet and independently of CSPs – must be able to offer seamless cloud-based communication and collaboration solutions that can scale for small, midsize, and large enterprises, as well as public sector organizations, in order to keep and grow market share. The latest version of Oracle Communications Unified Communications Suite gives CSPs the capability to do just that. In addition, its integration ...