Click here to close now.


SOA & WOA Authors: David Sprott, Lori MacVittie, Carmen Gonzalez, Elizabeth White, Ian Khan

Related Topics: Java, XML, SOA & WOA, AJAX & REA, Apache, Security

Java: Article

Designing a Java Cryptography Header

Encrypt personal files, exchange confidential messages and authenticate the sender

Designing and implementing a hybrid encryption application is a big challenge but without a supporting infrastructure it's almost impossible. There are open source libraries that allow you to encrypt a file but only provide the translation technique. After the information has been encrypted, how do you know what algorithm was used, who you encrypted it, what version did you used, etc. In order to decrypt the protected message or file, a well-defined cryptographic header provides all the information required. This also applies if the encrypted data is digitally signed and the recipient wants to validate the signature.

This article will address one of the critical components of a support infrastructure by providing a design of a cryptographic header used to precede encrypted and/or digitally signed messages and files. The header is used within an application known as DocuArmor that was written using Java and the Cryptography library from the BouncyCastle organization and designed by Logical Answers Inc. The header will store information used when encrypting and/or digitally signing a message or file and allow the recipient to decrypt the information and/or verify the digital signature. With a properly designed header, a person can encrypt their personal files as well as exchange confidential messages and authenticate the sender.

Hybrid Encryption
In order to encrypt personal files and exchange protected data, we use a hybrid technique with two types of encryption, symmetric and asymmetric.

Symmetric encryption uses a single key to hide the message and reveal the message. There are several symmetric algorithms available such as AES (the Advanced Encryption Standard) but the important thing to remember is that the file can be encrypted and decrypted using the same key. An example is the Caesar cipher that shifts the letters of the alphabet by a specific number. If the shift is 2 (single key) then we get the following translation; a=c, b=d, c=e, ..., z=b.

Asymmetric encryption uses a pair of keys (public, private) to hide and reveal the message and the RSA algorithm is most commonly used. The RSA algorithm was credited in 1977 to Ronald Rivest, Adi Shamir, and Leonard Adleman. Sometimes referred to as Public Key Infrastructure (PKI), the pubic key is used to encrypt data and the private key is used to decrypt data.

Figure 1: Public and Private Key Functions

The hybrid technique uses the symmetric key to encrypt a file. The asymmetric public key is used to encrypt the symmetric key and is placed in the header. When the recipient receives an encrypted file, the encrypted symmetric key is extracted from the header. The encrypted symmetric key is decrypted using the private key. The file is decrypted using the symmetric key.

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

When two people want to exchange encrypted files, they each generate a pair of asymmetric keys and exchange a copy of their public keys. By using the other person's public key, they can encrypt a file, storing the cryptographic information in the header and then e-mail it to the recipient. The recipient will use the header to extract a symmetric key with their private key and decrypt the accompanying file. If a digital signature is included, the recipient can authenticate the sender.

Figure 2: Exchange of Encrypted Files

Cryptographic Header
When a file is encrypted, digitally signed or both, a Cryptographic header is placed in front of the resulting file and has the following structure. The structure consists of two sections, the header and the encrypted/plain file contents.

Figure 3: Encrypted File Structure

The header structure contains information required to reverse the encryption process and decrypt the contents of the file or verify the digital signature. The header contains the total length, an ID, version, and two sections containing encryption and digital signature information. Using Java, you can write out the contents of header within a byte stream as well as read it back in.

Figure 4: Cryptographic Header Structure

  • Total Len: Contains the total length of the header (stored as a 4 byte integer)
  • Header ID: Contains the string "LAHEADER" to identify the file (16 bytes)
  • Header Version: Structural version of the header (stored as a 4 byte integer)
  • Encryption Information: Holds the algorithm, mode, encrypted symmetric key, etc.
  • Digital Signature Information: Holds digital signature

