Java 类org.apache.commons.codec.binary.Hex 实例源码

项目:cas-5.1.0    文件:EncodingUtils.java   
/**
 * 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;
    }
}
项目:alfresco-repository    文件:MD4PasswordEncoderImpl.java   
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());
    }
}
项目:javaOIDCMsg    文件:NoneAlgorithm.java   
@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);
    }
}
项目:PEF    文件:IPPseudonymizerTest.java   
@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]))));
    }
}
项目:bubichain-sdk-java    文件:Transaction.java   
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;
}
项目:cyberduck    文件:HttpUploadFeature.java   
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));
    }
}
项目:neo-java    文件:TestUtil.java   
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;
}
项目:neo-java    文件:ModelUtil.java   
/**
 * 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);
    }
}
项目:NEILREN4J    文件:Encodes.java   
/**
 * Hex解码.
 */
public static byte[] decodeHex(String input) {
    try {
        return Hex.decodeHex(input.toCharArray());
    } catch (DecoderException e) {
        throw Exceptions.unchecked(e);
    }
}
项目:BIMplatform    文件:X2Pass.java   
@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;
}
项目:javaOIDCMsg    文件:JWTCreator.java   
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);
}
项目:open-kilda    文件:PathVerificationPacketOutTest.java   
@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);
}
项目:microraiden-java    文件:MicroRaiden.java   
/**
 * 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());
    }
}
项目:dcaf-java    文件:LocalServerAuthorizationManager.java   
/**
   * @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[]{});
  }
项目:org.openhab.binding.loxone    文件:LxWsClient.java   
/**
 * Hash user name and password according to the algorithm required by the Miniserver
 *
 * @param hashKeyHex
 *            string with hash key received from the Miniserver in hex characters
 * @return
 *         hashed credentials to send to the Miniserver for authentication
 */
private String hashCredentials(String hashKeyHex) {
    if (user == null || password == null || hashKeyHex == null) {
        return null;
    }
    try {
        byte[] hashKeyBytes = Hex.decodeHex(hashKeyHex.toCharArray());
        SecretKeySpec signKey = new SecretKeySpec(hashKeyBytes, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signKey);
        String data = user + ":" + password;
        byte[] rawData = mac.doFinal(data.getBytes());
        byte[] hexData = new Hex().encode(rawData);
        return new String(hexData, "UTF-8");
    } catch (DecoderException | NoSuchAlgorithmException | InvalidKeyException
            | UnsupportedEncodingException e) {
        logger.debug("[{}] Error encrypting credentials: {}", debugId, e.getMessage());
        return null;
    }
}
项目:alfresco-repository    文件:MessageDigestPasswordEncoder.java   
/**
 * Encodes the rawPass using a MessageDigest. If a salt is specified it will
 * be merged with the password before encoding.
 * 
 * @param rawPass
 *            The plain text password
 * @param salt
 *            The salt to sprinkle
 * @return Hex string of password digest (or base64 encoded string if
 *         encodeHashAsBase64 is enabled.
 */
public String encodePassword(String rawPass, Object salt)
{
    String saltedPass = mergePasswordAndSalt(rawPass, salt, false);

    MessageDigest messageDigest = getMessageDigest();

    byte[] digest;

    try
    {
        digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e)
    {
        throw new IllegalStateException("UTF-8 not supported!");
    }

    if (getEncodeHashAsBase64())
    {
        return new String(Base64.encodeBase64(digest));
    } else
    {
        return new String(Hex.encodeHex(digest));
    }
}
项目:ExcelHandle    文件:Encodes.java   
/**
 * Hex解码.
 */
