Machine Learning Authors: Elizabeth White, Liz McMillan, Rene Buest, Yeshim Deniz, Pat Romanski

Related Topics: Java IoT, Industrial IoT, Microservices Expo, Machine Learning , 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.

@CloudExpo Stories
"We're a cybersecurity firm that specializes in engineering security solutions both at the software and hardware level. Security cannot be an after-the-fact afterthought, which is what it's become," stated Richard Blech, Chief Executive Officer at Secure Channels, in this SYS-CON.tv interview at @ThingsExpo, held November 1-3, 2016, at the Santa Clara Convention Center in Santa Clara, CA.
Enterprise architects are increasingly adopting multi-cloud strategies as they seek to utilize existing data center assets, leverage the advantages of cloud computing and avoid cloud vendor lock-in. This requires a globally aware traffic management strategy that can monitor infrastructure health across data centers and end-user experience globally, while responding to control changes and system specification at the speed of today’s DevOps teams. In his session at 20th Cloud Expo, Josh Gray, Chie...
To get the most out of their data, successful companies are not focusing on queries and data lakes, they are actively integrating analytics into their operations with a data-first application development approach. Real-time adjustments to improve revenues, reduce costs, or mitigate risk rely on applications that minimize latency on a variety of data sources. Jack Norris reviews best practices to show how companies develop, deploy, and dynamically update these applications and how this data-first...
Intelligent Automation is now one of the key business imperatives for CIOs and CISOs impacting all areas of business today. In his session at 21st Cloud Expo, Brian Boeggeman, VP Alliances & Partnerships at Ayehu, will talk about how business value is created and delivered through intelligent automation to today’s enterprises. The open ecosystem platform approach toward Intelligent Automation that Ayehu delivers to the market is core to enabling the creation of the self-driving enterprise.
"We're here to tell the world about our cloud-scale infrastructure that we have at Juniper combined with the world-class security that we put into the cloud," explained Lisa Guess, VP of Systems Engineering at Juniper Networks, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
Historically, some banking activities such as trading have been relying heavily on analytics and cutting edge algorithmic tools. The coming of age of powerful data analytics solutions combined with the development of intelligent algorithms have created new opportunities for financial institutions. In his session at 20th Cloud Expo, Sebastien Meunier, Head of Digital for North America at Chappuis Halder & Co., discussed how these tools can be leveraged to develop a lasting competitive advantage ...
As businesses adopt functionalities in cloud computing, it’s imperative that IT operations consistently ensure cloud systems work correctly – all of the time, and to their best capabilities. In his session at @BigDataExpo, Bernd Harzog, CEO and founder of OpsDataStore, presented an industry answer to the common question, “Are you running IT operations as efficiently and as cost effectively as you need to?” He then expounded on the industry issues he frequently came up against as an analyst, and ...
The question before companies today is not whether to become intelligent, it’s a question of how and how fast. The key is to adopt and deploy an intelligent application strategy while simultaneously preparing to scale that intelligence. In her session at 21st Cloud Expo, Sangeeta Chakraborty, Chief Customer Officer at Ayasdi, will provide a tactical framework to become a truly intelligent enterprise, including how to identify the right applications for AI, how to build a Center of Excellence to ...
In his session at 20th Cloud Expo, Mike Johnston, an infrastructure engineer at Supergiant.io, discussed how to use Kubernetes to set up a SaaS infrastructure for your business. Mike Johnston is an infrastructure engineer at Supergiant.io with over 12 years of experience designing, deploying, and maintaining server and workstation infrastructure at all scales. He has experience with brick and mortar data centers as well as cloud providers like Digital Ocean, Amazon Web Services, and Rackspace. H...
You know you need the cloud, but you’re hesitant to simply dump everything at Amazon since you know that not all workloads are suitable for cloud. You know that you want the kind of ease of use and scalability that you get with public cloud, but your applications are architected in a way that makes the public cloud a non-starter. You’re looking at private cloud solutions based on hyperconverged infrastructure, but you’re concerned with the limits inherent in those technologies.
DevOps is under attack because developers don’t want to mess with infrastructure. They will happily own their code into production, but want to use platforms instead of raw automation. That’s changing the landscape that we understand as DevOps with both architecture concepts (CloudNative) and process redefinition (SRE). Rob Hirschfeld’s recent work in Kubernetes operations has led to the conclusion that containers and related platforms have changed the way we should be thinking about DevOps and...
SYS-CON Events announced today that Massive Networks will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
Because IoT devices are deployed in mission-critical environments more than ever before, it’s increasingly imperative they be truly smart. IoT sensors simply stockpiling data isn’t useful. IoT must be artificially and naturally intelligent in order to provide more value In his session at @ThingsExpo, John Crupi, Vice President and Engineering System Architect at Greenwave Systems, will discuss how IoT artificial intelligence (AI) can be carried out via edge analytics and machine learning techn...
FinTechs use the cloud to operate at the speed and scale of digital financial activity, but are often hindered by the complexity of managing security and compliance in the cloud. In his session at 20th Cloud Expo, Sesh Murthy, co-founder and CTO of Cloud Raxak, showed how proactive and automated cloud security enables FinTechs to leverage the cloud to achieve their business goals. Through business-driven cloud security, FinTechs can speed time-to-market, diminish risk and costs, maintain continu...
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
Existing Big Data solutions are mainly focused on the discovery and analysis of data. The solutions are scalable and highly available but tedious when swapping in and swapping out occurs in disarray and thrashing takes place. The resolution for thrashing through machine learning algorithms and support nomenclature is through simple techniques. Organizations that have been collecting large customer data are increasingly seeing the need to use the data for swapping in and out and thrashing occurs ...
As many know, the first generation of Cloud Management Platform (CMP) solutions were designed for managing virtual infrastructure (IaaS) and traditional applications. But that’s no longer enough to satisfy evolving and complex business requirements. In his session at 21st Cloud Expo, Scott Davis, Embotics CTO, will explore how next-generation CMPs ensure organizations can manage cloud-native and microservice-based application architectures, while also facilitating agile DevOps methodology. He wi...
SYS-CON Events announced today that CA Technologies has been named "Platinum Sponsor" of SYS-CON's 21st International Cloud Expo®, which will take place October 31-November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CA Technologies helps customers succeed in a future where every business - from apparel to energy - is being rewritten by software. From planning to development to management to security, CA creates software that fuels transformation for companies in the applic...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...