本文整理匯總了Java中org.apache.commons.codec.binary.Hex類的典型用法代碼示例。如果您正苦於以下問題:Java Hex類的具體用法?Java Hex怎麽用?Java Hex使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Hex類屬於org.apache.commons.codec.binary包,在下文中一共展示了Hex類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: hexDecode
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
/**
* Hex decode string.
*
* @param data the data
* @return the string
*/
public static String hexDecode(final char[] data) {
try {
final byte[] result = Hex.decodeHex(data);
return new String(result);
} catch (final Exception e) {
return null;
}
}
示例2: decodeHash
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
public byte[] decodeHash(String encodedHash)
{
if (!getEncodeHashAsBase64())
{
try
{
return Hex.decodeHex(encodedHash.toCharArray());
}
catch (DecoderException e)
{
throw new RuntimeException("Unable to decode password hash");
}
}
else
{
return Base64.decodeBase64(encodedHash.getBytes());
}
}
示例3: verify
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
@Override
public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception {
byte[] signatureBytes = null;
String signature = jwt.getSignature();
String urlDecoded = null;
switch (encodeType) {
case Base16:
urlDecoded = URLDecoder.decode(signature, "UTF-8");
signatureBytes = Hex.decodeHex(urlDecoded);
break;
case Base32:
Base32 base32 = new Base32();
urlDecoded = URLDecoder.decode(signature, "UTF-8");
signatureBytes = base32.decode(urlDecoded);
break;
case Base64:
signatureBytes = Base64.decodeBase64(signature);
break;
}
if (signatureBytes.length > 0) {
throw new SignatureVerificationException(this);
}
}
示例4: testIPv6Mask120
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
@Test
public void testIPv6Mask120() throws InvalidKeyException, DecoderException {
final int mask = 120;
final IPPseudonymizer ipv6Pseudonymizer = IPPseudonymizer.initIPv6Pseudonymizer("3AE1E5F99DD4FF7196FE64ACDE688C89", mask);
final byte[] ip = Hex.decodeHex("97010a9b423def694d2aa231011d1210".toCharArray());
final byte[] newIp = ipv6Pseudonymizer.pseudonymize(ip.clone());
for (int i = 0; i < mask / 8; i++) {
assertThat(newIp[i], is(equalTo(ip[i])));
}
for (int i = mask / 8; i < 16; i++) {
assertThat(newIp[i], is(not(equalTo(ip[i]))));
}
}
示例5: generateTransactionBlob
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
private TransactionBlob generateTransactionBlob() throws SdkException{
Chain.Transaction.Builder builder = Chain.Transaction.newBuilder();
if (txMetadata != null) {
builder.setMetadata(ByteString.copyFromUtf8(Hex.encodeHexString(txMetadata.getBytes())));
}
builder.setSourceAddress(sponsorAddress);
builder.setNonce(nonce);
long specifiedSeq = nodeManager.getLastSeq() + finalNotifySeqOffset;
logger.debug("specified seq:" + specifiedSeq);
for (BcOperation bcOperation : operationList) {
bcOperation.buildTransaction(builder, specifiedSeq);
}
cn.bubi.blockchain.adapter3.Chain.Transaction transaction = builder.build();
logger.info("transaction:" + transaction);
byte[] bytesBlob = transaction.toByteArray();
TransactionBlob transactionBlob = new TransactionBlob(bytesBlob, nodeManager.getCurrentSupportHashType());
// 設置最長等待超時通知
txFailManager.finalNotifyFailEvent(specifiedSeq, transactionBlob.getHash(), SdkError.TRANSACTION_ERROR_TIMEOUT);
return transactionBlob;
}
示例6: sendMessage
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
/**
* Sends MAVLink packet to RockBLOCK.
*
* @param packet MAVLink packet to send.
*/
public void sendMessage(MAVLinkPacket packet) throws ClientProtocolException, IOException {
if (packet == null)
return;
HttpPost httppost = new HttpPost(serviceURL);
String data = Hex.encodeHexString(packet.encodePacket());
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair(PARAM_IMEI, imei));
params.add(new BasicNameValuePair(PARAM_USERNAME, username));
params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
params.add(new BasicNameValuePair(PARAM_DATA, data));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String responseString = null;
if (entity != null) {
InputStream responseStream = entity.getContent();
try {
responseString = IOUtils.toString(responseStream);
} finally {
responseStream.close();
}
}
if (responseString == null || responseString.startsWith("FAILED")) {
throw new IOException(String.format("Failed to post message to RockBLOCK API. %s", responseString));
}
MAVLinkLogger.log(Level.INFO, "MT", packet);
}
示例7: verify
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
protected void verify(final Path file, final MessageDigest digest, final Checksum checksum) throws ChecksumException {
if(file.getType().contains(Path.Type.encrypted)) {
log.warn(String.format("Skip checksum verification for %s with client side encryption enabled", file));
return;
}
if(null == digest) {
log.debug(String.format("Digest disabled for file %s", file));
return;
}
if(null == checksum || !checksum.algorithm.equals(HashAlgorithm.md5)) {
log.warn("ETag returned by server is unknown checksum algorithm");
return;
}
if(!checksum.algorithm.equals(HashAlgorithm.md5)) {
log.warn(String.format("ETag %s returned by server is %s but expected MD5", checksum.hash, checksum.algorithm));
return;
}
// Obtain locally-calculated MD5 hash.
final String expected = Hex.encodeHexString(digest.digest());
// Compare our locally-calculated hash with the ETag returned by S3.
if(!checksum.equals(Checksum.parse(expected))) {
throw new ChecksumException(MessageFormat.format(LocaleFactory.localizedString("Upload {0} failed", "Error"), file.getName()),
MessageFormat.format("Mismatch between MD5 hash {0} of uploaded data and ETag {1} returned by the server",
expected, checksum.hash));
}
}
示例8: sendAsynchCommand
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
public static Message sendAsynchCommand(final String host, final int port, final CommandEnum command,
final Optional<ByteArraySerializable> payload, final JSONObject error) throws IOException {
final byte[] payloadBa;
if (payload.isPresent()) {
payloadBa = payload.get().toByteArray();
} else {
payloadBa = new byte[0];
}
final Message requestMessage = new Message(TestUtil.MAIN_NET_MAGIC, command, payloadBa);
final byte[] requestBa = requestMessage.toByteArray();
LOG.info(">>>:{}", Hex.encodeHexString(requestBa));
final byte[] responseBa = sendAsynch(host, port, requestBa, error);
LOG.info("<<<:{}", Hex.encodeHexString(responseBa));
if (responseBa.length == 0) {
return null;
}
final ByteBuffer bb = ByteBuffer.wrap(responseBa);
final Message responseMessage = new Message(bb);
if (responseMessage.magic != MAIN_NET_MAGIC) {
throw new RuntimeException("response magic was " + responseMessage.magic + " expected " + MAIN_NET_MAGIC);
}
return responseMessage;
}
示例9: decodeHex
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
/**
* decodes a hex string.
*
* @param string
* the string to decode.
* @return the decoded hex string.
*/
public static byte[] decodeHex(final String string) {
try {
return Hex.decodeHex(string.toCharArray());
} catch (final Exception e) {
throw new RuntimeException(e);
}
}
示例10: decodeHex
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
/**
* Hex解碼.
*/
public static byte[] decodeHex(String input) {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw Exceptions.unchecked(e);
}
}
示例11: process
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
@Override
public String process(int lineNumber, String result) throws DeserializeException {
while (result.contains("\\X2\\")) {
int index = result.indexOf("\\X2\\");
int indexOfEnd = result.indexOf("\\X0\\", index);
if (indexOfEnd == -1) {
throw new DeserializeException(lineNumber, "\\X2\\ not closed with \\X0\\");
}
if ((indexOfEnd - index) % 4 != 0) {
throw new DeserializeException(lineNumber, "Number of hex chars in \\X2\\ definition not divisible by 4");
}
try {
ByteBuffer buffer = ByteBuffer.wrap(Hex.decodeHex(result.substring(index + 4, indexOfEnd).toCharArray()));
CharBuffer decode = Charsets.UTF_16BE.decode(buffer);
result = result.substring(0, index) + decode.toString() + result.substring(indexOfEnd + 4);
} catch (DecoderException e) {
throw new DeserializeException(lineNumber, e);
}
}
return result;
}
示例12: signBase16Encoding
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
private String signBase16Encoding() throws UnsupportedEncodingException {
String header = URLEncoder.encode(headerJson, "UTF-8");
String payload = URLEncoder.encode(payloadJson, "UTF-8");
byte[] bHeader = header.getBytes("UTF-8");
String encodedHeader = Hex.encodeHexString(bHeader);
byte[] bPayload = payload.getBytes("UTF-8");
String encodedPayload = Hex.encodeHexString(bPayload);
String content = String.format("%s.%s", encodedHeader, encodedPayload);
byte[] signatureBytes = algorithm.sign(content.getBytes(StandardCharsets.UTF_8));
String signature = Hex.encodeHexString(signatureBytes);
String signatureFinal = URLEncoder.encode(signature, "UTF-8");
return String.format("%s.%s", content, signatureFinal);
}
示例13: testBcastPacket
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
@SuppressWarnings("static-access")
@Test
public void testBcastPacket() {
// This is Broadcast so set dstIpTarget to the broadcast IP
InetSocketAddress dstIpTarget = new InetSocketAddress(pvs.VERIFICATION_PACKET_IP_DST, 200);
// Generate the VerificationPacket
OFPacketOut packet = pvs.generateVerificationPacket(sw1, OFPort.of(1));
System.out.println("packet: " + Hex.encodeHexString(packet.getData()));
// Source MAC will always be that of sw1 for both Unicast and Broadcast
byte[] srcMac = Arrays.copyOfRange(packet.getData(), 6, 12);
assertArrayEquals(MacAddress.of(sw1HwAddrTarget).getBytes(), srcMac);
// Destination MAC should be that of BROADCAST for Broadcast Packet
byte[] dstMac = Arrays.copyOfRange(packet.getData(), 0, 6);
assertArrayEquals(MacAddress.of(pvs.VERIFICATION_BCAST_PACKET_DST).getBytes(), dstMac);
// Source IP is actual switch1 IP
byte[] srcIpActual = Arrays.copyOfRange(packet.getData(), 26, 30);
assertArrayEquals(srcIpTarget.getAddress().getAddress(), srcIpActual);
// Destination IP is that of DESTINATION BROADCAST IP
byte[] dstIpActual = Arrays.copyOfRange(packet.getData(), 30, 34);
assertArrayEquals(dstIpTarget.getAddress().getAddress(), dstIpActual);
}
示例14: createAccount
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
/**
* Create a new Ethereum account to be used for testing microraiden
* channels. Stores the account in the same folder where the
* program is run. Note - there is no encryption on this private key
* so it should be used for anything real!!
* @param accountFile - the name of the output file for the account
*/
public void createAccount(String accountFile) {
ECKey keyPair = new ECKey();
String address = new String(Hex.encodeHex(keyPair.getAddress()));
System.out.println("Generated new account: 0x" + address);
byte[] priv = keyPair.getPrivKeyBytes();
try {
OutputStream os = new FileOutputStream(accountFile + ".pkey");
JSONObject obj=new JSONObject();
obj.put("privkey", new String(Hex.encodeHex(priv)));
obj.put("address", address);
os.write(obj.toJSONString().getBytes());
os.close();
} catch (IOException e) {
System.out.println("Couldn't write to file: " + accountFile + " " + e.toString());
}
}
示例15: generateVerifier
import org.apache.commons.codec.binary.Hex; //導入依賴的package包/類
/**
* @param face the the verifier should be generated for
* @return Verifier
*/
@NotNull
private Verifier generateVerifier(@NotNull Face face) throws MacFailedException, InvalidKeyException {
Optional<byte[]> cborData = Utils.serializeCbor(face);
if(cborData.isPresent()) {
Optional<byte[]> psk = getPsk(face.getSai());
if (psk.isPresent()) {
logger.debug("computeMac with payload: " + Hex.encodeHexString(cborData.get())
+ " and algorithm: " + face.getMacMethod().algorithmName);
byte[] mac = Utils.computeMac(face.getMacMethod(), psk.get(), cborData.get());
return new Verifier(mac);
}
}
return new Verifier(new byte[]{});
}