Java Code Examples for org.apache.commons.codec.binary.Hex

The following examples show how to use org.apache.commons.codec.binary.Hex. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: hadoop-ozone   Source File: ContinueToken.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generate a continuation token which is used in get Bucket.
 *
 * @return if key is not null return continuation token, else returns null.
 */
public String encodeToString() {
  if (this.lastKey != null) {

    ByteBuffer buffer = ByteBuffer
        .allocate(4 + lastKey.length()
            + (lastDir == null ? 0 : lastDir.length()));
    buffer.putInt(lastKey.length());
    buffer.put(lastKey.getBytes(StandardCharsets.UTF_8));
    if (lastDir != null) {
      buffer.put(lastDir.getBytes(StandardCharsets.UTF_8));
    }

    String hex = Hex.encodeHexString(buffer.array());
    String digest = DigestUtils.sha256Hex(hex);
    return hex + CONTINUE_TOKEN_SEPERATOR + digest;
  } else {
    return null;
  }
}
 
Example 2
Source Project: bisq   Source File: RelayMain.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private static void handleRelay() {
    get("/relay", (request, response) -> {
        log.info("Incoming relay request from: " + request.userAgent());
        boolean isAndroid = request.queryParams("isAndroid").equalsIgnoreCase("true");
        boolean useSound = request.queryParams("snd").equalsIgnoreCase("true");
        String token = new String(Hex.decodeHex(request.queryParams("token").toCharArray()), "UTF-8");
        String encryptedMessage = new String(Hex.decodeHex(request.queryParams("msg").toCharArray()), "UTF-8");
        log.info("isAndroid={}\nuseSound={}\napsTokenHex={}\nencryptedMessage={}", isAndroid, useSound, token,
            encryptedMessage);
        if (isAndroid) {
            return relayService.sendAndroidMessage(token, encryptedMessage, useSound);
        } else {
            boolean isProduction = request.queryParams("isProduction").equalsIgnoreCase("true");
            boolean isContentAvailable = request.queryParams("isContentAvailable").equalsIgnoreCase("true");
            return relayService.sendAppleMessage(isProduction, isContentAvailable, token, encryptedMessage, useSound);
        }
    });
}
 
Example 3
Source Project: distributedlog   Source File: DistributedLogTool.java    License: Apache License 2.0 6 votes vote down vote up
protected void printStreams(Namespace namespace) throws Exception {
    Iterator<String> streams = namespace.getLogs();
    System.out.println("Streams under " + getUri() + " : ");
    System.out.println("--------------------------------");
    while (streams.hasNext()) {
        String streamName = streams.next();
        System.out.println(streamName);
        if (!printMetadata) {
            continue;
        }
        MetadataAccessor accessor =
                namespace.getNamespaceDriver().getMetadataAccessor(streamName);
        byte[] metadata = accessor.getMetadata();
        if (null == metadata || metadata.length == 0) {
            continue;
        }
        if (printHex) {
            System.out.println(Hex.encodeHexString(metadata));
        } else {
            System.out.println(new String(metadata, UTF_8));
        }
        System.out.println("");
    }
    System.out.println("--------------------------------");
}
 
Example 4
Source Project: unidbg   Source File: AndroidRelocationIterator.java    License: Apache License 2.0 6 votes vote down vote up
public AndroidRelocationIterator(int objectSize, SymbolLocator symtab, byte[] androidRelData, boolean rela) {
    if (log.isDebugEnabled()) {
        Inspector.inspect(androidRelData, "androidRelData hex=" + Hex.encodeHexString(androidRelData));
    }

    this.objectSize = objectSize;
    this.buffer = ByteBuffer.wrap(androidRelData);
    this.rela = rela;
    reloc_ = new ElfRelocation(objectSize, symtab);

    relocation_count_ = readSleb128();
    reloc_.offset = readSleb128();

    relocation_index_ = 0;
    relocation_group_index_ = 0;
    group_size_ = 0;
}
 
Example 5
Source Project: gocd   Source File: AnalyticsPluginAssetsService.java    License: Apache License 2.0 6 votes vote down vote up
private String sha2Digest(byte[]... bytes) {
    try {
        MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM);

        for (byte[] data : bytes) {
            md.update(data);
        }

        return Hex.encodeHexString(md.digest());
    } catch (Exception e) {
        LOGGER.error("Error generating {} hash", HASH_ALGORITHM, e);
        ExceptionUtils.bomb(e);
    }

    return null;
}
 
