Java IoT Authors: Elizabeth White, Sematext Blog, Liz McMillan, Jnan Dash, Greg O'Connor

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.

@ThingsExpo Stories
SYS-CON Events announced today that Commvault, a global leader in enterprise data protection and information management, has been named “Bronze Sponsor” of SYS-CON's 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Commvault is a leading provider of data protection and information management solutions, helping companies worldwide activate their data to drive more value and business insight and to transform moder...
SYS-CON Events has announced today that Roger Strukhoff has been named conference chair of Cloud Expo and @ThingsExpo 2016 Silicon Valley. The 19th Cloud Expo and 6th @ThingsExpo will take place on November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. "The Internet of Things brings trillions of dollars of opportunity to developers and enterprise IT, no matter how you measure it," stated Roger Strukhoff. "More importantly, it leverages the power of devices and the Interne...
Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abil...
Digital innovation is the next big wave of business transformation based on digital technologies of which IoT and Big Data are key components, For example: Business boundary innovation is a challenge to excavate third-party business value using IoT and BigData, like Nest Business structure innovation may propose re-building business structure from scratch, as Uber does in the taxicab industry The social model innovation is also a big challenge to the new social architecture with the design fr...
So, you bought into the current machine learning craze and went on to collect millions/billions of records from this promising new data source. Now, what do you do with them? Too often, the abundance of data quickly turns into an abundance of problems. How do you extract that "magic essence" from your data without falling into the common pitfalls? In her session at @ThingsExpo, Natalia Ponomareva, Software Engineer at Google, provided tips on how to be successful in large scale machine learning...
If you had a chance to enter on the ground level of the largest e-commerce market in the world – would you? China is the world’s most populated country with the second largest economy and the world’s fastest growing market. It is estimated that by 2018 the Chinese market will be reaching over $30 billion in gaming revenue alone. Admittedly for a foreign company, doing business in China can be challenging. Often changing laws, administrative regulations and the often inscrutable Chinese Interne...
Why do your mobile transformations need to happen today? Mobile is the strategy that enterprise transformation centers on to drive customer engagement. In his general session at @ThingsExpo, Roger Woods, Director, Mobile Product & Strategy – Adobe Marketing Cloud, covered key IoT and mobile trends that are forcing mobile transformation, key components of a solid mobile strategy and explored how brands are effectively driving mobile change throughout the enterprise.
In his session at @ThingsExpo, Kausik Sridharabalan, founder and CTO of Pulzze Systems, Inc., will focus on key challenges in building an Internet of Things solution infrastructure. He will shed light on efficient ways of defining interactions within IoT solutions, leading to cost and time reduction. He will also introduce ways to handle data and how one can develop IoT solutions that are lean, flexible and configurable, thus making IoT infrastructure agile and scalable.
Data is an unusual currency; it is not restricted by the same transactional limitations as money or people. In fact, the more that you leverage your data across multiple business use cases, the more valuable it becomes to the organization. And the same can be said about the organization’s analytics. In his session at 19th Cloud Expo, Bill Schmarzo, CTO for the Big Data Practice at EMC, will introduce a methodology for capturing, enriching and sharing data (and analytics) across the organizati...
Internet of @ThingsExpo has announced today that Chris Matthieu has been named tech chair of Internet of @ThingsExpo 2016 Silicon Valley. The 6thInternet of @ThingsExpo will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Bsquare has been named “Silver Sponsor” of SYS-CON's @ThingsExpo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. For more than two decades, Bsquare has helped its customers extract business value from a broad array of physical assets by making them intelligent, connecting them, and using the data they generate to optimize business processes.
A strange thing is happening along the way to the Internet of Things, namely far too many devices to work with and manage. It has become clear that we'll need much higher efficiency user experiences that can allow us to more easily and scalably work with the thousands of devices that will soon be in each of our lives. Enter the conversational interface revolution, combining bots we can literally talk with, gesture to, and even direct with our thoughts, with embedded artificial intelligence, wh...
Video experiences should be unique and exciting! But that doesn’t mean you need to patch all the pieces yourself. Users demand rich and engaging experiences and new ways to connect with you. But creating robust video applications at scale can be complicated, time-consuming and expensive. In his session at @ThingsExpo, Zohar Babin, Vice President of Platform, Ecosystem and Community at Kaltura, will discuss how VPaaS enables you to move fast, creating scalable video experiences that reach your...
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life sett...
Cloud computing is being adopted in one form or another by 94% of enterprises today. Tens of billions of new devices are being connected to The Internet of Things. And Big Data is driving this bus. An exponential increase is expected in the amount of information being processed, managed, analyzed, and acted upon by enterprise IT. This amazing is not part of some distant future - it is happening today. One report shows a 650% increase in enterprise data by 2020. Other estimates are even higher....
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
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...
Businesses are struggling to manage the information flow and interactions between all of these new devices and things jumping on their network, and the apps and IT systems they control. The data businesses gather is only helpful if they can do something with it. In his session at @ThingsExpo, Chris Witeck, Principal Technology Strategist at Citrix, will discuss how different the impact of IoT will be for large businesses, expanding how IoT will allow large organizations to make their legacy ap...
In his general session at 18th Cloud Expo, Lee Atchison, Principal Cloud Architect and Advocate at New Relic, discussed cloud as a ‘better data center’ and how it adds new capacity (faster) and improves application availability (redundancy). The cloud is a ‘Dynamic Tool for Dynamic Apps’ and resource allocation is an integral part of your application architecture, so use only the resources you need and allocate /de-allocate resources on the fly.
SYS-CON Events announced today the Enterprise IoT Bootcamp, being held November 1-2, 2016, in conjunction with 19th Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA. Combined with real-world scenarios and use cases, the Enterprise IoT Bootcamp is not just based on presentations but with hands-on demos and detailed walkthroughs. We will introduce you to a variety of real world use cases prototyped using Arduino, Raspberry Pi, BeagleBone, Spark, and Intel Edison. Y...