public static byte[] decodeHex(String input) {
    try {
        return Hex.decodeHex(input.toCharArray());
    } catch (DecoderException e) {
        return "".getBytes();
    }
}
项目:ethereum-bytecode-analyzer    文件:ArithmeticOpcodesTest.java   
@Test
public void test_div_2() throws Exception {

    BigInteger div = new BigInteger("3f7a027000000000000000000000000000000000000000000000000000000000", 16);
    BigInteger divBy = new BigInteger("100000000000000000000000000000000000000000000000000000000", 16);
    BytecodeChunk chunk = createChunk(0,
            new Opcode(Opcodes.PUSH1, divBy),
            new Opcode(Opcodes.PUSH1, div),
            new Opcode(Opcodes.DIV, null),
            new Opcode(Opcodes.STOP, null)
    );
    EVMState evmState = symExecute(new HashMap<Integer, BytecodeChunk>() {{
        put(0, chunk);
    }});
    EVMStack stack = evmState.getStack();
    assertTrue(stack.size() == 1);
    TraceableWord result = stack.pop();
    assertTrue(Arrays.equals(Hex.decodeHex("3f7a0270"), result.getBytes()));
}
项目:neo-java    文件:LocalControllerNode.java   
/**
 * does something on a "block" message.
 *
 * @param peer
 *            the peer that sent the message.
 * @param message
 *            the message.
 */
private void onBlock(final RemoteNodeControllerRunnable peer, final Message message) {
    if (stopped) {
        return;
    }
    final Block newBlock = message.getPayload(Block.class);

    final String expected = new String(Hex.encodeHexString(message.getPayloadByteArray()));
    final String actual = Hex.encodeHexString(newBlock.toByteArray());

    if (!expected.equals(actual)) {
        LOG.error("onBlock newBlock: {}", newBlock);
        LOG.error("onBlock expected: {}", expected);
        LOG.error("onBlock actual  : {}", actual);
        return;
    }

    LocalNodeDataSynchronizedUtil.addUnverifiedBlock(localNodeData, newBlock);
    // LocalNodeDataSynchronizedUtil.verifyUnverifiedBlocks(localNodeData);
}
项目:bitbreeds-webrtc    文件:SCTPImpl.java   
/**
 * Handle message and create a response
 * @param input the incoming message
 * @return a byte response, an empty array is equal to no response.
 */
public List<byte[]> handleRequest(byte[] input) {
    SCTPMessage inFullMessage = SCTPMessage.fromBytes(input);

    logger.debug("Input Parsed: " + inFullMessage );

    logger.debug("Flags: " + Hex.encodeHexString(new byte[]{input[13]}));

    SCTPHeader inHdr = inFullMessage.getHeader();
    List<SCTPChunk> inChunks = inFullMessage.getChunks();

    return inChunks.stream()
            .map(chunk -> {
                MessageHandler handler = handlerMap.get(chunk.getType());
                if (handler != null) {

                    Optional<SCTPMessage> out = handler.handleMessage(this, context, inHdr, chunk);
                    return out.map(i -> SCTPUtil.addChecksum(i).toBytes()).orElse(new byte[]{});
                } else {
                    logger.warn("Not handled messagetype: " + chunk.getType());
                    return new byte[]{};
                }
            }).collect(Collectors.toList());
}
项目:logistimo-web-service    文件:TransactionUtil.java   
public static String checksum(Long domainId, List<ITransaction> list) {
  xLogger.fine("Entered checksum: {0}", (list == null ? "NULL" : list.size()));
  Iterator<ITransaction> it = list.iterator();
  try {
    MessageDigest md = MessageDigest.getInstance("MD5");
    while (it.hasNext()) {
      ITransaction trans = it.next();
      if (trans.getDomainId() == null) {
        trans.setDomainId(domainId);
      }
      byte[] fingerprint = trans.fingerprint();
      if (fingerprint != null) {
        md.update(fingerprint);
      }
    }
    return new String(Hex.encodeHex(md.digest()));
  } catch (Exception e) {
    xLogger.warn("{0} when getting checksum: {1}", e.getClass().getName(), e.getMessage());
    return null;
  }
}
项目:flume-release-1.7.0    文件:AvroEventDeserializer.java   
private void initialize() throws IOException, NoSuchAlgorithmException {
  SeekableResettableInputBridge in = new SeekableResettableInputBridge(ris);
  long pos = in.tell();
  in.seek(0L);
  fileReader = new DataFileReader<GenericRecord>(in,
      new GenericDatumReader<GenericRecord>());
  fileReader.sync(pos);

  schema = fileReader.getSchema();
  datumWriter = new GenericDatumWriter(schema);
  out = new ByteArrayOutputStream();
  encoder = EncoderFactory.get().binaryEncoder(out, encoder);

  schemaHash = SchemaNormalization.parsingFingerprint("CRC-64-AVRO", schema);
  schemaHashString = Hex.encodeHexString(schemaHash);
}
项目:asch-java    文件:Decoding.java   
public static byte[] hex(String hexString) throws DecodingException{
    try {
        return Hex.decodeHex(hexString.toCharArray());
    }
    catch (Exception ex){
        throw new DecodingException("decode hex failed",ex);
    }
}
项目:hive-udf-backports    文件:UDFMd5.java   
/**
 * Convert String to md5
 */