Example 6
Source Project: uyuni   Source File: MD5Crypt.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * MD5 and Hexify an array of bytes.  Take the input array, MD5 encodes it
 * and then turns it into Hex.
 * @param secretBytes you want md5hexed
 * @return md5hexed String.
 */
public static String md5Hex(byte[] secretBytes) {
    String retval = null;
    // add secret
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
        //byte[] secretBytes = inputString.getBytes("UTF-8");
        md.update(secretBytes);
        // generate the digest
        byte[] digest = md.digest();
        // hexify this puppy
        retval = new String(Hex.encodeHex(digest));
    }
    catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("NoSuchAlgorithm: MD5.  Something" +
                " weird with your JVM, you should be able to do this.", e);
    }
    return retval;
}
 
Example 7
public String getMd5(int[] program) {
	MessageDigest messageDigest;
	
	try {
		messageDigest = MessageDigest.getInstance("MD5");
	} catch (NoSuchAlgorithmException e) {
		//srlsy??
		throw new RuntimeException("", e);
	}
	
	for (int i = 0; i < program.length; i++) {
		messageDigest.update((byte)i);	
	}
	
	return new String(Hex.encodeHex(messageDigest.digest()));
}
 
Example 8
Source Project: nifi   Source File: Uuid5Evaluator.java    License: Apache License 2.0 6 votes vote down vote up
private static String toString(final byte[] uuid) {
    if (uuid == null) {
        return new UUID(0, 0).toString();
    }

    final String encoded = Hex.encodeHexString(Objects.requireNonNull(uuid));
    final StringBuffer sb = new StringBuffer(encoded);

    while (sb.length() != 32) {
        sb.insert(0, "0");
    }

    sb.ensureCapacity(32);
    sb.insert(8, '-');
    sb.insert(13, '-');
    sb.insert(18, '-');
    sb.insert(23, '-');

    return sb.toString();
}
 
Example 9
/**
 * Returns the digest value of a given public key.
 *
 * <p>In Version “H003” of the EBICS protocol the ES of the financial:
 *
 * <p>The SHA-256 hash values of the financial institution's public keys for X002 and E002 are
 * composed by concatenating the exponent with a blank character and the modulus in hexadecimal
 * representation (using lower case letters) without leading zero (as to the hexadecimal
 * representation). The resulting string has to be converted into a byte array based on US ASCII
 * code.
 *
 * @param publicKey the public key
 * @return the digest value
 * @throws EbicsException
 */
public static byte[] getKeyDigest(RSAPublicKey publicKey) throws AxelorException {
  String modulus;
  String exponent;
  String hash;
  byte[] digest;

  exponent = Hex.encodeHexString(publicKey.getPublicExponent().toByteArray());
  modulus = Hex.encodeHexString(removeFirstByte(publicKey.getModulus().toByteArray()));
  hash = exponent + " " + modulus;

  if (hash.charAt(0) == '0') {
    hash = hash.substring(1);
  }

  try {
    digest = MessageDigest.getInstance("SHA-256", "BC").digest(hash.getBytes("US-ASCII"));
  } catch (GeneralSecurityException | UnsupportedEncodingException e) {
    throw new AxelorException(
        e.getCause(), TraceBackRepository.CATEGORY_CONFIGURATION_ERROR, e.getMessage());
  }

  return new String(Hex.encodeHex(digest, false)).getBytes();
}
 
Example 10
Source Project: nifi   Source File: EncodeContent.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(InputStream in, OutputStream out) throws IOException {
    int len;
    byte[] inBuf = new byte[8192];
    Hex h = new Hex();
    while ((len = in.read(inBuf)) > 0) {
        // If the input buffer is of odd length, try to get another byte
        if (len % 2 != 0) {
            int b = in.read();
            if (b != -1) {
                inBuf[len] = (byte) b;
                len++;
            }
        }

        // Construct a new buffer bounded to len
        byte[] slice = Arrays.copyOfRange(inBuf, 0, len);
        try {
            out.write(h.decode(slice));
        } catch (DecoderException ex) {
            throw new IOException(ex);
        }
    }
    out.flush();
}
 
