Microservices Expo Authors: Elizabeth White, Liz McMillan, Sematext Blog, David Green, Pat Romanski

Related Topics: Java IoT, Industrial IoT, Microservices Expo, IoT User Interface, Recurring Revenue, Cloud Security

Java IoT: Article

Java Cryptography | Part 2

Encryption and Digital Signatures

In today's environment, information security is crucial for everyone. Security needs vary widely from protecting social security numbers to guarding corporate strategy. Information espionage can occur at all levels. A human resources employee or manager takes employee personnel files home to work on them and unfortunately loses them or they get stolen. An employee's notes to a supervisor regarding a case are intercepted and read via monitoring software by an outside hacker. The resulting damages can be costly and could be avoided by protecting assets with encryption technology.

This article demonstrates the implementation of the Cryptography header cited in the previous article and illustrates how to encrypt and digitally sign files 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.

Figure 1. Asymmetric Key Encryption Functions

The same pair of encryption 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. The encrypted symmetric key and digital signature along with additional information are stored in the Cryptography header which is affixed to the front of the encrypted file.

Figure 2. Asymmetric Key Signature Functions

The encryption 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, contain 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());

Generating Public/Private Encryption Keys
A Java key store is a password protected file that contains the user's pair of asymmetric encryption keys and certificate. Each key store associates a unique alias to each pair of encryption keys it contains. The Java key store file name is generated as alias_nnnn.jks, for example, jxdoe_fc99.jks. Certificates hold the public encryption key that allows a file to be encrypted for a specific individual who holds the matching deciphering key. The following steps along with Java code snippets illustrate how to generate the pair of public/private keys and store them in a key store file, using the Bouncy Castle cryptography library.

Figure 3. Pair of Asymmetric Keys

Step 1: Create an instance of the KeyPairGenerator class specifying the RSA asymmetric algorithm and Bouncy Castle provider. Generate a 1024-bit asymmetric public and private key pair to be stored in a password protected key store file.

//-Generate the pair of Asymmetric Encryption Keys (public/private)
KeyPairGenerator tKPGen = KeyPairGenerator.getInstance("RSA", "BC");
SecureRandom tRandom = new SecureRandom();
tKPGen.initialize(1024, tRandom); //-Key size in bits
KeyPair tPair = tKPGen.generateKeyPair();
PublicKey tUserPubKey = tPair.getPublic();
PrivateKey tUserPrivKey = tPair.getPrivate();

Step 2: Extract four hex digits from the public key to create a unique alias for the filename of the certificate and key store.

KeyFactory tKeyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec tPubSpec =
tKeyFactory.getKeySpec(tUserPubKey, RSAPublicKeySpec.class);
String t4HexDigits = tPubSpec.getModulus().toString(16).substring(8,12);
String tUniqueAlias = "jxdoe_" + t4HexDigits;

Step 3: Create a certificate to hold the asymmetric public key that can be used to encrypt your confidential information or distributed to others for exchanging encrypted files.

JcaContentSignerBuilder tSignBldr =
new JcaContentSignerBuilder("SHA512WithRSAEncryption");
ContentSigner tSigGen = tSignBldr.build(tUserPrivKey);
X500NameBuilder tBuilder = new X500NameBuilder(BCStyle.INSTANCE);
tBuilder.addRDN(BCStyle.CN, "John X. Doe"); //-Common name
tBuilder.addRDN(BCStyle.E, "[email protected]"); //-E-mail
tBuilder.addRDN(BCStyle.L, "Detroit"); //-City/Locale
tBuilder.addRDN(BCStyle.ST, "MI"); //-State
org.bouncycastle.asn1.x500.X500Name tX500Name = tBuilder.build();
Calendar tCal = Calendar.getInstance();
tCal.set(2014, 12, 31);
java.util.Date tEnd = tCal.getTime(); //-Ending date for certificate
X509v3CertificateBuilder tV3CertGen = new JcaX509v3CertificateBuilder(
tX500Name,  //-Issuer is same as Subject
BigInteger.valueOf( System.currentTimeMillis()), //-Serial Number
new java.util.Date(), //-Date start
tEnd,     //-Date end
tX500Name,  //-Subject
tUserPubKey); //-Public RSA Key
X509CertificateHolder tCertHolder = tV3CertGen.build(tSigGen);
JcaX509CertificateConverter tConverter =
new JcaX509CertificateConverter().setProvider("BC");
X509Certificate tCert = tConverter.getCertificate(tCertHolder);

