1 package net.argius.stew;
8 * A skeletal implementation of the Password interface using ciphers.
10 public abstract class CipherPassword implements Password {
12 private static final Logger log = Logger.getLogger(CipherPassword.class);
14 private static String secretKey = "";
16 private String transformedString;
19 public final String getTransformedString() {
20 if (transformedString != null) {
21 return transformedString;
27 public final void setTransformedString(String transformedString) {
28 if (transformedString != null) {
29 this.transformedString = transformedString;
34 public final String getRawString() {
35 if (transformedString != null) {
36 return decrypt(transformedString);
42 public final void setRawString(String rowString) {
43 if (rowString != null) {
44 this.transformedString = encrypt(rowString);
49 public final boolean hasPassword() {
50 return transformedString != null;
57 public static void setSecretKey(String secretKey) {
58 assert secretKey != null && secretKey.length() > 0;
59 CipherPassword.secretKey = secretKey;
63 * Encrypts a password.
65 * @return the encrypted password
67 private String encrypt(String rowString) {
69 Cipher cipher = getCipherInstance(secretKey, Cipher.ENCRYPT_MODE);
70 byte[] encrypted = cipher.doFinal(rowString.getBytes());
71 return toHexString(encrypted);
72 } catch (Exception ex) {
79 * Decrypts a password.
80 * @param cryptedString
81 * @return the decrypted password
83 private String decrypt(String cryptedString) {
85 Cipher cipher = getCipherInstance(secretKey, Cipher.DECRYPT_MODE);
86 byte[] decrypted = cipher.doFinal(toBytes(cryptedString));
87 return new String(decrypted);
88 } catch (Exception ex) {
94 private static String toHexString(byte[] bytes) {
95 StringBuffer buffer = new StringBuffer();
96 for (byte b : bytes) {
97 buffer.append(String.format("%02X", b & 0xFF));
99 return buffer.toString();
102 private static byte[] toBytes(String hexString) {
103 ByteArrayOutputStream bos = new ByteArrayOutputStream();
104 for (int i = 0; i < hexString.length(); i += 2) {
105 String s = hexString.substring(i, i + 2);
106 bos.write(Integer.parseInt(s, 16));
108 return bos.toByteArray();
112 * Gets a instance of Cipher class.
114 * @param mode Cipher.DECRYPT_MODE or Cipher.DECRYPT_MODE
115 * @return the instance of Cipher class
118 protected abstract Cipher getCipherInstance(String key, int mode);