One way or another your project needs a string encrypter. From encrypting passwords saved in text files to encrypting entire
files, this class is a handy companion.
package YOUR-PACKAGE;
import java.security.spec.KeySpec;
import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class Encrypter {
public Encrypter(String scheme) {
this(scheme, DEFAULT_ENCRYPTION_KEY);
}
public Encrypter(String scheme, String key) {
if (key == null ||
key.trim().length() < 24) {
return;
}
try {
byte keyAsBytes[] = key.getBytes(UNICODE_FORMAT);
if (scheme.equals(DESEDE_ENCRYPTION_SCHEME)) {
keySpec =
new DESedeKeySpec(keyAsBytes);
} else if
(scheme.equals(DES_ENCRYPTION_SCHEME)) {
keySpec = new DESKeySpec(keyAsBytes);
} else {
return; // or throw
}
keyFactory =
SecretKeyFactory.getInstance(scheme);
cipher = Cipher.getInstance(scheme);
} catch (Exception e) {
// do something
}
}
public String encrypt(String unencrypted) {
if (unencrypted == null ||
unencrypted.trim().length() == 0) {
return null;
}
try {
javax.crypto.SecretKey key =
keyFactory.generateSecret(keySpec);
cipher.init(1, key);
byte cleartext[] =
unencrypted.getBytes(UNICODE_FORMAT);
//
byte ciphertext[] = cipher.doFinal(cleartext);
BASE64Encoder base64encoder = new BASE64Encoder();
return base64encoder.encode(ciphertext);
} catch (Exception e) {
return null;
}
}
public String decrypt(String encrypted) {
if (encrypted == null ||
encrypted.trim().length() == 0) {
return null;
}
try {
javax.crypto.SecretKey key =
keyFactory.generateSecret(keySpec);
cipher.init(2, key);
BASE64Decoder base64decoder = new BASE64Decoder();
byte cleartext[] =
base64decoder.decodeBuffer(encrypted);
//
byte ciphertext[] = cipher.doFinal(cleartext);
return bytes2String(ciphertext);
} catch (Exception e) {
return null;
}
}
private static String bytes2String(byte bytes[]) {
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
stringBuffer.append((char) bytes[i]);
}
return stringBuffer.toString();
}
public static final String
DESEDE_ENCRYPTION_SCHEME = "DESede";
public static final String
DES_ENCRYPTION_SCHEME = "DES";
// At least 24 characters
public static final String DEFAULT_ENCRYPTION_KEY =
"THIS IS YOUR ENCRYPTION KEY, CHANGE TO DESIRED TEXT KEY";
private KeySpec keySpec;
private SecretKeyFactory keyFactory;
private Cipher cipher;
private static final String UNICODE_FORMAT = "UTF8";
// Convience for DES scheme
public static String E(String S) {
Encrypter e = new Encrypter("DES");
return e.encrypt(S);
}
public static String D(String S) {
Encrypter e = new Encrypter("DES");
return e.decrypt(S);
}
}
How to use the class
// Encrypt a string
String e = Encrypter.E (string-to-encrypt);
// Decrypt a string
String d = Encrypter.D (encrypted-string);
The class is tested to work as expected.
Good luck.