Step 4: Save the certificate to disk so that it can be used for encrypting your own personal information or distributing to others.

byte[] tBA = tCert.getEncoded();
File tFile = new File("C:\\" + tUniqueAlias + ".cer");
FileOutputStream tFOS = new FileOutputStream(tFile);

Step 5: Insert the certificate into an array of X509 certificates called a chain. Create a password protected key store file to hold the private key and certificate chain and save it to disk. The key store saves the private key and certificate chain as an entry at a unique key called the alias and is password protected as well. The same password will be used to protect the entry and key store.

KeyStore tKStore = KeyStore.getInstance("JKS", "SUN");
tKStore.load(null, null); //-Initialize KeyStore
X509Certificate[] tChain = new X509Certificate[1];
tChain[0] = tCert; //-Put certificate into a chain
String tKSFileName = "C:\\" + tUniqueAlias + ".jks";
tFOS = new FileOutputStream(tKSFileName);
tKStore.store(tFOS, "password".toCharArray()); //-Set KeyStore password

Encryption with Digital Signature
Encryption is used to protect a file from being read by unauthorized eyes by altering its original contents to an indecipherable form. Using a hybrid encryption technique, the file is encrypted with an AES (Advanced Encryption Standard) symmetric key and the key is encrypted using RSA asymmetric encryption. In addition to protecting a file, a digital signature can be added to provide authentication of the originator who sent/encrypted the file. The digital signature is a unique number that is generated using the owner's asymmetric private key and a hash algorithm on the encrypted file contents. The following steps along with Java code snippets illustrate how to encrypt and add a digital signature to a file.

Figure 4: AES Symmetric Key

Step 1: Let's assume you want to encrypt and digitally sign the file, C:\sampleFile.txt. Dynamically generate a symmetric "secret" key using the Java class, KeyGenerator. The symmetric key will be used to encrypt the file. The Java class KeyGenerator is instantiated using the symmetric algorithm, "AES", and provider, BouncyCastle("BC"). The instance of KeyGenerator is initialized with a secure random seed and the maximum key size in bits allowed by your country. The following code illustrates how to generate a symmetric key.

KeyGenerator tKeyGen = KeyGenerator.getInstance("AES", "BC");
SecureRandom tRandom2 = new SecureRandom();
tKeyGen.init(256, tRandom2); //-256 bit AES symmetric key
SecretKey tSymmetricKey = tKeyGen.generateKey();

Step 2: Generate a Cryptography header that stores cryptographic information used to later decrypt the file and verify the digital signature. Save the symmetric algorithm, mode and padding in the header. The following code illustrates the header instantiation and initialization.

CryptoHeader tHead = new CryptoHeader();
tHead.symKeyAlg(1);   //-AES
tHead.symKeyMode(5);  //-CTR Segmented Integer Counter mode
tHead.symKeyPadding(2); //-PKCS7 Padding
tHead.decryptID(tUniqueAlias); //-Owner's unique alias

Step 3: Load the owner's certificate and extract the public key. You can also load another person's certificate if you are encrypting the file for someone other than yourself. The public key will be used to encrypt the symmetric key.

InputStream tCertIS = new FileInputStream("C:\\" +tUniqueAlias+ ".cer");
CertificateFactory tFactory = CertificateFactory.getInstance("X.509","BC");
X509Certificate tCertificate =
PublicKey tPubKey = tCertificate.getPublicKey();

Step 4: Generate a Java Cipher object and initialize it using the owner's or another person's asymmetric public key extracted from the certificate and set its mode to "Cipher.WRAP_MODE". Use the Java Cipher and public key to encrypt and wrap the symmetric key. Store the wrapped encrypted key in the header and its length.

