我需要使用bash脚本以与javax.crypto.Cipher相同的方式加密字符串。在Java中,我使用AES-256和密钥“0123456789”。但是,当我使用openssl时,我必须将“0123456789”转换为十六进制,但结果与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
是字符ustore0123456789
而不是0123456789
加上空字符,正如 @Artjom 所说的那样,你的 Java 使用 AES-128 ECB 模式(和 OpenSSL 一样使用 PKCS#5 填充)。此外,echo
命令(在 bash 中是内置命令)会向数据添加一个换行符,但是你的 Java 没有这样做,而openssl enc -a
将结果编码为 base64 而不是十六进制。修复这些问题:echo -n lun01 |openssl aes-128-ecb -K 30313233343536373839000000000000 |od -tx1
给出了与你的 Java 结果相匹配的0000000 d2 30 b2 16 e9 d6 59 64 ab d4 09 2f 5c 45 5a 21
。 - dave_thompson_085