Encryption Information
The Encryption Information structure contains information that was used to encrypt the contents of the file and later decrypt the file. The symmetric key and initialization vector is encrypted with the recipient's asymmetric public key. The recipient could be the owner if you are encrypting a file for yourself or another user you want to send confidential information to.

An additional field has been allocated to allow the encryption of the symmetric key with another set of asymmetric keys. For example, if owner A is sending an encrypted file to another person B, the symmetric key can be encrypted with B's public key as well as A's public key so that either person can decrypt the file.

Alternatively, an employee can encrypt a file with their public key and a corporation could insert an encrypted symmetric key into the header using their asymmetric keys. The corporation's asymmetric keys can be a Certifying Authority (CA), which can be used to issue employee keys.

Figure 5: Encryption Information Structure

  • Encrypt Flag: (Y/N - 2 bytes) specifies whether the file is encrypted.
  • Decrypt ID Length: (integer - 4 bytes) length in chars(bytes) of the Key ID.
  • Decrypt ID: (size varies) an identifier of the RSA keys used in the encryption/decryption process. It is the alias associated to the asymmetric encryption keys (e.g., JaneDoe_12ff).
  • Other Decrypt ID Length: (integer - 4 bytes) length in chars(bytes) of the Key ID.
  • Other Decrypt ID: (size varies) an identifier of the RSA keys used in the encryption/decryption process. It can be the alias or the common name (e.g., JaneDoe_12ff or Logical Answers CA).
  • Symmetric Key Algorithm: (integer - 4 bytes) specifies the symmetric key algorithm used to encrypt the file. The default value is 1=AES.
  • Symmetric Key Mode: (integer - 4 bytes) specifies the symmetric key block cipher mode used to enhance confidentiality. The default value is 5=Segmented Integer Counter mode (CTR).
  • Symmetric Key Padding: (integer - 4 bytes) specifies the type of padding for block cipher. The default value is 1=No Padding
  • Wrapped Symmetric Key Length: (integer - 4 bytes)
  • Wrapped Symmetric Key: (size varies) symmetric key used to encrypt/decrypt the file and encrypted with the asymmetric key.
  • Initialization Vector Length: (integer - 4 bytes)
  • Initialization Vector: (byte[] - size varies) vector used with the symmetric encryption process.
  • Other Wrapped Symmetric Key Length: (integer - 4 bytes)
  • Other Wrapped Symmetric Key: (size varies) symmetric key used to encrypt/decrypt the file and encrypted with another person's asymmetric key.
  • Other Initialization Vector Length: (integer - 4 bytes)
  • Other Initialization Vector: (byte[] - size varies) vector used with the symmetric encryption process.

Digital Signature Information
The Digital Signature Information structure contains information used to add or verify a digital signature generated from the contents of the file. The digital signature is generated with the owner's private key using a specific algorithm and then inserted into the header. When the recipient receives the signed file, they can use the signer's public key to validate its authenticity. If the signature is authenticated, it implies the file has not been altered and the holder of the private key generated the signature.

Figure 6: Digital Signature Information Structure

  • Signed Flag: (Y/N - 2 bytes) specifies whether the file contains a digital signature
  • Signature Algorithm: (integer - 4 bytes) specifies the algorithm used to generate the digital signature. The default value is 12= SHA512WithRSAEncryption
  • Verify Signature Cert Name Length: (integer - 4 bytes) length in chars(bytes) of the filename of the certificate used to verify a digital signature
  • Verify Signature Cert Name: (size varies) filename of the certificate holding the RSA public key used to verify the digital signature of a file (e.g., JaneDoe_fa39.cer).
  • Signature Date/Time: (long - 8 bytes) date the digital signature was generated.
  • Signature Length: (integer - 4 bytes)
  • Signature: (size varies) holds digital signature generated with RSA private key and signature engine

