import java.io.ObjectInputStream.GetField;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class AESCrypt {
private final Cipher cipher;
private final SecretKeySpec key;
private String encryptedText, decryptedText;
//private AlgorithmParameterSpec ivspec;
public AESCrypt(String password) throws Exception {
// hash password with SHA-256 and crop the output to 128-bit for key
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(password.getBytes("UTF-8"));
byte[] keyBytes = new byte[16];
System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
key = new SecretKeySpec(keyBytes, "AES");
//byte[] iv = new byte[cipher.getBlockSize()];
//ivspec = new IvParameterSpec(iv);
getIV();
}
public AlgorithmParameterSpec getIV() {
AlgorithmParameterSpec ivspec;
byte[] iv = new byte[cipher.getBlockSize()];
new SecureRandom().nextBytes(iv);
ivspec = new IvParameterSpec(iv);
return ivspec;
}
public String encrypt(String plainText) throws Exception {
cipher.init(Cipher.ENCRYPT_MODE, key, getIV());
byte[] encrypted = cipher.doFinal(plainText.getBytes());
encryptedText = DatatypeConverter.printBase64Binary(encrypted);
return encryptedText;
}
public String decrypt(String cryptedText) throws Exception {
cipher.init(Cipher.DECRYPT_MODE, key, getIV());
byte[] bytes = DatatypeConverter.parseBase64Binary(cryptedText);
byte[] decrypted = cipher.doFinal(bytes);
decryptedText = new String(decrypted, "UTF-8");
return decryptedText;
}
public static void main(String[] args) throws Exception {
System.out.print("....AES....\n");
String message = "DOBOJ";
String password = "PASSWORD";
System.out.println("MSG:" + message);
AESCrypt aes = new AESCrypt(password);
String encryptedText = aes.encrypt(message).toString();
System.out.println("ENCRYPTED MSG: " + encryptedText);
String decryptedText = aes.decrypt(encryptedText);
System.out.print("DECRYPTED MSG: " + decryptedText);
}
}