Tags

, , , , ,


A static secret key approach can come in handy when there is a need to persist sensitive information across session. Thus can be used to encrypt cookies where the client has nothing to do with it but is centrally processed on the app server, hence eliminating the risk of the key being exposed.

package com.core;

/**
*
* @author reisang
*/
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class CryptoService {

private static SecretKeySpec secretKeySpec;

public static String encrypt(String message) throws Exception {
setupCrypto();
Cipher cipher = Cipher.getInstance(“AES”);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal((message).getBytes());
return BytetoHex(encrypted);
}

public static String decrypt(String ciphertext) throws Exception {
setupCrypto();
Cipher cipher = Cipher.getInstance(“AES”);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] original = cipher.doFinal(hexToBytes(ciphertext));
String originalString = new String(original);
return originalString;
}

public static void setupCrypto() throws Exception {
String SALT = “#42_2332!@@@!*(*(&”;
byte[] key = (SALT).getBytes(“UTF-8”);
MessageDigest sha = MessageDigest.getInstance(“SHA-256”);
key = sha.digest(key);
secretKeySpec = new SecretKeySpec(key, “AES”);
}

public static String BytetoHex(byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10) {
strbuf.append(“0”);
}
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}

public static byte[] hexToBytes(String hexValue) {
char[] hex = hexValue.toCharArray();
int length = hex.length / 2;
byte[] raw = new byte[length];
for (int i = 0; i < length; i++) {
int high = Character.digit(hex[i * 2], 16);
int low = Character.digit(hex[i * 2 + 1], 16);
int value = (high << 4) | low;
if (value > 127) {
value -= 256;
}
raw[i] = (byte) value;
}
return raw;
}

public static void main(String[] args) throws Exception {
String bytes = CryptoService.encrypt(“hello”);
String temp =CryptoService.decrypt(bytes);
System.out.println(temp);

}
}

Advertisements