// Singletone
public class DesEncrypter
{
private static DesEncrypter INSTANCE;
private final static String ENCRYPTION_SALT = "abcdefgh"; // must be 8 bytes
private final static String ENCRYPTION_PASSWORD = "password";
private final static String ENCRYPTION_ALGORITHM = "PBEWithMD5AndDES";
private final static int ENCRYPTION_ITERATION = 20;
private Cipher ecipher;
private Cipher dcipher;
public static DesEncrypter getInstance()
{
if (INSTANCE == null)
{
INSTANCE = new DesEncrypter();
}
return INSTANCE;
}
private DesEncrypter() {
// Create an 8-byte initialization vector
PBEKeySpec pbeKeySpec;
PBEParameterSpec pbeParameterSpec;
SecretKeyFactory secretKeyFactory;
SecretKey secretKey;
try {
pbeParameterSpec = new PBEParameterSpec(ENCRYPTION_SALT.getBytes(), ENCRYPTION_ITERATION);
pbeKeySpec = new PBEKeySpec(ENCRYPTION_PASSWORD.toCharArray());
secretKeyFactory = SecretKeyFactory.getInstance(ENCRYPTION_ALGORITHM);
secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
dcipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
ecipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
dcipher.init(Cipher.DECRYPT_MODE, secretKey, pbeParameterSpec);
ecipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
} catch (InvalidKeySpecException e) {
}
}
// Buffer used to transport the bytes from one stream to another
byte[] buf = new byte[1024];
public void encrypt(InputStream in, OutputStream out) {
try {
// Bytes written to out will be encrypted
out = new CipherOutputStream(out, ecipher);
// Read in the cleartext bytes and write to out to encrypt
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
out.close();
} catch (java.io.IOException e) {
}
}
public void decrypt(InputStream in, OutputStream out) {
try {
// Bytes read from in will be decrypted
in = new CipherInputStream(in, dcipher);
// Read in the decrypted bytes and write the cleartext to out
int numRead = 0;
while ((numRead = in.read(buf)) >= 0) {
out.write(buf, 0, numRead);
}
//out.close();
} catch (java.io.IOException e) {
}
}
}