File Naming Conventions
The Cryptographic header holds information that designates which keys were used to encrypt a file but it's not physically accessible without reading it in first. With proper naming conventions, you can determine who the intended recipient is for encrypted files - whether it is for yourself or a colleague. When you generate your pair of asymmetric encryption keys using Java, store them in a file called a key store. The key store holds a pair of asymmetric keys as an entry with a unique alias. The alias typically consists of the initial of your first name and your last name. To make it more unique, you can extract 4 hex digits from your public key and append an underline and the hex digits to the alias. For example, if the person's name was Jane Smith, then the resulting unique alias would be jsmith_ad5e. A certificate holds a person's public key and the alias would be used in the filename, as jsmith_ad5e.cer. Similarly, the key store holding the pair of asymmetric keys would be saved as, jsmith_ad5e.jks.

Following the unique alias analogy, Jane Smith could encrypt files for herself and the file name would be appended with her alias and an appropriate file extension. For example, if Jane encrypted a personal file, myTaxes.txt, then the result would be myTaxes.txt.jsmith_ad5e.aes. If Jane wanted to send her colleague Dick an encrypted document, she would use Dick's certificate to encrypt it. If Dick's certificate is djones_9fa2, Jane could encrypt the file, comments.doc, for Dick and the resulting file would be comments.doc.djones_9fa2.aes. When Dick receives the file, he knows it is for him by recognizing his alias on the file name.

The unique alias is stored within the header. This reinforces the importance of having a well-defined Cryptographic header for implementing encryption within your applications.

A well-defined cryptographic header stores the information required to encrypt, decrypt and digitally sign a file. Along with facilitating the implementation of standard cryptographic functions, the header also provides the following benefits:

  • The header allows for the protection of personal files as well as the exchange of confidential data.
  • Using the stored digital signature, the recipient can determine if the sender is valid and whether file has been altered.
  • The header allows either the sender or recipient to decrypt the encrypted file since both would encrypt the symmetric key with their public key.
  • Using the concept of a Certifying Authority pair of asymmetric keys, a corporation, group, or family could issue pairs of asymmetric keys to their employees or members and decipher files encrypted by them in case of emergencies.
  • The header allows for using different combinations of symmetric algorithms, modes, padding and key sizes to be used to encrypt information.
  • The header version allows for enhancements to be added to the structure for implementing new functions and still support older versions.

