How do I decrypt an object with DES?
Category: javax.crypto, viewed: 4718 time(s).
On the previous example How do I encrypt an object with DES? we encrypt an object. In this example we'll decrypt the stored object.
package org.kodejava.example.security;
import java.io.*;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
public class ObjectDecrypt {
//
// Method for reading object stored in a file.
//
private static Object readFromFile(String filename) throws Exception {
FileInputStream fis = null;
ObjectInputStream ois = null;
Object object = null;
try {
fis = new FileInputStream(new File(filename));
ois = new ObjectInputStream(fis);
object = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ois != null) {
ois.close();
}
if (fis != null) {
fis.close();
}
}
return object;
}
public static void main(String[] args) throws Exception {
//
// Read the previously stored SecretKey.
//
SecretKey key = (SecretKey) readFromFile("secretkey.dat");
//
// Read the SealedObject
//
SealedObject sealedObject = (SealedObject) readFromFile("sealed.dat");
//
// Preparing Cipher object from decryption.
//
String algorithmName = sealedObject.getAlgorithm();
Cipher cipher = Cipher.getInstance(algorithmName);
cipher.init(Cipher.DECRYPT_MODE, key);
String text = (String) sealedObject.getObject(cipher);
System.out.println("Text = " + text);
}
}
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!