org.apache.commons.codec.binary.Hex类的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(9.9k)|赞(0)|评价(0)|浏览(1120)

本文整理了Java中org.apache.commons.codec.binary.Hex类的一些代码示例,展示了Hex类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Hex类的具体详情如下:
包路径:org.apache.commons.codec.binary.Hex
类名称:Hex

Hex介绍

[英]Hex encoder and decoder.
[中]十六进制编码器和解码器。

代码示例

代码示例来源:origin: gocd/gocd

private String sha256(byte[] bytes) {
    MessageDigest md;

    try {
      md = MessageDigest.getInstance(HASH_ALGORITHM);
    } catch (NoSuchAlgorithmException ignored) {
      return null; // Using standard algorithm that is required to exist
    }

    md.update(bytes);
    return Hex.encodeHexString(md.digest());
  }
}

代码示例来源:origin: Graylog2/graylog2-server

private String buildFingerprint(List<Stream> streams) {
  final MessageDigest sha1Digest = DigestUtils.getSha1Digest();
  final StringBuilder sb = new StringBuilder();
  for (Stream stream : Ordering.from(getStreamComparator()).sortedCopy(streams)) {
    sb.append(stream.hashCode());
    for (StreamRule rule : Ordering.from(getStreamRuleComparator()).sortedCopy(stream.getStreamRules())) {
      sb.append(rule.hashCode());
    }
    for (Output output : Ordering.from(getOutputComparator()).sortedCopy(stream.getOutputs())) {
      sb.append(output.hashCode());
    }
  }
  return String.valueOf(Hex.encodeHex(sha1Digest.digest(sb.toString().getBytes(StandardCharsets.US_ASCII))));
}

代码示例来源:origin: commons-codec/commons-codec

/**
 * Converts a String representing hexadecimal values into an array of bytes of those same values. The
 * returned array will be half the length of the passed String, as it takes two characters to represent any given
 * byte. An exception is thrown if the passed String has an odd number of elements.
 *
 * @param data
 *            A String containing hexadecimal digits
 * @return A byte array containing binary data decoded from the supplied char array.
 * @throws DecoderException
 *             Thrown if an odd number or illegal of characters is supplied
 * @since 1.11
 */
public static byte[] decodeHex(final String data) throws DecoderException {
  return decodeHex(data.toCharArray());
}

代码示例来源:origin: commons-codec/commons-codec

/**
 * Converts an array of character bytes representing hexadecimal values into an array of bytes of those same values.
 * The returned array will be half the length of the passed array, as it takes two characters to represent any given
 * byte. An exception is thrown if the passed char array has an odd number of elements.
 *
 * @param array
 *            An array of character bytes containing hexadecimal digits
 * @return A byte array containing binary data decoded from the supplied byte array (representing characters).
 * @throws DecoderException
 *             Thrown if an odd number of characters is supplied to this function
 * @see #decodeHex(char[])
 */
@Override
public byte[] decode(final byte[] array) throws DecoderException {
  return decodeHex(new String(array, getCharset()).toCharArray());
}

代码示例来源:origin: ninjaframework/ninja

