Convert Hex-Encoded String to String

Convert hex-encoded String to String

You want to use the hex encoded data as an AES key, but the
data is not a valid UTF-8 sequence. You could interpret
it as a string in ISO Latin encoding, but the AES(key: String, ...)
initializer converts the string back to its UTF-8 representation,
i.e. you'll get different key data from what you started with.

Therefore you should not convert it to a string at all. Use the

extension Data {
init?(fromHexEncodedString string: String)
}

method from hex/binary string conversion in Swift
to convert the hex encoded string to Data and then pass that
as an array to the AES(key: Array<UInt8>, ...) initializer:

let hexkey = "dcb04a9e103a5cd8b53763051cef09bc66abe029fdebae5e1d417e2ffc2a07a4"
let key = Array(Data(fromHexEncodedString: hexkey)!)

let encrypted = try AES(key: key, ....)

How can I convert hex encoded string to string in C efficiently

Instead of copying two characters and using strtol you could create a function that converts the characters 0 .. 9 and A .. F to an int (0x0 to 0xF).

#include <ctype.h>

int toval(char ch) {
if (isdigit((unsigned char)ch)) return ch - '0';
return toupper((unsigned char)ch) - 'A' + 0x10;
}

Then looping over the string and adding up the result will be pretty straight forward:

void htostr(char *wr, const char *rd) {
for (; rd[0] != '\0' && rd[1] != '\0'; rd += 2, ++wr) {
// multiply the first with 0x10 and add the value of the second
*wr = toval(rd[0]) * 0x10 + toval(rd[1]);
}
*wr = '\0'; // null terminate
}

Example usage:

#include <stdio.h>

int main() {
char hstr[] = "61626364";
char res[1 + sizeof hstr / 2];

htostr(res, hstr);

printf(">%s<\n", res);
}

Hex string to text conversion - swift 3

You probably can use something like this:

func hexToStr(text: String) -> String {

let regex = try! NSRegularExpression(pattern: "(0x)?([0-9A-Fa-f]{2})", options: .caseInsensitive)
let textNS = text as NSString
let matchesArray = regex.matches(in: textNS as String, options: [], range: NSMakeRange(0, textNS.length))
let characters = matchesArray.map {
Character(UnicodeScalar(UInt32(textNS.substring(with: $0.rangeAt(2)), radix: 16)!)!)
}

return String(characters)
}

Hex to String & String to Hex conversion in nodejs

You need to use Buffer.from() for decoding as well. Consider writing a higher-order function to reduce the amount of repeated code:

const convert = (from, to) => str => Buffer.from(str, from).toString(to)
const utf8ToHex = convert('utf8', 'hex')
const hexToUtf8 = convert('hex', 'utf8')

hexToUtf8(utf8ToHex('dailyfile.host')) === 'dailyfile.host'

Converting from hex to string

Like so?

static void Main()
{
byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}

Convert a string representation of a hex dump to a byte array using Java?

Update (2021) - Java 17 now includes java.util.HexFormat (only took 25 years):

HexFormat.of().parseHex(s)


For older versions of Java:

Here's a solution that I think is better than any posted so far:

/* s must be an even-length string. */
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}

Reasons why it is an improvement:

  • Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte)

  • Doesn't convert the String into a char[], or create StringBuilder and String objects for every single byte.

  • No library dependencies that may not be available

Feel free to add argument checking via assert or exceptions if the argument is not known to be safe.

String Hex Encoding and Decoding


new String(source.getBytes(inputCharacterCoding), outputCharacterCoding)
.getBytes()

This probably does not do what you think it does.

First things first: a String has no encoding. Repeat after me: a String has no encoding.

A String is simply a sequence of tokens which aim to represent characters. It just happens that for this purpose Java uses a sequence of chars. They could just as well be carrier pigeons.

UTF8, CP1047 and others are just character codings; two operations can be performed:

  • encoding: turn a stream of carrier pigeons (chars) into a stream of bytes;
  • decoding: turn a stream of bytes into a stream of carrier pigeons (chars).

Basically, your base assumption is wrong; you cannot associate an encoding with a String. Your real input should be a byte stream (more often than not a byte array) which you know is the result of a particular encoding (in your case, UTF-8), which you want to re-encode using another charset (in your case, CP1047).

The "secret" behing a real answer here would be the code of your Hex.encodeHex() method but you don't show it, so this is as good an answer that I can muster.



Related Topics



Leave a reply



Submit