Example 11
Source Project: scipio-erp   Source File: HashCrypt.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean doCompareTypePrefix(String crypted, String defaultCrypt, byte[] bytes) {
    int typeEnd = crypted.indexOf("}");
    String hashType = crypted.substring(1, typeEnd);
    String hashed = crypted.substring(typeEnd + 1);
    MessageDigest messagedigest = getMessageDigest(hashType);
    messagedigest.update(bytes);
    byte[] digestBytes = messagedigest.digest();
    char[] digestChars = Hex.encodeHex(digestBytes);
    String checkCrypted = new String(digestChars);
    if (hashed.equals(checkCrypted)) {
        return true;
    }
    // This next block should be removed when all {prefix}oldFunnyHex are fixed.
    if (hashed.equals(oldFunnyHex(digestBytes))) {
        Debug.logWarning("Warning: detected oldFunnyHex password prefixed with a hashType; this is not valid, please update the value in the database with ({%s}%s)", module, hashType, checkCrypted);
        return true;
    }
    return false;
}
 
Example 12
@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"));
}
 
Example 13
Source Project: hadoop-etl-udfs   Source File: HdfsSerDeImportService.java    License: MIT License 6 votes vote down vote up
private static Object getJavaObjectFromPrimitiveData(Object data, ObjectInspector objInsp) {
    assert(objInsp.getCategory() == Category.PRIMITIVE);
    if (data == null) {
        return null;
    }
    if (data instanceof BytesWritable && objInsp instanceof WritableHiveDecimalObjectInspector) {
        // BytesWritable cannot be directly cast to HiveDecimalWritable
        WritableHiveDecimalObjectInspector oi = (WritableHiveDecimalObjectInspector) objInsp;
        data = oi.create(((BytesWritable) data).getBytes(), oi.scale());
    }
    Object obj = ObjectInspectorUtils.copyToStandardJavaObject(data, objInsp);
    if (obj instanceof HiveDecimal) {
        obj = ((HiveDecimal) obj).bigDecimalValue();
    } else if (obj instanceof HiveVarchar || obj instanceof HiveChar) {
        obj = obj.toString();
    } else if (obj instanceof byte[]) {
        obj = Hex.encodeHexString((byte[]) obj);
    }
    return obj;
}
 
Example 14
Source Project: SPADE   Source File: ABE.java    License: GNU General Public License v3.0 6 votes vote down vote up
private String encryptAnnotation(String plainAnnotation, Cipher cipher)
{
	if(plainAnnotation == null)
		return null;
	try
	{
		String encryptedAnnotationStr;
		byte[] encryptedAnnotation = cipher.doFinal(plainAnnotation.getBytes(StandardCharsets.UTF_8));
		encryptedAnnotationStr = Hex.encodeHexString(encryptedAnnotation);
		return encryptedAnnotationStr;
	}
	catch(Exception ex)
	{
		String message = "Unable to encrypt annotation " + "'" + plainAnnotation + "'. " +
				"This would disturb any further encryption of annotations.";
		logger.log(Level.WARNING, message, ex);
		return null;
	}
}
 
Example 15
@Override
protected void verify(final Path file, final MessageDigest digest, final Checksum checksum) throws ChecksumException {
    if(null == digest) {
        log.debug(String.format("Digest verification disabled for file %s", file));
        return;
    }
    if(file.getType().contains(Path.Type.encrypted)) {
        log.warn(String.format("Skip checksum verification for %s with client side encryption enabled", file));
        return;
    }
    final String expected = Hex.encodeHexString(digest.digest());
    if(!checksum.equals(Checksum.parse(expected))) {
        throw new ChecksumException(MessageFormat.format(LocaleFactory.localizedString("Upload {0} failed", "Error"), file.getName()),
                MessageFormat.format("Mismatch between {0} hash {1} of uploaded data and ETag {2} returned by the server",
                        checksum.algorithm.toString(), expected, checksum.hash));
    }
}
 
Example 16
@Override
public AddressInformation getAddressInformation(final String address) throws ApplicationException {
  try (final CloseableHttpClient client = getAuthenticatedHttpClientProxy();
      final InputStream jsonData = doComplexJSONRPCMethod(client, "searchrawtransactions", address).getContent()) {

    final AddressInformation addressInformation = JSONRPCParser.getAddressInformation(address, jsonData);

    for (final AddressOutpoint outpoint : addressInformation.getOutpoints()) {
      final String txid = new String(Hex.encodeHex(outpoint.getReferenceTransaction()));
      try (final InputStream utxoJsonData = doComplexJSONRPCMethod(client, "gettxout", txid, outpoint.getIndex()).getContent()) {
        outpoint.setSpent(JSONRPCParser.isNullResult(utxoJsonData));
      }
    }

    return addressInformation;
  } catch (IOException | HttpException | DecoderException e) {
    e.printStackTrace();
    throw new ApplicationException(e.getMessage());
  }
}
 
