0

How can we convert from String to Hex in java

This code is part of AES encryption algorithm, I have this method that return the encrypted value as: String I need it to return the result as Hex instead .

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;
}
Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42
sara
  • 9
  • 2
  • Possible duplicate of [how to convert a char from alphabetical character to hexadecimal number in java](https://stackoverflow.com/questions/4477714/how-to-convert-a-char-from-alphabetical-character-to-hexadecimal-number-in-java) – Rann Lifshitz Apr 18 '19 at 11:17
  • 4
    Possible duplicate of [Converting A String To Hexadecimal In Java](https://stackoverflow.com/questions/923863/converting-a-string-to-hexadecimal-in-java) – Cray Apr 18 '19 at 11:18

1 Answers1

0

I would suggest something like this:

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();
}

In your original code you already converted the bytes from the Base64 encoding back to a string using the default charset, which is probably not what you want there.

TheWhiteRabbit
  • 1,253
  • 1
  • 5
  • 18
  • Glad to help and welcome to SO. If an answer works for you please vote it up and accept it, SO discourages 'thank you' messages in comments. :-) – TheWhiteRabbit Apr 18 '19 at 13:29
  • I need to feed this output to be the input of Decrypt method, but I got this Error message: Input length must be multiple of 16 when decrypting with padded cipher – sara Apr 18 '19 at 15:19
  • I would suggest creating a new question for this with both the source code of your encrypt and decrypt method as this indicates a different problem. Most likely a discrepancy between both methods, but I can't tell for sure without the full context. Also have a look at this topic, it described the same issue, maybe you'll find an answer there? https://stackoverflow.com/questions/10494764/input-length-must-be-multiple-of-16-when-decrypting-with-padded-cipher – TheWhiteRabbit Apr 19 '19 at 06:07