我有我使用加密的javax.crypto.Cipher中的相同方式使用bash腳本加密的字符串。在java中,我使用帶有「」鍵的AES-256。但是,當我使用OpenSSL的,我不得不轉換 「」 爲十六進制,但結果是不一樣的java的Java那樣
echo "lun01" | openssl aes-256-cbc -e -a -K 7573746f726530313233343536373839 -iv 7573746f726530313233343536373839
dpMyN7L5HI8VZEs1biQJ7g ==的
的Java:
public class CryptUtil {
public static final String DEFAULT_KEY = "";
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'是字符'ustore'不是''加空值,而@Artjom說 您的Java執行AES-128 ECB模式(以及PKCS#5填充哪個OpenSSL也是)。 此外,'echo'命令(在bash中內置)爲數據添加了一個換行符,但是您的Java不會,並且'openssl enc -a'將結果編碼爲base64而不是hex。修復這些: 'echo -n lun01 | openssl aes-128-ecb -K 30313233343536373839000000000000 | od -tx1'給出'0000000 d2 30 b2 16 e9 d6 59 64 ab d4 09 2f 5c 45 5a 21'匹配您的Java結果。 –