Cipher tCipherRSA = Cipher.getInstance("RSA", "BC");
tCipherRSA.init(Cipher.WRAP_MODE, (PublicKey)tPubKey);
byte[] tWrappedKey = tCipherRSA.wrap(tSymmetricKey);

Figure 5. Wrap Symmetric Key

Step 5: Generate an initialization vector if required by the symmetric mode chosen to encrypt the file. AES is a block cipher symmetric algorithm and the Counter (CTR) mode requires an initialization vector. The AES block size is 16 bytes.

int tSize = Cipher.getInstance("AES", "BC").getBlockSize();
byte[] tInitVectorBytes = new byte[tSize];
SecureRandom tRandom3 = new SecureRandom();
IvParameterSpec tIVSpec = new IvParameterSpec(tInitVectorBytes);

Figure 6. Initialization Vector

Step 6: Use the previously instantiated Cipher and set its mode to "Cipher.ENCRYPT_MODE". Use the public key to encrypt the initialization vector. Store the encrypted vector in the header along with its length.

tCipherRSA.init(Cipher.ENCRYPT_MODE, (PublicKey)tPubKey);
byte[] tInitVectorEncrypted = tCipherRSA.doFinal(tIVSpec.getIV());

Figure 7. Wrap Initialization Vector

Step 7:(Optional) If you are using an enterprise CA hierarchy and encrypting for yourself, use the CA asymmetric public key stored in the key store to wrap the symmetric key and encrypt the initialization vector and store both in the header. If encrypting for another person, use the owner's asymmetric key to wrap the symmetric key and encrypt the initialization vector and store both in the header. You can store the values in the header variables, wrappedSymKeyOther and initVectorOther as well as their lengths. This provides the ability for the CA or owner to decrypt the encrypted file.

Step 8: 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 generate a digital signature and stored in the header.

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

Figure 8. Private Key

Step 9: Generate a Java Signature object specifying the signature algorithm and provider. Initialize the signature engine with the owner's asymmetric private key. The signature engine is bound to the private key so that only the public key can validate it. Store the signature algorithm in the header so that it can be verified later.

Signature tSigEngine =
Signature.getInstance("SHA512WithRSAEncryption", "BC");
tHead.signatureAlg(12); //-SHA512WithRSAEncryption

Step 10: Generate a Java Cipher object based on the symmetric algorithm, mode, padding and provider which will be used to encrypt the target file. Initialize the Cipher object using the symmetric key and initialization vector and set its mode to "Cipher.ENCRYPT_MODE".

Cipher tCipherEncrypt = Cipher.getInstance("AES/CTR/PKCS7Padding", "BC");
tCipherEncrypt.init(Cipher.ENCRYPT_MODE, tSymmetricKey, tIVSpec);

Step 11: Load the file to be encrypted as a Java "FileInputStream". Encrypt the file to a temporary Java "FileOutputStream" using the Java Cipher, symmetric key and initialization vector and in parallel, sign the encrypted data with the signature engine. The stream is processed a buffer at a time till the end of the file is reached. The end result is an encrypted and digitally signed temporary file.

