Just use the UTF-8 encoding and your values should be right.
I've just made an small example so I think will be clear to understand.
Please check here:
package com.nicolas.cli;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class TestCrypt {
public static void main(String args[]) {
TestCrypt testCrypt = new TestCrypt(keyValue);
String encrypted = testCrypt.encrypt("someValue");
System.out.println(encrypted);
String decrypted = testCrypt.decrypt(encrypted);
System.out.println(decrypted);
}
private static final String CRYPTO_ALGORITHM = "AES";
private static final Logger LOGGER = LoggerFactory.getLogger(TestCrypt.class);
private static final byte[] keyValue =
new byte[]{'T', 'h', 'e', 'B', 'e', 's', 't', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
private final Key key;
private final Cipher cipher = getCipherInstance();
public TestCrypt(byte [] key) {
this.key = new SecretKeySpec(key, CRYPTO_ALGORITHM);
}
private Cipher getCipherInstance() {
try {
return Cipher.getInstance(CRYPTO_ALGORITHM);
} catch (GeneralSecurityException e) {
LOGGER.error("Crypto error: Unable to get cipher instance");
throw new RuntimeException(e);
}
}
public String encrypt(String password) {
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encVal = cipher.doFinal(password.getBytes());
return new BASE64Encoder().encode(encVal);
} catch (GeneralSecurityException e) {
LOGGER.error("Crypto error: Unable to encrypt password");
throw new RuntimeException(e);
}
}
public String decrypt(String encryptedPassword) {
try {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decodedValue = new BASE64Decoder().decodeBuffer(encryptedPassword);
return new String(cipher.doFinal(decodedValue), StandardCharsets.UTF_8);
} catch (GeneralSecurityException | IOException e) {
LOGGER.error("Crypto error: Unable to encrypt password");
throw new RuntimeException(e);
}
}
}