Example 17
Source Project: sync-android   Source File: EndToEndEncryptionTest.java    License: Apache License 2.0 5 votes vote down vote up
public static byte[] hexStringToByteArray(String s) {
    try {
        return Hex.decodeHex(s.toCharArray());
    } catch (DecoderException ex) {
        // Crash the tests at this point, we've input bad data in our hard-coded values
        throw new RuntimeException("Error decoding hex data: " + s);
    }
}
 
Example 18
Source Project: trex-stateless-gui   Source File: PacketUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Read pcap file to get all includes packet
 *
 * @param pcapFile
 * @return
 * @throws PcapNativeException
 * @throws NotOpenException
 */
private List<String> getpcapPacketList(String pcapFile) throws PcapNativeException, NotOpenException {
    PcapHandle handler = Pcaps.openOffline(pcapFile);
    Packet packet = null;
    List<String> packetList = new ArrayList<>();
    while ((packet = handler.getNextPacket()) != null) {
        packetList.add(Hex.encodeHexString(packet.getRawData()));
    }
    return packetList;
}
 
Example 19
/**
 * refresh underlying RegionScanner we call this when new store file gets
 * created by MemStore flushes or current scanner fails due to compaction
 */
public void updateScanner() throws IOException {
        if (LOG.isDebugEnabled()) {
            SpliceLogUtils.debug(LOG,
                    "updateScanner with hregionInfo=%s, tableName=%s, rootDir=%s, scan=%s",
                    hri, htd.getNameAsString(), rootDir, scan);
        }
        if (flushed) {
            if (LOG.isDebugEnabled())
                SpliceLogUtils.debug(LOG, "Flush occurred");
            byte[] restartRow = null;
            if (rowBuffer != null && !rowBuffer.isEmpty()) {
                restartRow = CellUtil.cloneRow(rowBuffer.get(0));
                rowBuffer = null;
            } else if (this.topCell != null) {
                restartRow = Bytes.add(CellUtil.cloneRow(topCell), new byte[]{0});
            }
            if (restartRow != null) {
                if (LOG.isDebugEnabled())
                    SpliceLogUtils.debug(LOG, "setting start row to %s", Hex.encodeHexString(restartRow));
                //noinspection deprecation
                scan.setStartRow(restartRow);
            }
        }
        memScannerList.add(getMemStoreScanner());
        this.region = openHRegion();
        RegionScanner regionScanner = new CountingRegionScanner(HRegionUtil.getScanner(region, scan, memScannerList), region, scan);
        if (flushed) {
            if (scanner != null)
                scanner.close();
        }
        scanner = regionScanner;
}
 
Example 20
Source Project: letv   Source File: rrrccc.java    License: Apache License 2.0 5 votes vote down vote up
private static SecretKeySpec bй0439йй0439й(String str) throws Exception {
    String str2 = null;
    while (true) {
        try {
            str2.length();
        } catch (Exception e) {
            b0429Щ0429Щ0429Щ = b0429ЩЩЩ0429Щ();
            try {
                return new SecretKeySpec(Hex.decodeHex(str.toCharArray()), "AES");
            } catch (Exception e2) {
                throw e2;
            }
        }
    }
}
 
