Java中从String到Hex的覆盖

时间:2019-04-18 11:14:46

标签: java string hex

我们如何在Java中将String转换为Hex

此代码是AES加密算法的一部分,我有此方法将加密后的值返回为:字符串,我需要它以十六进制形式返回结果。

public static String encrypt(String Data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = c.doFinal(Data.getBytes());

    String encryptedValue = new String( Base64.getEncoder().encode(encVal) ) ;
    return encryptedValue;
}

1 个答案:

答案 0 :(得分:0)

我建议这样的事情:

public static String encrypt(String Data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] encVal = c.doFinal(Data.getBytes());

    // simply store the encoded byte array here
    byte[] bytes = Base64.getEncoder().encode(encVal);

    // loop over the bytes and append each byte as hex string
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for(byte b : bytes)
       sb.append(String.format("%02x", b));
    return sb.toString();
}

在原始代码中,您已经使用默认字符集将Base64编码的字节转换回字符串,这可能不是您想要的。