yourfanat wrote: I am using another tool for Oracle developers - dbForge Studio for Oracle. This IDE has lots of usefull features, among them: oracle designer, code competion and formatter, query builder, debugger, profiler, erxport/import, reports and many others. The latest version supports Oracle 12C. More information here.
Cloud Computing
Conference & Expo
November 2-4, 2009 NYC
Register Today and SAVE !..

2008 West
Data Direct
SOA, WOA and Cloud Computing: The New Frontier for Data Services
Red Hat
The Opening of Virtualization
User Environment Management – The Third Layer of the Desktop
Cloud Computing for Business Agility
CMIS: A Multi-Vendor Proposal for a Service-Based Content Management Interoperability Standard
Freedom OSS
Practical SOA” Max Yankelevich
Architecting an Enterprise Service Router (ESR) – A Cost-Effective Way to Scale SOA Across the Enterprise
Return on Assests: Bringing Visibility to your SOA Strategy
Managing Hybrid Endpoint Environments
Game-Changing Technology for Enterprise Clouds and Applications
Click For 2008 West
Event Webcasts

2008 West
Get ‘Rich’ Quick: Rapid Prototyping for RIA with ZERO Server Code
Keynote Systems
Designing for and Managing Performance in the New Frontier of Rich Internet Applications
How Can AJAX Improve Homeland Security?
Beyond Widgets: What a RIA Platform Should Offer
REAs: Rich Enterprise Applications
Click For 2008 Event Webcasts
In many cases, the end of the year gives you time to step back and take stock of the last 12 months. This is when many of us take a hard look at what worked and what did not, complete performance reviews, and formulate plans for the coming year. For me, it is all of those things plus a time when I u...
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 ( 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.*; 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 =;
X500NameBuilder tBuilder = new X500NameBuilder(BCStyle.INSTANCE);
tBuilder.addRDN(BCStyle.CN, "John X. Doe"); //-Common name
tBuilder.addRDN(BCStyle.E, ""); //-E-mail
tBuilder.addRDN(BCStyle.L, "Detroit"); //-City/Locale
tBuilder.addRDN(BCStyle.ST, "MI"); //-State
org.bouncycastle.asn1.x500.X500Name tX500Name =;
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 =;
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);, "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 =;
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 =;
//-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 =;
while (tLength > 0) {
tFileOStream.write(tBuffer, 0, tLength);
tLength =;


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 ( 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
About 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.

In order to post a comment you need to be registered and logged in.

Register | Sign-in

Reader Feedback: Page 1 of 1

SOA World Latest Stories
The Internet of Things will greatly expand the opportunities for data collection and new business models driven off of that data. In her session at Internet of @ThingsExpo, Esmeralda Swartz, CMO of MetraTech, will discuss how for this to be effective you not only need to have infrastru...
SAP is delivering break-through innovation combined with fantastic user experience powered by the market-leading in-memory technology, SAP HANA. In his General Session at 15th Cloud Expo, Thorsten Leiduck, VP ISVs & Digital Commerce, SAP, will discuss how SAP and partners provide clo...
SimpleECM is the only platform to offer a powerful combination of enterprise content management (ECM) services, capture solutions, and third-party business services providing simplified integrations and workflow development for solution providers. SimpleECM is opening the market to bus...
One of the more popular methods of dealing with not just with the explosion of devices but the growing challenge of dealing with growth of compute devices under management in general is virtual desktop infrastructure (VDI). While VDI has been overshadowed of late by newer and shinier T...
The only place to be June 9-11 is Cloud Expo & @ThingsExpo 2015 East at the Javits Center in New York City. Join us there as delegates from all over the world come to listen to and engage with speakers & sponsors from the leading Cloud Computing, IoT & Big Data companies. Cloud Expo ...
To manage complex web services with lots of calls to the cloud, many businesses have invested in Application Performance Management (APM) and Network Performance Management (NPM) tools. Together APM and NPM tools are essential aids in improving a business’s infrastructure required to s...
Subscribe to the World's Most Powerful Newsletters
Subscribe to Our Rss Feeds & Get Your SYS-CON News Live!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)!

Advertise on this site! Contact advertising(at)! 201 802-3021

SYS-CON Featured Whitepapers