繁体   English   中英

在Java中从String转换为Hex

[英]Coverting from String to Hex in Java

我们如何在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编码中的字节转换回字符串,这可能不是您想要的字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM