AJAX & REA Authors: Liz McMillan, Elizabeth White, David H Deans, Pat Romanski, Scott Hirsch

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.

@CloudExpo Stories
Software-driven innovation is becoming a primary approach to how businesses create and deliver new value to customers. A survey of 400 business and IT executives by the IBM Institute for Business Value showed businesses that are more effective at software delivery are also more profitable than their peers nearly 70 percent of the time (1). DevOps provides a way for businesses to remain competitive, applying lean and agile principles to software development to speed the delivery of software that ...

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

"Our premise is Docker is not enough. That's not a bad thing - we actually love Docker. At ActiveState all our products are based on open source technology and Docker is an up-and-coming piece of open source technology," explained Bart Copeland, President & CEO of ActiveState Software, in this SYS-CON.tv interview at DevOps Summit at Cloud Expo®, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
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...
Infor has announced a new feature Infor CloudSuite™ Aerospace & Defense (A&D) to aid compliance with International Traffic in Arms Regulations (ITAR). The ITAR function will serve as a complementary function for new or existing Infor CloudSuite A&D customers, to facilitate compliance for Infor customers that are creating a US defense article or performing a US defense service and wish to benefit from cloud-services. The ITAR regulation serves to manage handling and access requirements for dat...
What do a firewall and a fortress have in common? They are no longer strong enough to protect the valuables housed inside. Like the walls of an old fortress, the cracks in the firewall are allowing the bad guys to slip in - unannounced and unnoticed. By the time these thieves get in, the damage is already done and the network is already compromised. Intellectual property is easily slipped out the back door leaving no trace of forced entry. If we want to reign in on these cybercriminals, it's hig...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The 3rd International @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 it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to th...
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover ...
Cochlear Limited, the global leader in implantable hearing solutions, has selected AppZero for easy migration of its Microsoft Windows Server 2003 applications, a major priority for IT organizations before Microsoft ends support on July 14, 2015. AppZero software enables server application migration from old operating systems to new platforms or clouds and has been proven to be ten times faster, more reliable and efficient than alternative approaches.
Fundamentally, SDN is still mostly about network plumbing. While plumbing may be useful to tinker with, what you can do with your plumbing is far more intriguing. A rigid interpretation of SDN confines it to Layers 2 and 3, and that's reasonable. But SDN opens opportunities for novel constructions in Layers 4 to 7 that solve real operational problems in data centers. "Data center," in fact, might become anachronistic - data is everywhere, constantly on the move, seemingly always overflowing. Net...
SYS-CON Media announced today the IBM, which offers the world’s deepest portfolio of technologies and expertise that are transforming the future of work, has launched ad campaigns on SYS-CON’s numerous online magazines such as Cloud Computing Journal, DevOps Journal, Virtualization Journal, and IoT Journal. IBM's campaigns focus on application testing, improving application development processes, common challenges in testing composite applications, continuous testing as part of the DevOps lifec...
To manage complex web services with lots of calls to the cloud, many businesses have invested in Application Performance Management (APM) and Network Performance Management (NPM) tools. Together APM and NPM tools are essential aids in improving a business's infrastructure required to support an effective web experience... but they are missing a critical component - Internet visibility. Internet connectivity has always played a role in customer access to web presence, but in the past few years u...
In her General Session at 15th Cloud Expo, Anne Plese, Senior Consultant, Cloud Product Marketing, at Verizon Enterprise, focused on finding the right mix of renting vs. buying Oracle capacity to scale to meet business demands, and offer validated Oracle database TCO models for Oracle development and testing environments. Anne Plese is a marketing and technology enthusiast/realist with over 19+ years in high tech. At Verizon Enterprise, she focuses on driving growth for the Verizon Cloud platfo...
As cloud gives an opportunity to businesses to buy services externally – how is cloud impacting your customers? In his General Session at 15th Cloud Expo, Fabio Gori, Director of Worldwide Cloud Marketing at Cisco, provided answers to big questions: Do you see hybrid cloud as where the world is going? What benefits does it bring? And how does Cisco connect all of these clouds? He also discussed Intercloud and Cisco’s investment on it.
SYS-CON Events announced today that AIC, a leading provider of OEM/ODM server and storage solutions, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. AIC is a leading provider of both standard OTS, off-the-shelf, and OEM/ODM server and storage solutions. With expert in-house design capabilities, validation, manufacturing and production, AIC's broad selection of products are highly flexible and are conf...
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, p...
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada...
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 th...
Agility is top of mind for Cloud/Service providers and Enterprises alike. Policy Driven Data Center provides a policy model for application deployment by decoupling application needs from the underlying infrastructure primitives. In his session at 15th Cloud Expo, David Klebanov, a Technical Solutions Architect with Cisco Systems, discussed how it differentiates from the software-defined top-down control by offering a declarative approach to allow faster and simpler application deployment. Davi...