I am using AesCipherService
from Apache Shiro.
For some reason, I can't get it to work like http://aesencryption.net/.
My code is basically this:
String encrypt(String input) throws Exception {
StringBuilder builder = new StringBuilder();
AesCipherService aesCipher = new AesCipherService();
byte[] bytes = aesCipher.encrypt(input.getBytes(), "0123456789abcdef".getBytes()).getBytes();
String aesProduct = new String(bytes);
builder.append(aesProduct);
byte[] bytesEncoded = Base64.encodeBase64(builder.toString().getBytes());
return new String(bytesEncoded);
}
If you encrypt "Hello" you will get
Shvvv71GB++/vULvv73vv71/Zu+/vRIc77+977+9Y33bkmrvv70SOWffqXTvv71777+977+9
When that site outputs
IM/5UIbDXWhuPz2ZFKyScQ==
What did I do wrong with the code?
Looks like you may be doing Base 64 encoding more than once. Also, that site uses "ECB" mode, which is not the default in Cipher. So, you are seeing the difference in outputs. It is important that encryption and decryption use same algorithm.
Below is corrected code.
import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.crypto.AesCipherService;
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(encrypt("Hello"));
}
static String encrypt(String input) throws Exception {
AesCipherService aesCipher = new AesCipherService();
aesCipher.setModeName("ECB");
byte[] bytes = aesCipher.encrypt(input.getBytes("UTF-8"), "0123456789abcdef".getBytes()).getBytes();
byte[] bytesEncoded = Base64.encodeBase64(bytes);
return new String(bytesEncoded);
}
}
This produces
xqkuF4FDmucSdb410R0HPw==
NOTE: This is not same as what site produces for same input, however, this string can be decrypted on the site. I am not sure what is the reason of the difference.