FileOutputStream tFileOS = new FileOutputStream("C:\\$$$$$$$$.tmp");
InputStream tFileIS = new FileInputStream("C:\\sampleFile.txt");
byte[] tInBuffer = new byte[4096];
byte[] tOutBuffer = new byte[4096];
int tNumOfBytesRead = tFileIS.read(tInBuffer);
while (tNumOfBytesRead == tInBuffer.length) {
//-Encrypt the input buffer data and store in the output buffer
int tNumOfBytesUpdated =
tCipherEncrypt.update(tInBuffer, 0, tInBuffer.length, tOutBuffer);
//-Sign the encrypted data in the output buffer
tSigEngine.update(tOutBuffer, 0, tNumOfBytesUpdated);
tFileOS.write(tOutBuffer, 0, tNumOfBytesUpdated);
tNumOfBytesRead = tFileIS.read(tInBuffer);
//-Process the remaining bytes in the input file.
if (tNumOfBytesRead > 0) {
tOutBuffer = tCipherEncrypt.doFinal(tInBuffer, 0, tNumOfBytesRead);
} else {
tOutBuffer = tCipherEncrypt.doFinal();
tSigEngine.update(tOutBuffer); //-Sign the remaining bytes
tFileOS.write(tOutBuffer, 0, tOutBuffer.length);
tFileOS.close(); //-Close the temporary file
tFileIS.close(); //-Close input file

Figure 9. Encrypt and Sign the File

The code can be made more efficient by allocating larger buffers and writing out the encrypted data after a threshold has been reached.

Step 12: Generate the digital signature from the signature engine after signing the file and store it in the header along with its length. Save the signature algorithm, signature certificate name and its length in the header.

byte[] tSignature = tSigEngine.sign();
tHead.verifySigCertName(tUniqueAlias + ".cer");

Step 13: Calculate the total size of the header and save in the header along with its version. Write the header into a ByteArrayOutputStream, which can be converted to a byte array. The Cryptography header class contains a method to write out the header to a ByteArrayOutputStream. Write out the byte array to a file using a Java "FileOutputStream."

ByteArrayOutputStream tHeadBAOS = new ByteArrayOutputStream();
Object tRC = tHead.writeOutHeaderV4(new DataOutputStream(tHeadBAOS));
String tEncryptedFileName = "C:\\sampleFile.txt." + tUniqueAlias + ".asg";
FileOutputStream tFileOStream = new FileOutputStream(tEncryptedFileName);
byte[] tArray = tHeadBAOS.toByteArray();
tFileOStream.write(tArray, 0, tArray.length);

Step 14: Append the temporary "encrypted" file to the output stream. The end result is an encrypted file with a digital signature. Note that the file extension is "ASG" instead of "AES" to imply that it is encrypted and digitally signed. The temporary file though encrypted should be securely deleted afterwards by overwriting it.

tInStream = new FileInputStream("C:\\$$$$$$$$.tmp");
byte[] tBuffer = new byte[4096];
int tLength = tInStream.read(tBuffer);
while (tLength > 0) {
tFileOStream.write(tBuffer, 0, tLength);
tLength = tInStream.read(tBuffer);


This article demonstrates how to encrypt and digitally sign any file using Java Cryptography methods and the Cryptography libraries from Bouncy Castle organization. The Cryptography header provides information required to decipher the file and validate who encrypted its contents. 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
Deploying applications in hybrid cloud environments is hard work. Your team spends most of the time maintaining your infrastructure, configuring dev/test and production environments, and deploying applications across environments – which can be both time consuming and error prone. But what if you could automate provisioning and deployment to deliver error free environments faster? What could you do with your free time?
This complete kit provides a proven process and customizable documents that will help you evaluate rapid application delivery platforms and select the ideal partner for building mobile and web apps for your organization.
Monitoring of Docker environments is challenging. Why? Because each container typically runs a single process, has its own environment, utilizes virtual networks, or has various methods of managing storage. Traditional monitoring solutions take metrics from each server and applications they run. These servers and applications running on them are typically very static, with very long uptimes. Docker deployments are different: a set of containers may run many applications, all sharing the resource...
SYS-CON Events announced today that 910Telecom will exhibit at the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Housed in the classic Denver Gas & Electric Building, 910 15th St., 910Telecom is a carrier-neutral telecom hotel located in the heart of Denver. Adjacent to CenturyLink, AT&T, and Denver Main, 910Telecom offers connectivity to all major carriers, Internet service providers, Internet backbones and ...
SYS-CON Events announced today that eCube Systems, a leading provider of middleware modernization, integration, and management solutions, will exhibit at @DevOpsSummit at 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. eCube Systems offers a family of middleware evolution products and services that maximize return on technology investment by leveraging existing technical equity to meet evolving business needs. ...
The following fictional case study is a composite of actual horror stories I’ve heard over the years. Unfortunately, this scenario often occurs when in-house integration teams take on the complexities of DevOps and ALM integration with an enterprise service bus (ESB) or custom integration. It is written from the perspective of an enterprise architect tasked with leading an organization’s effort to adopt Agile to become more competitive. The company has turned to Scaled Agile Framework (SAFe) as ...

Modern organizations face great challenges as they embrace innovation and integrate new tools and services. They begin to mature and move away from the complacency of maintaining traditional technologies and systems that only solve individual, siloed problems and work “well enough.” In order to build...

The post Gearing up for Digital Transformation appeared first on Aug. 28, 2016 03:15 PM EDT  Reads: 1,581

DevOps at Cloud Expo – being held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA – announces that its Call for Papers is open. Born out of proven success in agile development, cloud computing, and process automation, DevOps is a macro trend you cannot afford to miss. From showcase success stories from early adopters and web-scale businesses, DevOps is expanding to organizations of all sizes, including the world's largest enterprises – and delivering real results. Am...
Thomas Bitman of Gartner wrote a blog post last year about why OpenStack projects fail. In that article, he outlined three particular metrics which together cause 60% of OpenStack projects to fall short of expectations: Wrong people (31% of failures): a successful cloud needs commitment both from the operations team as well as from "anchor" tenants. Wrong processes (19% of failures): a successful cloud automates across silos in the software development lifecycle, not just within silos.
Internet of @ThingsExpo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. 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 - comp...
Cloud Expo 2016 New York at the Javits Center New York was characterized by increased attendance and a new focus on operations. These were both encouraging signs for all involved in Cloud Computing and all that it touches. As Conference Chair, I work with the Cloud Expo team to structure three keynotes, numerous general sessions, and more than 150 breakout sessions along 10 tracks. Our job is to balance the state of enterprise IT today with the trends that will be commonplace tomorrow. Mobile...
DevOps at Cloud Expo, taking place Nov 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 19th 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 wait for long dev...
19th Cloud Expo, taking place November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy. Meanwhile, 94% of enterpri...
A company’s collection of online systems is like a delicate ecosystem – all components must integrate with and complement each other, and one single malfunction in any of them can bring the entire system to a screeching halt. That’s why, when monitoring and analyzing the health of your online systems, you need a broad arsenal of different tools for your different needs. In addition to a wide-angle lens that provides a snapshot of the overall health of your system, you must also have precise, ...
The 19th International Cloud Expo has announced that its Call for Papers is open. Cloud Expo, to be held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA, brings together Cloud Computing, Big Data, Internet of Things, DevOps, Digital Transformation, Microservices and WebRTC to one location. With cloud computing driving a higher percentage of enterprise IT budgets every year, it becomes increasingly important to plant your flag in this fast-expanding business opportuni...
As the world moves toward more DevOps and Microservices, application deployment to the cloud ought to become a lot simpler. The Microservices architecture, which is the basis of many new age distributed systems such as OpenStack, NetFlix and so on, is at the heart of Cloud Foundry - a complete developer-oriented Platform as a Service (PaaS) that is IaaS agnostic and supports vCloud, OpenStack and AWS. Serverless computing is revolutionizing computing. In his session at 19th Cloud Expo, Raghav...

Let's just nip the conflation of these terms in the bud, shall we?

"MIcro" is big these days. Both microservices and microsegmentation are having and will continue to have an impact on data center architecture, but not necessarily for the same reasons. There's a growing trend in which folks - particularly those with a network background - conflate the two and use them to mean the same thing.

They are not.

One is about the application. The other, the network. T...

If you are within a stones throw of the DevOps marketplace you have undoubtably noticed the growing trend in Microservices. Whether you have been staying up to date with the latest articles and blogs or you just read the definition for the first time, these 5 Microservices Resources You Need In Your Life will guide you through the ins and outs of Microservices in today’s world.
Sharding has become a popular means of achieving scalability in application architectures in which read/write data separation is not only possible, but desirable to achieve new heights of concurrency. The premise is that by splitting up read and write duties, it is possible to get better overall performance at the cost of a slight delay in consistency. That is, it takes a bit of time to replicate changes initiated by a "write" to the read-only master database. It's eventually consistent, and it'...
SYS-CON Events announced today that Isomorphic Software will exhibit at DevOps Summit at 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Isomorphic Software provides the SmartClient HTML5/AJAX platform, the most advanced technology for building rich, cutting-edge enterprise web applications for desktop and mobile. SmartClient combines the productivity and performance of traditional desktop software with the simp...