下面列出了 org.apache.commons.codec.binary.Hex # decodeHex ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void testSymbol(String hex) throws Exception {
byte[] data = Hex.decodeHex(hex.toCharArray());
ByteBuffer buffer = ByteBuffer.wrap(data);
int packetSize = buffer.getInt();
buffer.get(); // type
data = new byte[packetSize];
buffer.get(data);
buffer = ByteBuffer.wrap(data);
long count = Utils.unpack_dd(buffer);
for (int i = 0; i < count; i++) {
long address = Utils.unpack_dq(buffer);
long b2 = Utils.unpack_dd(buffer);
long b3 = Utils.unpack_dd(buffer);
String name = Utils.readCString(buffer);
System.out.println("address=0x" + Long.toHexString(address) + ", b2=" + b2 + ", b3=" + b3 + ", name=" + name);
}
data = new byte[buffer.remaining()];
buffer.get(data);
Inspector.inspect(data, "Remaining");
}
@Test
public void testOutBoundAndInboundSpan() throws Exception {
TracingConfig tracingConfig =
new TracingConfig(
"tracingHandlerClientIntegrationTest", config().getConfig("settings.tracing"));
val client = newClient(new FakeTracer(tracingConfig));
val request =
DefaultSegmentedRequest.builder()
.method(GET)
.path("/v1/authinit")
.host("127.0.0.1" + ":" + server.getPort())
.build();
client.write(request);
// We wait on the local future because this signals the full roundtrip between outbound and
// return trip from the Application Handler out and then back in.
local.get();
assertEquals(reportedSpans.size(), 1);
val responseHex = ByteBufUtil.hexDump(((SegmentedData) response).content());
byte[] bytes = Hex.decodeHex(responseHex.toCharArray());
assertEquals(expectedResponse, new String(bytes, "UTF-8"));
}
/**
* Hex解码, String->byte[].
*/
public static byte[] decodeHex(String input) {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw new IllegalStateException("Hex Decoder exception", e);
}
}
/**
* Decodes the hex string. Null if failed.
*
* @param hexString string in hex format
* @return converted ascii string
*/
public static String decodeHex(String hexString){
if(hexString == null){
return null;
}else{
try{
return new String(Hex.decodeHex(hexString.toCharArray()));
}catch(Exception e){
// ignore
return null;
}
}
}
@Test
public void testSerialize() throws IOException, ClassNotFoundException, DecoderException {
OnlineSession session = new OnlineSession();
session.setId(123);
session.setHost("127.0.0.1");
session.setTimeout(1);
session.setUserId(123L);
session.setAttribute("z", "z");
session.setStatus(OnlineSession.OnlineStatus.force_logout);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(session);
oos.close();
bos.close();
byte[] objectBytes = bos.toByteArray();
String str = Hex.encodeHexString(objectBytes);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(Hex.decodeHex(str.toCharArray())));
OnlineSession actualSession = (OnlineSession) ois.readObject();
ois.close();
Assert.assertEquals(session.getId(), actualSession.getId());
Assert.assertEquals(session.getHost(), actualSession.getHost());
Assert.assertEquals(session.getTimeout(), actualSession.getTimeout());
Assert.assertEquals(session.getUserId(), actualSession.getUserId());
Assert.assertEquals(session.getAttributes().get("z"), actualSession.getAttributes().get("z"));
Assert.assertEquals(session.getStatus(), actualSession.getStatus());
Assert.assertEquals(session.getSystemHost(), actualSession.getSystemHost());
}
@Override
protected byte[] decodeFromString(String value) {
try {
return Hex.decodeHex(value.toCharArray());
} catch (DecoderException e) {
throw new IllegalArgumentException("Value '" + value + "' can't be decoded as hex", e);
}
}
@Override
public ValidationResult validate(final String subject, final String input, final ValidationContext validationContext) {
try {
Hex.decodeHex(input.toCharArray());
return new ValidationResult.Builder().valid(true).input(input).subject(subject).build();
} catch (final Exception e) {
return new ValidationResult.Builder().valid(false).explanation("Not a valid Hex String").input(input).subject(subject).build();
}
}
/**
* Converts a Hex encoded string to a byte array.
*
* @param stringValue Hex encoded string
* @return Decoded byte array
*/
public static byte[] toBytes(String stringValue) {
try {
return Hex.decodeHex(stringValue.toCharArray());
} catch (DecoderException e) {
throw new IllegalArgumentException("Value: " + stringValue + " is not Hex encoded", e);
}
}
/**
* Transform an hexadecimal String to a byte array.
*/
public static byte[] hexStringToByte(String hexString) {
try {
return Hex.decodeHex(hexString.toCharArray());
} catch (DecoderException e) {
throw new UnexpectedException(e);
}
}
/**
* Sets the secret key as a HEX string. It should be long enough to be hard
* to recover with a brute force attack.
*
* @x.category GETSET
*/
public void setSecretKey(String secretKey) {
try {
this.secretKey = Hex.decodeHex(secretKey.toCharArray());
} catch (DecoderException e) {
throw new ConfigurationException(
"Invalid secret key: " + secretKey, e);
}
}
public static byte[] stringToHash(String str) {
if (str == null || str.equals("")) {
return null;
}
try {
return Hex.decodeHex(str.toCharArray());
} catch (DecoderException e) {
return null;
}
}
private void decodeProfiles(String profilesInfo, ProfileInfoListResponse profiles) throws DecoderException, IOException {
InputStream is = new ByteArrayInputStream(Hex.decodeHex(profilesInfo.toCharArray()));
profiles.decode(is);
if (LogStub.getInstance().isDebugEnabled()) {
LogStub.getInstance().logDebug (LOG,"Profile list object: " + profiles.toString());
}
}
@Override
public boolean processCommand(Emulator<?> emulator, GdbStub stub, String command) {
if (command.startsWith("qSupported")) {
stub.makePacketAndSend("PacketSize=" + DebugServer.PACKET_SIZE + ";vContSupported+;multiprocess-;xmlRegisters=arm");
return true;
}
if (command.startsWith("qAttached")) {
stub.makePacketAndSend("1");
return true;
}
if (command.startsWith("qC")) {
stub.makePacketAndSend("QC1");
return true;
}
if (command.startsWith("qfThreadInfo")) {
stub.makePacketAndSend("m01");
return true;
}
if (command.startsWith("qsThreadInfo")) {
stub.makePacketAndSend("l");
return true;
}
if (command.startsWith("qRcmd,")) {
try {
String cmd = new String(Hex.decodeHex(command.substring(6).toCharArray()), StandardCharsets.UTF_8);
if (log.isDebugEnabled()) {
log.debug("qRcmd=" + cmd);
}
stub.makePacketAndSend("E01");
return true;
} catch (DecoderException e) {
throw new IllegalStateException(e);
}
}
return false;
}
public static StaticBuffer decodeKey(final String name) {
try {
return new StaticArrayBuffer(Hex.decodeHex(name.toCharArray()));
} catch (DecoderException e) {
throw new RuntimeException(e);
}
}
public static byte[] fromHex(String hex) {
try {
return Hex.decodeHex(hex.toCharArray());
} catch (DecoderException e) {
throw new RuntimeException("Failed to decode hex: " + hex, e);
}
}
public static byte[] hex(String str) {
try {
return Hex.decodeHex(str.toCharArray());
}
catch (DecoderException e) {
throw new IllegalStateException(e);
}
}
/**
* Converts a string value to a decoded binary
*
* @param data String value to convert to decoded hex
* @return Decoded binary from the string value specified
*/
private byte[] fromString(final String data) {
try {
return Hex.decodeHex(data.toCharArray());
} catch (final DecoderException e) {
LOGGER.error(e.getLocalizedMessage(), e);
return null;
}
}
private List<ValidationResult> validateKeyed(EncryptionMethod encryptionMethod, KeyDerivationFunction kdf, String keyHex) {
List<ValidationResult> validationResults = new ArrayList<>();
boolean limitedStrengthCrypto = !PasswordBasedEncryptor.supportsUnlimitedStrength();
if (limitedStrengthCrypto) {
if (encryptionMethod.isUnlimitedStrength()) {
validationResults.add(new ValidationResult.Builder().subject(ENCRYPTION_ALGORITHM.getName())
.explanation(encryptionMethod.name() + " (" + encryptionMethod.getAlgorithm() + ") is not supported by this JVM due to lacking JCE Unlimited " +
"Strength Jurisdiction Policy files. See Admin Guide.").build());
}
}
int allowedKeyLength = PasswordBasedEncryptor.getMaxAllowedKeyLength(ENCRYPTION_ALGORITHM.getName());
if (StringUtils.isEmpty(keyHex)) {
validationResults.add(new ValidationResult.Builder().subject(RAW_KEY_HEX.getName())
.explanation(RAW_KEY_HEX.getDisplayName() + " is required when using algorithm " + encryptionMethod.getAlgorithm() + ". See Admin Guide.").build());
} else {
byte[] keyBytes = new byte[0];
try {
keyBytes = Hex.decodeHex(keyHex.toCharArray());
} catch (DecoderException e) {
validationResults.add(new ValidationResult.Builder().subject(RAW_KEY_HEX.getName())
.explanation("Key must be valid hexadecimal string. See Admin Guide.").build());
}
if (keyBytes.length * 8 > allowedKeyLength) {
validationResults.add(new ValidationResult.Builder().subject(RAW_KEY_HEX.getName())
.explanation("Key length greater than " + allowedKeyLength + " bits is not supported by this JVM" +
" due to lacking JCE Unlimited Strength Jurisdiction Policy files. See Admin Guide.").build());
}
if (!CipherUtility.isValidKeyLengthForAlgorithm(keyBytes.length * 8, encryptionMethod.getAlgorithm())) {
List<Integer> validKeyLengths = CipherUtility.getValidKeyLengthsForAlgorithm(encryptionMethod.getAlgorithm());
validationResults.add(new ValidationResult.Builder().subject(RAW_KEY_HEX.getName())
.explanation("Key must be valid length [" + StringUtils.join(validKeyLengths, ", ") + "]. See Admin Guide.").build());
}
}
// Perform some analysis on the selected encryption algorithm to ensure the JVM can support it and the associated key
List<String> kdfsForKeyedCipher = getKDFsForKeyedCipher();
if (kdf == null || !kdfsForKeyedCipher.contains(kdf.name())) {
validationResults.add(new ValidationResult.Builder().subject(KEY_DERIVATION_FUNCTION.getName())
.explanation(KEY_DERIVATION_FUNCTION.getDisplayName() + " is required to be " + StringUtils.join(kdfsForKeyedCipher, ", ") + " when using algorithm " +
encryptionMethod.getAlgorithm()).build());
}
return validationResults;
}
/**
* Decodes the given string by using the hexadecimal representation of its UTF-8 bytes.
*
* @param s The string to decode.
* @return The decoded string.
* @throws Exception If an error occurs.
*/
public static String utf8HexDecode(String s) throws Exception {
if (s == null) {
return null;
}
return new String(Hex.decodeHex(s.toCharArray()), ENCODING_UTF8);
}
/**
* Covert hex to bytes
*
* @param hex string to convert
* @return bytes representation
* @throws DecoderException if invalid data encountered
*/
@Nullable
private static byte[] fromHex(String hex) throws DecoderException {
return hex == null ? null : Hex.decodeHex(hex.toCharArray());
}