private String signHmacSha1(String value, String key) {
  try {
    // Get an hmac_sha1 key from the raw key bytes
    byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
    SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
    // Get an hmac_sha1 Mac instance and initialize with the signing key
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);
    // Compute the hmac on input data bytes
    byte[] rawHmac = mac.doFinal(value.getBytes(StandardCharsets.UTF_8));
    // Convert raw bytes to Hex
    byte[] hexBytes = new Hex().encode(rawHmac);
    // Convert array of Hex bytes to a String
    return new String(hexBytes, "UTF-8");
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: liyiorg/weixin-popular

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
   SecretKeySpec secret_key = new SecretKeySpec(paternerKey.getBytes("UTF-8"), "HmacSHA256");
   sha256_HMAC.init(secret_key);
   return Hex.encodeHexString(sha256_HMAC.doFinal((str+"&key="+paternerKey).getBytes("UTF-8"))).toUpperCase();
} catch (Exception e) {
  logger.error("", e);
return DigestUtils.md5Hex(str+"&key="+paternerKey).toUpperCase();

代码示例来源:origin: gocd/gocd

protected static boolean matchChecksum(File localFile, String expectedSignature) {
  try (FileInputStream input = new FileInputStream(localFile)) {
    MessageDigest digester = MessageDigest.getInstance("MD5");
    try (DigestInputStream digest = new DigestInputStream(input, digester)) {
      IOUtils.copy(digest, new NullOutputStream());
    }
    return expectedSignature.equalsIgnoreCase(encodeHexString(digester.digest()));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: commons-codec/commons-codec

@Test
public void testSha1UpdateWithByteArray(){
  final String d1 = "C'est un homme qui rentre dans un café, et plouf";
  final String d2 = "C'est un homme, c'est qu'une tête, on lui offre un cadeau: 'oh... encore un chapeau!'";
  MessageDigest messageDigest = DigestUtils.getSha1Digest();
  messageDigest.update(d1.getBytes());
  messageDigest.update(d2.getBytes());
  final String expectedResult = Hex.encodeHexString(messageDigest.digest());
  messageDigest = DigestUtils.getSha1Digest();
  DigestUtils.updateDigest(messageDigest, d1.getBytes());
  DigestUtils.updateDigest(messageDigest, d2.getBytes());
  final String actualResult = Hex.encodeHexString(messageDigest.digest());
  assertEquals(expectedResult, actualResult);
}

代码示例来源:origin: gocd/gocd

public static String md5Hex(final InputStream data) {
  return objectPools.computeDigest(DigestObjectPools.MD_5, digest -> {
    byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
    int read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
    while (read > -1) {
      digest.update(buffer, 0, read);
      read = data.read(buffer, 0, STREAM_BUFFER_LENGTH);
    }
    return Hex.encodeHexString(digest.digest());
  });
}

代码示例来源:origin: commons-codec/commons-codec

@SuppressWarnings("deprecation") // deliberate tests of deprecated code
@Test
public void testShaUpdateWithByteArray(){
  final String d1 = "C'est un homme qui rentre dans un café, et plouf";
  final String d2 = "C'est un homme, c'est qu'une tête, on lui offre un cadeau: 'oh... encore un chapeau!'";
  MessageDigest messageDigest = DigestUtils.getShaDigest();
  messageDigest.update(d1.getBytes());
  messageDigest.update(d2.getBytes());
  final String expectedResult = Hex.encodeHexString(messageDigest.digest());
  messageDigest = DigestUtils.getShaDigest();
  DigestUtils.updateDigest(messageDigest, d1.getBytes());
  DigestUtils.updateDigest(messageDigest, d2.getBytes());
  final String actualResult = Hex.encodeHexString(messageDigest.digest());
  assertEquals(expectedResult, actualResult);
}

代码示例来源:origin: net.thucydides/thucydides-core

private String generateHMACFor(String secretKey, String message) {
  try {
    byte[] keyBytes = secretKey.getBytes();
    Key key = new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacMD5");
    Mac mac = Mac.getInstance("HmacMD5");
    mac.init(key);
    return new String(Hex.encodeHex(mac.doFinal(message.getBytes())));
  } catch (GeneralSecurityException e) {
    throw new IllegalStateException("Could not generate HMAC for some reason", e);
  }
}

代码示例来源:origin: SonarSource/sonarqube

public String getHash() {
  return Hex.encodeHexString(globalMd5Digest.digest());
 }
}

代码示例来源:origin: apache/nifi

private static SecretKey getMasterKey() throws KeyManagementException {
    try {
      // Get the master encryption key from bootstrap.conf
      String masterKeyHex = NiFiPropertiesLoader.extractKeyFromBootstrapFile();
      return new SecretKeySpec(Hex.decodeHex(masterKeyHex.toCharArray()), "AES");
    } catch (IOException | DecoderException e) {
      logger.error("Encountered an error: ", e);
      throw new KeyManagementException(e);
    }
  }
}

代码示例来源:origin: commons-codec/commons-codec

@Test
public void testHmacSha1UpdateWithInpustream() throws IOException {
  final Mac mac = HmacUtils.getHmacSha1(HmacAlgorithmsTest.STANDARD_KEY_BYTES);
  HmacUtils.updateHmac(mac, new ByteArrayInputStream(HmacAlgorithmsTest.STANDARD_PHRASE_BYTES));
  assertEquals(HmacAlgorithmsTest.STANDARD_SHA1_RESULT_STRING, Hex.encodeHexString(mac.doFinal()));
  HmacUtils.updateHmac(mac, new ByteArrayInputStream("".getBytes()));
  assertEquals("f42bb0eeb018ebbd4597ae7213711ec60760843f", Hex.encodeHexString(mac.doFinal()));
}

代码示例来源:origin: b3log/latke

/**
 * Encrypts by AES.
 *
 * @param content the specified content to encrypt
 * @param key     the specified key
 * @return encrypted content
 * @see #decryptByAES(java.lang.String, java.lang.String)
 */
public static String encryptByAES(final String content, final String key) {
  try {
    final KeyGenerator kgen = KeyGenerator.getInstance("AES");
    final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
    secureRandom.setSeed(key.getBytes());
    kgen.init(128, secureRandom);
    final SecretKey secretKey = kgen.generateKey();
    final byte[] enCodeFormat = secretKey.getEncoded();
    final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
    final Cipher cipher = Cipher.getInstance("AES");
    final byte[] byteContent = content.getBytes("UTF-8");
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    final byte[] result = cipher.doFinal(byteContent);
    return Hex.encodeHexString(result);
  } catch (final Exception e) {
    LOGGER.log(Level.WARN, "Encrypt failed", e);
    return null;
  }
}

代码示例来源:origin: commons-codec/commons-codec

/**
 * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
 * The returned array will be double the length of the passed array, as it takes two characters to represent any
 * given byte.
 *
 * @param data
 *            a byte[] to convert to Hex characters
 * @return A char[] containing lower-case hexadecimal characters
 */
public static char[] encodeHex(final byte[] data) {
  return encodeHex(data, true);
}

代码示例来源:origin: commons-codec/commons-codec

/**
 * Reads through a ByteBuffer and returns the digest for the data
 *
 * @param data
 *            Data to digest
 * @return the digest as a hex string
 *
 * @since 1.11
 */
public String digestAsHex(final ByteBuffer data) {
  return Hex.encodeHexString(digest(data));
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Utility method supporting both possible digest formats: Base64 and Hex
 */
private boolean digestMatches(byte[] digest, String providedDigest) {
  return providedDigest.equalsIgnoreCase(Hex.encodeHexString(digest)) || providedDigest.equalsIgnoreCase(new String(Base64.encode(digest)));
}

代码示例来源:origin: commons-codec/commons-codec

/**
 * Calculates the MD5 digest and returns the value as a 32 character hex string.
 *
 * @param data
 *            Data to digest
 * @return MD5 digest as a hex string
 */
public static String md5Hex(final byte[] data) {
  return Hex.encodeHexString(md5(data));
}

代码示例来源:origin: commons-codec/commons-codec

/**
 * Calculates the SHA-1 digest and returns the value as a hex string.
 *
 * @param data
 *            Data to digest
 * @return SHA-1 digest as a hex string
 * @since 1.7
 */
public static String sha1Hex(final String data) {
  return Hex.encodeHexString(sha1(data));
}

相关文章