Example 21
Source Project: otroslogviewer   Source File: AuthStoreUtils.java    License: Apache License 2.0 5 votes vote down vote up
private String saltAndEncrypt(char[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
    IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
  String value;
  Hex hex = new Hex();
  char[] saltedData = addSalt(data);

  byte[] encode = encrypt(saltedData, password);
  value = new String(hex.encode(encode));
  return value;
}
 
Example 22
Source Project: extract   Source File: UpdatableDigester.java    License: MIT License 5 votes vote down vote up
public UpdatableDigester(final String modifier, final String algorithm) {
    super(new UpdatableInputStreamDigester(20 * 1024 * 1024,
            algorithm, algorithm.replace("-", ""), Hex::encodeHexString) {
        @Override
        protected String getDigestUpdateModifier() {
            return modifier;
        }
    });
    this.algorithm = algorithm;
}
 
Example 23
Source Project: product-recommendation-system   Source File: EncryptTest.java    License: MIT License 5 votes vote down vote up
/**
 * 加密操作
 */
@Test
public void testEncryptPassword() {
	String plainPsd = "123";
	// 1. 用SecureRandom生成一个随机数
	byte[] salt = new byte[8];
	SecureRandom securityRandom = new SecureRandom();
	securityRandom.nextBytes(salt);
	// 2.用Hex来对随机数进行编码
	String encodedSalt = Hex.encodeHexString(salt);
	// 3.将随机数和密码用不可逆加密算法加密1024次
	byte[] result = null;
	try {
		MessageDigest digest = MessageDigest.getInstance("SHA1");
		digest.update(salt);
		
		result = digest.digest(plainPsd.getBytes());
		
		for (int i = 1; i < 1024; i++) {
			digest.reset();
			result = digest.digest(result);
		}
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	// 4.将上一步得到的字节数组用Hex编码
	String sha1Psd = Hex.encodeHexString(result);
	// 5.将第二步和第四步得到的值拼凑
	String encryptedPsd = encodedSalt + sha1Psd;
	System.out.println(encryptedPsd);
}
 
Example 24
@Test
public void testMapBlobColumn() {
  byte[] value = new byte[20];
  new Random().nextBytes(value);

  primeWithType(Hex.encodeHexString(value), BLOB);
  ResultSet resultSet = getResultSet();

  Schema schema = Schema.builder().addNullableField("col", FieldType.BYTES).build();
  Row expected = Row.withSchema(schema).addValue(value).build();

  assertEquals(expected, cassandraRowMapper.map(resultSet).next());
}
 
Example 25
Source Project: secure-data-service   Source File: DeltaJournalTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEntityId() throws DecoderException {
    String id = "1234567890123456789012345678901234567890";
    String superid = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    String extraid = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
    Map<String, Object> delta = new HashMap<String, Object>();
    delta.put("_id", Hex.decodeHex(id.toCharArray()));
    assertEquals(id + "_id", DeltaJournal.getEntityId(delta));
    delta.put("i", Arrays.asList(Hex.decodeHex(superid.toCharArray())));
    assertEquals(superid + "_id" + id + "_id", DeltaJournal.getEntityId(delta));
    delta.put("i", Arrays.asList(Hex.decodeHex(superid.toCharArray()), Hex.decodeHex(extraid.toCharArray())));
    assertEquals(extraid + "_id" + superid + "_id" + id + "_id", DeltaJournal.getEntityId(delta));

}
 
Example 26
Source Project: beam   Source File: JvmVerification.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> Java getByteCodeVersion(final Class<T> clazz) throws IOException {
  final InputStream stream =
      clazz.getClassLoader().getResourceAsStream(clazz.getName().replace(".", "/") + ".class");
  final byte[] classBytes = IOUtils.toByteArray(stream);
  final String versionInHexString =
      Hex.encodeHexString(new byte[] {classBytes[6], classBytes[7]});
  return versionMapping.get(versionInHexString);
}
 
Example 27
Source Project: incubator-gobblin   Source File: MD5Digest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Static method to get an MD5Digest from a binary byte representation
 * @param md5Bytes
 * @return a filled out MD5Digest
 */
public static MD5Digest fromBytes(byte[] md5Bytes)
{
  Preconditions.checkArgument(md5Bytes.length == MD5_BYTES_LENGTH,
      "md5 bytes must be " + MD5_BYTES_LENGTH + " bytes in length, found " + md5Bytes.length + " bytes.");
  String md5String = Hex.encodeHexString(md5Bytes);
  return new MD5Digest(md5String, md5Bytes);
}
 
Example 28
Source Project: java-uniqueid   Source File: IDBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void buildModeOnlySpread() {
    // Cluster ID test.
    final byte[] result = IDBuilder.build(new Blueprint(0, 0, 0, 0));
    final byte[] lastTwoBytes = new byte[]{result[6], result[7]};
    final String expected = "0000";
    assertThat(Hex.encodeHexString(lastTwoBytes), is(expected));
}
 
Example 29
Source Project: zheshiyigeniubidexiangmu   Source File: BitfinexService.java    License: MIT License 5 votes vote down vote up
private static String createHmacSignature(String secret, String inputText, String algoName) {
    try {
        Mac mac = Mac.getInstance(algoName);
        SecretKeySpec key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), algoName);
        mac.init(key);

        return new String(Hex.encodeHex(mac.doFinal(inputText.getBytes(StandardCharsets.UTF_8))));

    } catch (Exception e) {
        throw new RuntimeException("cannot create " + algoName, e);
    }
}
 
Example 30
Source Project: usergrid   Source File: Count.java    License: Apache License 2.0 5 votes vote down vote up
/** the counter name should uniquely identify the entity being counted. */
@JsonIgnore
public String getCounterName() {
    if ( counterName == null ) {
        counterName = tableName + ":" + Hex.encodeHexString( getKeyNameBytes().array() ) + ":" + Hex
                .encodeHexString( getColumnNameBytes().array() );
    }
    return counterName;
}