I am new to software design patterns and trying factory design (creational pattern) to implement in my application for encryption/decryption using key.
I want to make sure this is Factory pattern and if its a bad design. Also if you can help how to improve it .
My code is follows :
abstract base class :
public abstract class EncryptDecrypt {
protected Key getKey() {
Key key = new SecretKeySpec(getKeyValue().getBytes(), getAlgorithm());
return key;
}
protected Cipher getCipher() throws NoSuchAlgorithmException, NoSuchPaddingException {
Cipher c = Cipher.getInstance(getAlgorithm());
return c;
}
protected abstract String getKeyValue();
protected abstract String getAlgorithm();
public final String encryptText(String valueToEnc) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
String keyValue = getKeyValue();
String algorithm = getAlgorithm();
Key key = getKey();
Cipher c = getCipher();
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encValue = c.doFinal(valueToEnc.getBytes());
String encryptedValue = new String(Base64.getEncoder().encode(encValue));
return encryptedValue;
}
public final String decryptText(String encryptedValue) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
String keyValue = getKeyValue();
String algorithm = getAlgorithm();
Key key = getKey();
Cipher c = getCipher();
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = Base64.getDecoder().decode(encryptedValue);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
}
and following is a sample AES implementation :
public class AESEncryptDecrypt extends EncryptDecrypt {
@Override
protected String getKeyValue() {
return "ThisIsA Key 1234";
}
@Override
protected String getAlgorithm() {
return "AES";
}
}
Client class :
public class Test {
public static void main(String[] args) throws Exception {
EncryptDecrypt ed = new AESEncryptDecrypt();
String msg = "Text message@yahoo.com";
String e = ed.encryptText(msg);
System.out.println(e);
System.out.println(ed.decryptText(e));
}
}
Thank you so much for taking the time to answer.
Aucun commentaire:
Enregistrer un commentaire