Welcome!

Web 2.0 Authors: Kevin Benedict, Esmeralda Swartz, Tim Hinds, Pat Romanski, Michael Bushong

Related Topics: Java, SOA & WOA, AJAX & REA, Web 2.0, Oracle, Security, SDN Journal

Java: Article

Java Cryptography | Part 3

Decryption and verifying signatures

After you have secured your private electronic information using encryption and learned how to encrypt and digitally sign files for others, how do you extract the information and determine who encrypted the file? Asymmetric public/private key encryption allows you to decipher the information and verify the accompanying digital signature if it exists.

This article illustrates how to decrypt and verify the digital signature on files encrypted 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.

Figure1: Asymmetric Key Encryption Functions

The same pair of 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.

Figure 2: Asymmetric Key Signature Functions

The decryption 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, contains 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());

Decryption for Files or Java Objects
Once a file has been encrypted and/or signed using the DocuArmor application, it can be deciphered by the owner of the matching asymmetric private key. The process involves reading the header, extracting the symmetric key and deciphering the appended encrypted data. The following steps along with the Java code snippets illustrate the process used to decrypt an encrypted file.

Step 1: Assume you want to decrypt the encrypted file, C:\sampleFile.txt.jxdoe_nnnn.asg and the String variable, tUniqueAlias = "jxdoe_nnnn", holds the alias associated to the encrypted file. Read the header from the encrypted file and determine decrypted output name.

File tSrcFile = new File("C:\\sampleFile.txt." + tUniqueAlias + ".aes");
String tDecryptFile = tSrcFile.getName();
tDecryptFile = tDecryptFile.substring(0, tDecryptFile.lastIndexOf('.'));
tDecryptFile = tDecryptFile.substring(0, tDecryptFile.lastIndexOf('.'));
OutputStream tFileOStream = new FileOutputStream(tDecryptFile);
DataInputStream tDInStream =
new DataInputStream(new FileInputStream(tSrcFile));
Object tRC = CryptoHeader.readHeader(tDInStream);
CryptoHeader tHead = (CryptoHeader)tRC;

Step 2: 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 decrypt the symmetric key.

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

Figure 3: Private Key

Step 3: Generate a Java Cipher object using the asymmetric private key and set its mode to "Cipher.UNWRAP_MODE".

Cipher tCipherRSA = Cipher.getInstance("RSA", "BC");
tCipherRSA.init(Cipher.UNWRAP_MODE, (PrivateKey)tPrivKey);

Step 4: Use the Java Cipher and asymmetric private key to unwrap the symmetric key. It's located in the header at the instance variable, wrappedSymKey or wrappedSymKeyOther, along with symmetric algorithm at symKeyAlgDesc. The symmetric key will be used to decrypt the file.

String tAlg = tHead.symKeyAlgDesc();
Key tSymmetricKey =
tCipherRSA.unwrap(tHead.wrappedSymKey(),tAlg, Cipher.SECRET_KEY);

Figure 4: Unwrap Symmetric Key

Step 5: Re-initialize the same Cipher to Cipher.DECRYPT_MODE. Use the Cipher and the asymmetric private key to decrypt the initialization vector stored within the header at the instance variable initVector or initVectorOther.

tCipher.init(Cipher.DECRYPT_MODE, (PrivateKey)tPrivKey);
byte[] tInitVector = tCipher.doFinal(tHead.initVector());
IvParameterSpec tIvParmSpec = new IvParameterSpec(tInitVector);

Figure 5: Unwrap Initialization Vector

Step 6: Generate a Java Cipher object using the symmetric key and initialization vector and set its mode to "Cipher.DECRYPT_MODE". The string representing the symmetric algorithm, mode and padding can be extracted from the Cryptography header using the "transformation" method.

tCipherDecrypt = Cipher.getInstance("AES/CTR/PKCS7Padding", "BC");
or tCipherDecrypt = Cipher.getInstance(tHead.transformation(), "BC");
tCipherDecrypt.init(Cipher.DECRYPT_MODE, tSymmetricKey, tIvParmSpec);

Step 7: Use the Java Cipher to decrypt the rest of the file to a Java FileOutputStream. The DataInputStream points to the start of the encrypted data after reading the header. The end result is a decrypted file.