public Text evaluate(Text n) {
  if (n == null) {
    return null;
  }

  digest.reset();
  digest.update(n.getBytes(), 0, n.getLength());
  byte[] md5Bytes = digest.digest();
  String md5Hex = Hex.encodeHexString(md5Bytes);

  result.set(md5Hex);
  return result;
}
项目:SPLGroundControl    文件:RockBlockClient.java   
/**
 * 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);
}
项目:SPLGroundControl    文件:RockBlockService.java   
private MAVLinkPacket getPacket(String data) throws DecoderException {
    if (data == null || data.isEmpty()) {
        return null;
    }

    Parser parser = new Parser();

    MAVLinkPacket packet = null;

    for (byte b : Hex.decodeHex(data.toCharArray())) {
        packet = parser.mavlink_parse_char(b & 0xFF);
    }

    return packet;
}
项目:InComb    文件:ATest.java   
public User createUser() {
    final byte[] salt = PasswordUtil.getNextSalt();
    final String passwordHash = Hex.encodeHexString(PasswordUtil.hash(PASSWORD, salt));

    final User user = new User(USERID, EMAIL, USERNAME, DISPLAYNAME, passwordHash,
            Hex.encodeHexString(salt), new Timestamp(System.currentTimeMillis()), false);
    new UserDao(con).insert(user);
    return user;
}
项目:cyberduck    文件:MantaObjectAttributeAdapter.java   
public PathAttributes convert(final MantaObject object) {
    final PathAttributes attributes = new PathAttributes();
    attributes.setPermission(new Permission(
        session.isUserWritable(object) ? Permission.Action.all : Permission.Action.read,
        Permission.Action.none,
        session.isWorldReadable(object) ? Permission.Action.read : Permission.Action.none));
    if(object.getLastModifiedTime() != null) {
        attributes.setModificationDate(object.getLastModifiedTime().getTime());
    }
    if(object.isDirectory()) {
        return attributes;
    }
    if(session.isWorldReadable(object)) {
        // mantaObject.getPath() starts with /
        final String joinedPath = session.getHost().getWebURL() + URIEncoder.encode(object.getPath());

        try {
            final URI link = new URI(joinedPath);
            attributes.setLink(new DescriptiveUrl(link, DescriptiveUrl.Type.http));
        }
        catch(URISyntaxException e) {
            log.warn(String.format("Cannot set link. Web URL returned %s", joinedPath), e);
        }
    }
    attributes.setSize(object.getContentLength());
    attributes.setETag(object.getEtag());
    final byte[] md5Bytes = object.getMd5Bytes();
    if(md5Bytes != null) {
        attributes.setChecksum(new Checksum(HashAlgorithm.md5, Hex.encodeHexString(md5Bytes)));
    }
    final String storageClass = object.getHeaderAsString(HEADER_KEY_STORAGE_CLASS);
    if(storageClass != null) {
        attributes.setStorageClass(storageClass);
    }
    return attributes;
}
项目:amv-access-api-poc    文件:MoreBase64.java   
public static String encodeHexAsBase64(String key) {
    requireNonNull(key, "`key` must not be null");
    requireNonNull(MoreHex.isHex(key), "`key` must be in hex");

    try {
        byte[] keyBase16 = Hex.decodeHex(key.toCharArray());
        return Base64.getEncoder().encodeToString(keyBase16);
    } catch (DecoderException e) {
        throw new RuntimeException(e);
    }
}
项目:javaOIDCMsg    文件:HMACAlgorithm.java   
@Override
public void verify(DecodedJWT jwt, EncodeType encodeType) throws Exception {
    byte[] contentBytes = String.format("%s.%s", jwt.getHeader(), jwt.getPayload()).getBytes(StandardCharsets.UTF_8);
    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;
    }

    try {
        boolean valid = crypto.verifySignatureFor(getDescription(), secret, contentBytes, signatureBytes);
        if (!valid) {
            throw new SignatureVerificationException(this);
        }
    } catch (IllegalStateException | InvalidKeyException | NoSuchAlgorithmException e) {
        throw new SignatureVerificationException(this, e);
    }
}
项目:wakeup-qcloud-sdk    文件:Base64Url.java   
public static void main(String[] args) throws DecoderException {

        // String hexString = "5095";
        String hexString = "789c6d8d4d4f83401884ff0b578c5dba0bbb98782015b1a1f8059a7222743fc8da96aecbdbdad6f8dfa5046fce6de6c9cc7c3bc522bfeec4baaa8dd1c2b9713c822e0a7ddfb91aa03c1a6d65552b90b6e794d2a0e7231c5a550d15b6ff96416fe590e38051c2281d732d640b5ae96172ea051c29be524c62e463e57382e854a08020a578c8febe38dfed5ba8e0642e9b98e21174bae97d16bfcde633299e0f49c81f27a26490b97665d7675dd0fdc35df1de994d23bc4301db349fbb918ea3e36b509878f7956d84dbb44b4ed23287b454f7119c12fea4968b64927d7c962179b9757e7e01ed1059d9";

        byte[] test = Hex.decodeHex(hexString.toCharArray());
        byte[] compressBytes = base64EncodeUrl(test);
        System.out.println("compress : " + new String(compressBytes));
        byte[] uncompressBytes = base64DecodeUrl(compressBytes);
        System.out.println("uncompress: "
                + Hex.encodeHexString(uncompressBytes));
    }
项目:CryptoKnight    文件:HashFactory.java   
public static String CommonHash(String p, String alg) throws NoSuchAlgorithmException
{
    MessageDigest md = MessageDigest.getInstance(alg);

    md.reset();

    md.update(p.getBytes(Charset.forName("UTF-8")));
    byte[] resBytes = md.digest();
    String res = new String(Hex.encodeHex(resBytes));

    return res;
}
项目:bitbreeds-webrtc    文件:DataChannelImpl.java   
/**
 * Data is sent as a SCTPMessage
 *
 *
 * @param data bytes to send
 */
