我们如何在java中将String从String转换为Hex
这段代码是AES加密算法的一部分,我有这个方法将加密值返回为:String我需要它来将结果返回为Hex。
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;
}
我会建议这样的事情:
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编码中的字节转换回字符串,这可能不是您想要的字符串。