/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Java;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
*
* @author Geert
*/
public class Cookie {
private static final String propertyLocation = "cookie.properties";
/**
* Create a new property file for cookies.
* @return true if it has succeeded.
*/
private static boolean newProperties(String location) {
Properties prop;
FileOutputStream output = null;
boolean succes = false;
try {
prop = new Properties();
output = new FileOutputStream(String.format("%s/%s", location, propertyLocation));
byte[] salt = new SecureRandom().generateSeed(32);
prop.setProperty("salt", new BASE64Encoder().encode(salt));
prop.store(output, null);
succes = true;
} catch (Exception ex) {
} finally {
if (output != null)
try { output.flush(); output.close(); } catch (IOException ex) {}
}
return succes;
}
public static String encrypt(String cookieContent) {
try {
byte[] salt = new BASE64Decoder().decodeBuffer(loadProperty("salt"));
SecretKeySpec key = new SecretKeySpec(salt, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(cookieContent.getBytes());
return new BASE64Encoder().encode(encryptedBytes);
} catch (Exception ex) {
}
return null;
}
public static String decrypt(String shoppingcart) throws Exception {
try {
byte[] salt = new BASE64Decoder().decodeBuffer(loadProperty("salt"));
SecretKeySpec key = new SecretKeySpec(salt, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] plaintext = cipher.doFinal(new BASE64Decoder().decodeBuffer(shoppingcart));
return new String(plaintext);
} catch (Exception ex) {
throw ex;
}
}
private static String loadProperty(String propertyName) {
Properties prop;
FileInputStream input = null;
String propValue = null;
try {
prop = new Properties();
InputStream propFile = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertyLocation);
System.out.println(Thread.currentThread().getContextClassLoader().getResource(".").getFile());
if (propFile == null)
newProperties(Thread.currentThread().getContextClassLoader().getResource(".").getFile());
prop.load(propFile);
propValue = prop.getProperty(propertyName);
} catch (IOException ex) {
Logger.getLogger(Cookie.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (input != null)
try { input.close(); } catch (IOException ex) {}
}
return propValue == null ? "" : propValue;
}
}