@Override
public void send(byte[] data,SCTPPayloadProtocolId ppid) {
    if(mode == ConnectionMode.TRANSFER && running) {
        byte[] out = sctpService.createPayloadMessage(data, ppid);
        putDataOnWire(out);
    }
    else {
        logger.error("Data {} not sent, channel not open",Hex.encodeHex(data));
    }
}
项目:neo-java    文件:ModelUtil.java   
/**
 * reads a variable length list of byte array serializable objects.
 *
 * @param bb
 *            the byte buffer to read.
 * @param cl
 *            the class of the objects in the list, which must implement
 *            ByteArraySerializable.
 * @param <T>
 *            the type of the objects in the list.
 * @return the list.
 */
public static <T extends ByteArraySerializable> List<T> readVariableLengthList(final ByteBuffer bb,
        final Class<T> cl) {
    final BigInteger lengthBi = getBigInteger(bb);
    final int length = lengthBi.intValue();

    LOG.trace("readArray length {} class {}", length, cl.getSimpleName());

    final List<T> list = new ArrayList<>();
    for (int ix = 0; ix < length; ix++) {

        LOG.trace("STARTED readArray class {} [{}]", cl.getSimpleName(), ix);
        final T t;
        try {
            final Constructor<T> con = cl.getConstructor(ByteBuffer.class);
            t = con.newInstance(bb);
        } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException e) {
            throw new RuntimeException(
                    "error reading record " + (ix + 1) + " of " + length + " class " + cl.getSimpleName(), e);
        }

        LOG.trace("SUCCESS readArray class {} [{}]: {} {}", cl.getSimpleName(), ix,
                Hex.encodeHexString(t.toByteArray()), t);

        list.add(t);
    }
    return list;
}
项目:marshalsec    文件:C3P0WrapperConnPool.java   
public static String makeC3P0UserOverridesString ( String codebase, String clazz ) throws ClassNotFoundException, NoSuchMethodException,
        InstantiationException, IllegalAccessException, InvocationTargetException, IOException {

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    try ( ObjectOutputStream oos = new ObjectOutputStream(b) ) {
        Class<?> refclz = Class.forName("com.mchange.v2.naming.ReferenceIndirector$ReferenceSerialized"); //$NON-NLS-1$
        Constructor<?> con = refclz.getDeclaredConstructor(Reference.class, Name.class, Name.class, Hashtable.class);
        con.setAccessible(true);
        Reference jndiref = new Reference("Foo", clazz, codebase);
        Object ref = con.newInstance(jndiref, null, null, null);
        oos.writeObject(ref);
    }

    return "HexAsciiSerializedMap:" + Hex.encodeHexString(b.toByteArray()) + ";"; //$NON-NLS-1$
}
项目:azeroth    文件:IDBuilderTest.java   
@Test
public void buildMostlyOnes() {
    final byte[] result = IDBuilder.build(new Blueprint(Blueprint.MAX_TIMESTAMP,
        Blueprint.MAX_SEQUENCE_COUNTER, Blueprint.MAX_GENERATOR_ID, Blueprint.MAX_CLUSTER_ID));
    final String expected = "ffffffffffff0fff";

    assertThat(Hex.encodeHexString(result), CoreMatchers.is(expected));
}
项目:amv-highmobility-cryptotool-wrapper    文件:CryptotoolUtilsTest.java   
@Test
public void encodeHexAsBase64() {
    String value = "ABCDEF";

    String valueHex = new String(Hex.encodeHex(value.getBytes(Charsets.UTF_8)));
    assertThat(valueHex, is(equalTo("414243444546")));

    String valueBase64 = CryptotoolUtils.encodeHexAsBase64(valueHex);

    assertThat(valueBase64, is(equalTo("QUJDREVG")));
}
项目:instalint    文件:PluginHashesTest.java   
@Test
public void test_toHex() {
  // lower-case
  assertThat(PluginHashes.toHex("aloa_bi_bop_a_loula".getBytes())).isEqualTo("616c6f615f62695f626f705f615f6c6f756c61");

  // compare results with commons-codec
  for (int index = 0; index < 100; index++) {
    String random = randomString();
    assertThat(PluginHashes.toHex(random.getBytes())).as(random).isEqualTo(
      Hex.encodeHexString(random.getBytes()).toLowerCase());
  }
}
项目:open-kilda    文件:PathVerificationService.java   
@Override
public boolean sendDiscoveryMessage(DatapathId srcSwId, OFPort port) {
    IOFSwitch srcSwitch = switchService.getSwitch(srcSwId);
    if (srcSwitch == null) {
        return false;
    }
    OFPacketOut ofPacketOut = (generateVerificationPacket(srcSwitch, port));
    logger.debug("sending verification packet out {}/{}: {}", srcSwitch.getId().toString(), port.getPortNumber(),
            Hex.encodeHexString(ofPacketOut.getData()));
    return srcSwitch.write(ofPacketOut);
}