For legal reasons, the filters for encrypting and decrypting data, CipherInputStream and CipherOutputStream, are part of a standard extension to Java called the Java Cryptography Extension, JCE for short.
The CipherInputStream and CipherOutputStream classes are both powered by a Cipher engine object that encapsulates the algorithm used to perform encryption and decryption. By changing the Cipher engine object, you change the algorithm that the streams use to encrypt and decrypt. Symmetric or secret key ciphers use the same key for both encryption and decryption. Asymmetric or public key ciphers use the different keys for encryption and decryption. The encryption key can be distributed as long as the decryption key is kept secret. Keys are specific to the algorithm in use, and are represented in Java by instances o the java.security.Key interface. The Cipher object is set in the constructor. Like all filter stream constructions, these constructors also take another input stream as an argument.
package javaio;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Provider;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class EncryptingStreams {
public static String infile = "secrets.txt";
public static String outfile = "secrets.des";
public static String password = "Mary had a little spider";
public static void main(String[] args) {
// TODO Auto-generated method stub
try{
FileInputStream fin = new FileInputStream(infile);
FileOutputStream fout = new FileOutputStream(outfile);
//register the provider that implements the algorithm
Provider sunJce = new com.sun.crypto.provider.SunJCE();
Security.addProvider(sunJce);
// create a key
char[] pbeKeyData = password.toCharArray();
PBEKeySpec pbeKeySpec = new PBEKeySpec(pbeKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);
// use Data ENcryption Standard
Cipher pbe = Cipher.getInstance("PBEWithMD5AndDES");
pbe.init(Cipher.ENCRYPT_MODE, pbeKey);
CipherOutputStream cout = new CipherOutputStream(fout, pbe);
byte[] input = new byte[64];
while(true){
int bytesRead = fin.read(input);
if(bytesRead==-1) break;
cout.write(input, 0, bytesRead);
}
cout.flush();
cout.close();
fin.close();
}
catch(Exception e){
System.err.println(e);
e.printStackTrace();
}
}
}
Posted by Triton