byte[] tInBuffer = new byte[4096];
byte[] tOutBuffer = new byte[4096];
int tNumOfBytesRead = tDInStream.read(tInBuffer);
while (tNumOfBytesRead == tInBuffer.length) {
//-Encrypt the input buffer data and store in the output buffer
int tNumOfBytesUpdated =
tCipherDecrypt.update(tInBuffer, 0, tInBuffer.length, tOutBuffer);
tFileOStream.write(tOutBuffer, 0, tNumOfBytesUpdated);
tNumOfBytesRead = tDInStream.read(tInBuffer);
}
//-Process the remaining bytes in the input file.
if (tNumOfBytesRead > 0) {
tOutBuffer = tCipherDecrypt.doFinal(tInBuffer, 0, tNumOfBytesRead);
} else {
tOutBuffer = tCipherDecrypt.doFinal();
}
tFileOStream.write(tOutBuffer, 0, tOutBuffer.length);
tFileOStream.close();

Figure 6: Decipher the Encrypted File

Step 7a: If the encrypted file contains a Java object, use the Java Cipher to decrypt the rest of the file to a Java ByteArrayOutputStream instead of a FileOutputStream. The end result can be converted to an instance of its original Java class.

ByteArrayInputStream tBAIS = new ByteArrayInputStream(tBAOS.toByteArray());  
ObjectInput tOIS = new ObjectInputStream(tBAIS);
Object tObject = tOIS.readObject();  //-Original Java object
tBAOS.close();
tBAIS.close();
tOIS.close();

Alternatively, the same technique can be used to decrypt the encrypted file using the symmetric key that was wrapped with the CA or owner's asymmetric public key. If the file was encrypted for another user, the owner can decrypt it using the additionally wrapped symmetric key. If the file was encrypted for oneself, the CA can decrypt it using the additionally wrapped symmetric key in the enterprise version.

Signature Verification
When a file has been digitally signed with a user's asymmetric private key, the signature is stored in the Cryptography header. The signature can be validated with the user's matching asymmetric public key stored in a certificate. The process involves reading the header, extracting the digital signature and validating it against the rest of the signed file and the asymmetric public key. The following steps describe the process used to verify a digital signature.

Step 1: Assume you want to verify the signature on the encrypted and digitally signed file, "C:\sampleFile.txt.jxdoe_nnnn.asg" and the String variable, tUniqueAlias = "jxdoe_nnnn", holds the alias associated to the file. Read the header from the signed file. After the header is read, keep in mind that the DataInputStream now points to the beginning of the encrypted data.

File tSrcFile = new File("C:\\sampleFile.txt." + tUniqueAlias + ".asg");
DataInputStream tDInStream =
new DataInputStream(new FileInputStream(tSrcFile));
Object tRC = CryptoHeader.readHeader(tDInStream);
CryptoHeader tHead = (CryptoHeader)tRC;
byte[] tCurrSignature = tHead.signature();

Step 2: Retrieve the certificate whose name is stored in the header and contains the asymmetric public key needed for verification. Retrieve the asymmetric public key from the certificate associated with the digital signature.

String tCertName = "C:\\" + tHead.verifySigCertName();
InputStream tInStream = new FileInputStream(tCertName);
CertificateFactory tFactory = CertificateFactory.getInstance("X.509","BC");
X509Certificate tCert =
(X509Certificate)tFactory.generateCertificate(tInStream);
tInStream.close();
PublicKey tPubKey = tCert.getPublicKey();

Figure 7: Extract Public Key

Step 3: Instantiate a Java signature engine and initialize it with the signature algorithm stored in the header and the asymmetric public key. The default value is "SHA512WithRSAEncryption".

Signature tSgnVerifyEngine = null;
String tSigAlg = tHead.signatureAlgDesc();
tSgnVerifyEngine = Signature.getInstance(tSigAlg,"BC");
tSgnVerifyEngine.initVerify(tPubKey);

Step 4: Use the Java signature engine to process the rest of the signed file and calculate a hash number that will be compared with the signature stored in the header.

int tBlockSize = 4096;
byte[] tBuffer = new byte[tBlockSize];
int tLength = tDInStream.read(tBuffer);
while (tLength == tBlockSize) {
tSgnVerifyEngine.update(tBuffer, 0, tBlockSize);
tLength = tDInStream.read(tBuffer);
}

if (tLength > 0) {
tSgnVerifyEngine.update(tBuffer, 0, tLength);
}

Step 5: After the file has been processed, use the Java signature engine to verify its result with the digital signature. A Boolean result is returned on whether the signature was valid.

Boolean tResult = tSgnVerifyEngine.verify(tCurrSignature);

Summary
The article demonstrates how to decrypt and verify the digit signature of and encrypted file using Java Cryptography methods and the Cryptography libraries from Bouncy Castle organization. Using the information provided within the Cryptography header, the user can validate who encrypted its contents and/or decipher the encrypted file. 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.