References and Other Technical Notes
Software requirements:

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
Docker is an excellent platform for organizations interested in running microservices. It offers portability and consistency between development and production environments, quick provisioning times, and a simple way to isolate services. In his session at DevOps Summit at 16th Cloud Expo, Shannon Williams, co-founder of Rancher Labs, will walk through these and other benefits of using Docker to run microservices, and provide an overview of RancherOS, a minimalist distribution of Linux designed expressly to run Docker. He will also discuss Rancher, an orchestration and service discovery platf...
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
PubNub on Monday has announced that it is partnering with IBM to bring its sophisticated real-time data streaming and messaging capabilities to Bluemix, IBM’s cloud development platform. “Today’s app and connected devices require an always-on connection, but building a secure, scalable solution from the ground up is time consuming, resource intensive, and error-prone,” said Todd Greene, CEO of PubNub. “PubNub enables web, mobile and IoT developers building apps on IBM Bluemix to quickly add scalable realtime functionality with minimal effort and cost.”
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...
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
Every innovation or invention was originally a daydream. You like to imagine a “what-if” scenario. And with all the attention being paid to the so-called Internet of Things (IoT) you don’t have to stretch the imagination too much to see how this may impact commercial and homeowners insurance. We’re beyond the point of accepting this as a leap of faith. The groundwork is laid. Now it’s just a matter of time. We can thank the inventors of smart thermostats for developing a practical business application that everyone can relate to. Gone are the salad days of smart home apps, the early chalkb...
With several hundred implementations of IoT-enabled solutions in the past 12 months alone, this session will focus on experience over the art of the possible. Many can only imagine the most advanced telematics platform ever deployed, supporting millions of customers, producing tens of thousands events or GBs per trip, and hundreds of TBs per month. With the ability to support a billion sensor events per second, over 30PB of warm data for analytics, and hundreds of PBs for an data analytics archive, in his session at @ThingsExpo, Jim Kaskade, Vice President and General Manager, Big Data & Ana...
In the consumer IoT, everything is new, and the IT world of bits and bytes holds sway. But industrial and commercial realms encompass operational technology (OT) that has been around for 25 or 50 years. This grittier, pre-IP, more hands-on world has much to gain from Industrial IoT (IIoT) applications and principles. But adding sensors and wireless connectivity won’t work in environments that demand unwavering reliability and performance. In his session at @ThingsExpo, Ron Sege, CEO of Echelon, will discuss how as enterprise IT embraces other IoT-related technology trends, enterprises with i...
When it comes to the Internet of Things, hooking up will get you only so far. If you want customers to commit, you need to go beyond simply connecting products. You need to use the devices themselves to transform how you engage with every customer and how you manage the entire product lifecycle. In his session at @ThingsExpo, Sean Lorenz, Technical Product Manager for Xively at LogMeIn, will show how “product relationship management” can help you leverage your connected devices and the data they generate about customer usage and product performance to deliver extremely compelling and reliabl...
The Internet of Things (IoT) is causing data centers to become radically decentralized and atomized within a new paradigm known as “fog computing.” To support IoT applications, such as connected cars and smart grids, data centers' core functions will be decentralized out to the network's edges and endpoints (aka “fogs”). As this trend takes hold, Big Data analytics platforms will focus on high-volume log analysis (aka “logs”) and rely heavily on cognitive-computing algorithms (aka “cogs”) to make sense of it all.
One of the biggest impacts of the Internet of Things is and will continue to be on data; specifically data volume, management and usage. Companies are scrambling to adapt to this new and unpredictable data reality with legacy infrastructure that cannot handle the speed and volume of data. In his session at @ThingsExpo, Don DeLoach, CEO and president of Infobright, will discuss how companies need to rethink their data infrastructure to participate in the IoT, including: Data storage: Understanding the kinds of data: structured, unstructured, big/small? Analytics: What kinds and how responsiv...
Since 2008 and for the first time in history, more than half of humans live in urban areas, urging cities to become “smart.” Today, cities can leverage the wide availability of smartphones combined with new technologies such as Beacons or NFC to connect their urban furniture and environment to create citizen-first services that improve transportation, way-finding and information delivery. In her session at @ThingsExpo, Laetitia Gazel-Anthoine, CEO of Connecthings, will focus on successful use cases.
The Workspace-as-a-Service (WaaS) market will grow to $6.4B by 2018. In his session at 16th Cloud Expo, Seth Bostock, CEO of IndependenceIT, will begin by walking the audience through the evolution of Workspace as-a-Service, where it is now vs. where it going. To look beyond the desktop we must understand exactly what WaaS is, who the users are, and where it is going in the future. IT departments, ISVs and service providers must look to workflow and automation capabilities to adapt to growing demand and the rapidly changing workspace model.
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
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 (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...
Hadoop as a Service (as offered by handful of niche vendors now) is a cloud computing solution that makes medium and large-scale data processing accessible, easy, fast and inexpensive. In his session at Big Data Expo, Kumar Ramamurthy, Vice President and Chief Technologist, EIM & Big Data, at Virtusa, will discuss how this is achieved by eliminating the operational challenges of running Hadoop, so one can focus on business growth. The fragmented Hadoop distribution world and various PaaS solutions that provide a Hadoop flavor either make choices for customers very flexible in the name of opti...
The true value of the Internet of Things (IoT) lies not just in the data, but through the services that protect the data, perform the analysis and present findings in a usable way. With many IoT elements rooted in traditional IT components, Big Data and IoT isn’t just a play for enterprise. In fact, the IoT presents SMBs with the prospect of launching entirely new activities and exploring innovative areas. CompTIA research identifies several areas where IoT is expected to have the greatest impact.
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...