/* Copyright Tom Valine 2002,2014 All Rights Reserved. ****************************************************************/
package com.kre8orz.i18n.processor;
import java.nio.charset.Charset;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.xml.bind.DatatypeConverter;
/**
* Obfuscates string data.
*
* @author Tom Valine (thomas.valine@gmail.com)
*/
public class I18NObfuscator {
//~ Static fields/initializers *************************************************************************************
private static final String _CIPHER = "DES" /*NOI18N*/;
private static final Charset _UTF8 = Charset.forName("UTF-8" /*NOI18N*/);
//~ Instance fields ************************************************************************************************
private final SecretKey _key;
private final String _keyPhrase;
//~ Constructors ***************************************************************************************************
/**
* Creates a new I18NObfuscator object.
*
* @param keyPhrase The key phrase used to encrypt the data.
*
* @throws RuntimeException If an error initializing the cipher occurs.
*/
public I18NObfuscator(String keyPhrase) {
try {
_keyPhrase = keyPhrase;
DESKeySpec keySpec = new DESKeySpec(_keyPhrase.getBytes(_UTF8));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(_CIPHER);
_key = keyFactory.generateSecret(keySpec);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
//~ Methods ********************************************************************************************************
/**
* Obfuscates data.
*
* @param data The data to obfuscate.
*
* @return Obfuscated data.
*
* @throws RuntimeException If an encryption error occurs.
*/
public String obfuscate(String data) {
try {
byte[] unencrypted = data.getBytes(_UTF8);
Cipher cipher = Cipher.getInstance(_CIPHER);
cipher.init(Cipher.ENCRYPT_MODE, _key);
return DatatypeConverter.printBase64Binary(cipher.doFinal(unencrypted));
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
/**
* Un-obfuscates date.
*
* @param data The data to un-obfuscate.
*
* @return Un-obfuscated data.
*
* @throws RuntimeException If an decryption error occurs.
*/
public String unobfuscate(String data) {
try {
byte[] encrypted = DatatypeConverter.parseBase64Binary(data);
Cipher cipher = Cipher.getInstance(_CIPHER);
cipher.init(Cipher.DECRYPT_MODE, _key);
return new String(cipher.doFinal(encrypted), _UTF8);
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
}
/* Copyright Tom Valine 2002,2014 All Rights Reserved. ****************************************************************/