当前位置: 首页>>代码示例>>Java>>正文


Java Hex类代码示例

本文整理汇总了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;
    }
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:15,代码来源:EncodingUtils.java

示例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());
    }
}
 
开发者ID:Alfresco,项目名称:alfresco-repository,代码行数:19,代码来源:MD4PasswordEncoderImpl.java

示例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);
    }
}
 
开发者ID:GJWT,项目名称:javaOIDCMsg,代码行数:24,代码来源:NoneAlgorithm.java

示例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]))));
    }
}
 
开发者ID:NCSC-NL,项目名称:PEF,代码行数:17,代码来源:IPPseudonymizerTest.java

示例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;
}
 
开发者ID:bubicn,项目名称:bubichain-sdk-java,代码行数:27,代码来源:Transaction.java

示例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);
}
 
开发者ID:envirover,项目名称:SPLGroundControl,代码行数:43,代码来源:RockBlockClient.java

示例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));
    }
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:27,代码来源:HttpUploadFeature.java

示例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;
}
 
开发者ID:coranos,项目名称:neo-java,代码行数:24,代码来源:TestUtil.java

示例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);
	}
}
 
开发者ID:coranos,项目名称:neo-java,代码行数:15,代码来源:ModelUtil.java

示例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);
    }
}
 
开发者ID:NeilRen,项目名称:NEILREN4J,代码行数:11,代码来源:Encodes.java

示例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;
}
 
开发者ID:shenan4321,项目名称:BIMplatform,代码行数:22,代码来源:X2Pass.java

示例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);
}
 
开发者ID:GJWT,项目名称:javaOIDCMsg,代码行数:18,代码来源:JWTCreator.java

示例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);
}
 
开发者ID:telstra,项目名称:open-kilda,代码行数:27,代码来源:PathVerificationPacketOutTest.java

示例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());
    }
}
 
开发者ID:RightMesh,项目名称:microraiden-java,代码行数:25,代码来源:MicroRaiden.java

示例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[]{});
  }
 
开发者ID:beduino-project,项目名称:dcaf-java,代码行数:23,代码来源:LocalServerAuthorizationManager.java


注:本文中的org.apache.commons.codec.binary.Hex类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。