I have to encrypt an string using bash script in the same way I encrypt using javax.crypto.Cipher. At java I use AES-256 with the key "0123456789". But When I use openssl I had to convert "0123456789" to hex, but the result is not the same of the java
echo "lun01" | openssl aes-256-cbc -e -a -K 7573746f726530313233343536373839 -iv 7573746f726530313233343536373839
dpMyN7L5HI8VZEs1biQJ7g==
Java:
public class CryptUtil {
public static final String DEFAULT_KEY = "0123456789";
private static CryptUtil instance;
private String chiperKey;
private CryptUtil(String chiperKey) {
this.chiperKey = chiperKey;
}
public static CryptUtil getInstance() {
if (null == instance) {
instance = new CryptUtil(DEFAULT_KEY);
}
return instance;
}
public static CryptUtil getInstance(String cipherkey) {
instance = new CryptUtil(cipherkey);
return instance;
}
public String aesEncrypt(String plainText) {
byte[] keyBytes = Arrays.copyOf(this.chiperKey.getBytes("ASCII"), 16);
SecretKey key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cleartext = plainText.getBytes("UTF-8");
byte[] ciphertextBytes = cipher.doFinal(cleartext);
final char[] encodeHex = Hex.encodeHex(ciphertextBytes);
return new String(encodeHex);
return null;
}
public static void main(String[] args) {
CryptUtil cryptUtil = CryptUtil.getInstance();
System.out.println(cryptUtil.aesEncrypt("lun01"));
}
}
d230b216e9d65964abd4092f5c455a21
7573746f726530313233343536373839
is the charactersustore0123456789
not0123456789
plus nulls, and as @Artjom says your Java does AES-128 ECB mode (and PKCS#5 padding which OpenSSL also does). Further, theecho
command (in bash a builtin) adds a newline to the data but your Java doesn't, andopenssl enc -a
encodes the result in base64 not hex. Fixing these:echo -n lun01 |openssl aes-128-ecb -K 30313233343536373839000000000000 |od -tx1
gives0000000 d2 30 b2 16 e9 d6 59 64 ab d4 09 2f 5c 45 5a 21
matching your Java result. – Smolensk