Digital Edition

SYS-CON.TV
Frank's Java Code Stack #1 Working with Cipher Streams
Frank's Java Code Stack #1 Working with Cipher Streams

(October 11, 2002) - Often it is necessary to encrypt confidential messages and send them across a stream for better Data veracity. With JCE, you can encrypt streams of data and decrypt them using public/private key pair or using a single signature key file. The technique involves associating a Cipher object to Input or Output Stream. Please note that JCE is different from JSA and you need Java Cryptography Extension APIs to work with this example. JDK 1.4 comes with JCE APIs.

Let's create a simple program, which initializes a KeyGenerator class, instantiates a Cipher Object using Cipher feedback Mode (CFB), which is a mode, provided by SunJCE Provider. The ciphstream code, which we have developed, encrypts a simple text message and writes it to a stream and creates a key file, which is necessary to decrypt this stream later.

1.    import javax.crypto.*;
2.    import javax.crypto.spec.*;
3.    import java.io.*;
4.    import java.security.*;
5.    public class ciphstream{
6.    /* A simple String encrypting method */
7.     public void encryptMessage(String message){
8.      try{
9.        /* Algorithm of our choice is DES..
10.        You can try SHA */
11.        KeyGenerator
12.        kg=KeyGenerator.getInstance("DES");
13.        /* SecureRandom provides a
14.        cryptographically strong
15.        pseudo-random number generator
16.              for implementation independent
17.        algorithms
18.        */
19.        kg.init(new SecureRandom());
20.
21.        SecretKey key=kg.generateKey();
22.        SecretKeyFactory
23.        skf=SecretKeyFactory.getInstance("DES");
24.
25.        Class al=Class.forName
26.        ("javax.crypto.spec.DESKeySpec");
27.        DESKeySpec ks=
28.        (DESKeySpec)skf.getKeySpec(key,al);
29.
30.        ObjectOutputStream oos=new
31.        ObjectOutputStream(new
32.        FileOutputStream("keyfile"));
33.        oos.writeObject(ks.getKey());
34.
35.        /* Transformation Format: Algo/Mode/Padding
36.        And CFB8 Mode does not need any Padding */
37.        Cipher c=
38.        Cipher.getInstance("DES/CFB8/NoPadding");
39.        c.init(Cipher.ENCRYPT_MODE,key);
40.
41.        /* Write the Cipher stream to a file */
42.        CipherOutputStream cos=new
43.        CipherOutputStream(new
44.        FileOutputStream("ciphertext"),c);
45.        PrintWriter pw=new PrintWriter(new
46.        OutputStreamWriter(cos));
47.        pw.println(message);
48.        pw.close();
49.
50.        oos.writeObject(c.getIV());
51.        oos.close();
52.    }catch(Exception e){ System.out.println(""+e);}
53.   }
54.    public void decryptMessage(){
55.    try{
56.        ObjectInputStream ois=new
57.        ObjectInputStream(new
58.        FileInputStream("keyfile"));
59.
60.        /* Read the Secret Key from the Key File */
61.        DESKeySpec ks=new DESKeySpec((byte[])
62.        ois.readObject());
63.
64.        SecretKeyFactory
65.        skf=SecretKeyFactory.getInstance("DES");
66.        SecretKey key=skf.generateSecret(ks);
67.
68.        /* Read the Cipher text */
69.        Cipher c=
70.        Cipher.getInstance("DES/CFB8/NoPadding");
71.        c.init(Cipher.DECRYPT_MODE,key,new
72.        IvParameterSpec((byte[]) ois.readObject()));
73.        CipherInputStream cis=new
74.        CipherInputStream(new
75.        FileInputStream("ciphertext"),c);
76.
77.        cis.read(new byte[0]); BufferedReader br=new
78.        BufferedReader(new InputStreamReader(cis));
79.        System.out.println("Retrieved Message..");
80.        System.out.println(br.readLine());
81.    }catch(Exception e){System.out.println(""+e);}
82.   }
83.
84.    public static void main(String ar[]){
85.        ciphstream myciph=new ciphstream();
86.        myciph.encryptMessage("Karl Mark is dead.
87.        Patriots report at 7. Keller Square");
88.        myciph.decryptMessage();
89.     }
90.  }

Before Creating a Cipher object, you need a valid Secret Key to operate on the message. We take the aid from SecretKeyFactory and the DESKeySpec class to generate a random secret key, which we can use to encrypt our message. And also we save the secret key in a file for decrypting the message at a later instance. Note that anyone having this key file can decrypt the message. After generating the key, we create a Cipher object and initialize it with the key. By default the CFB mode works on 8-byte block (CFB8). You can, however, change this. But make sure that the value is a multiple of 8. Decryption is straightforward and we use Initialization Vector for decrypting because of the inherent requirement of CFB mode.

Assignment:
Create a client server application, which can exchange crypted messages over the stream. Don't save the key as a file. Directly pipe it to a Socket Output Stream.

About Frank Jennings
Frank Jennings works in the Communication Designs Group of Pramati Technologies

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

Register | Sign-in

Reader Feedback: Page 1 of 1

For generating keypair:

KeyPairGenerator kpg=KeyPairGenerator.getInstance("DSA");
//Strength Value
kpg.initialize(512);
KeyPair kp=kpg.generateKeyPair();

Do check out these two interface DSAPrivateKey and DSAPublicKey

This deals with the basic symmetric key encryption. How do you encrypt with a private/public key pair. I don't want to generated a signature. Cleartext should be encrypted by the public key and decrypted directly with the private key.

I found the article interesting, showing how to use high-level cryptography API's in an almost simple way (well, you still have to know how the machinery works to use it correctly).

What surprises me, on the other side, is the low-level way used to access the various services. Nearly all parameters are sent in string form. One even needs the reflection mechanism to build a class (again with its name in string form!), followed by a cast to regain the proper object.

The conclusion I draw from this is that enumeration types are cruelly missing in Java. Tricks exist to simulate them, and I can only be surprised to see how little they are generally used in the various API's I can see. This one is no exception.




ADS BY GOOGLE
Subscribe to the World's Most Powerful Newsletters

ADS BY GOOGLE

Most DevOps journeys involve several phases of maturity. Research shows that the inflection point wh...
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 1...
CloudEXPO New York 2018, colocated with DXWorldEXPO New York 2018 will be held November 11-13, 2018,...
Dynatrace is an application performance management software company with products for the informatio...
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22...
DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, ...
Today, we have more data to manage than ever. We also have better algorithms that help us access our...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: D...
A valuable conference experience generates new contacts, sales leads, potential strategic partners a...
DXWorldEXPO LLC announced today that ICOHOLDER named "Media Sponsor" of Miami Blockchain Event by Fi...
SYS-CON Events announced today that IoT Global Network has been named “Media Sponsor” of SYS-CON's @...
The best way to leverage your Cloud Expo presence as a sponsor and exhibitor is to plan your news an...
DevOpsSummit New York 2018, colocated with CloudEXPO | DXWorldEXPO New York 2018 will be held Novemb...
DXWorldEXPO | CloudEXPO are the world's most influential, independent events where Cloud Computing w...
Disruption, Innovation, Artificial Intelligence and Machine Learning, Leadership and Management hear...
Enterprises are striving to become digital businesses for differentiated innovation and customer-cen...
DXWorldEXPO LLC announced today that Telecom Reseller has been named "Media Sponsor" of CloudEXPO | ...
Consumer-driven contracts are an essential part of a mature microservice testing portfolio enabling ...
"Calligo is a cloud service provider with data privacy at the heart of what we do. We are a typical ...
Digital Transformation: Preparing Cloud & IoT Security for the Age of Artificial Intelligence. As au...