javax.crypto.Mac.update()方法的使用及代码示例

x33g5p2x  于2022-01-24 转载在 其他  
字(9.5k)|赞(0)|评价(0)|浏览(110)

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

Mac.update介绍

[英]Updates this Mac instance with the specified byte.
[中]使用指定的字节更新此Mac实例。

代码示例

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

/**
 * Returns the digest for the input data.
 *
 * @param valueToDigest the input to use
 * @return the digest as a byte[]
 * @since 1.11
 */
public byte[] hmac(final ByteBuffer valueToDigest) {
  mac.update(valueToDigest);
  return mac.doFinal();
}

代码示例来源:origin: auth0/java-jwt

/**
 * Create signature for JWT header and payload.
 *
 * @param algorithm algorithm name.
 * @param secretBytes algorithm secret.
 * @param headerBytes JWT header.
 * @param payloadBytes JWT payload.
 * @return the signature bytes.
 * @throws NoSuchAlgorithmException if the algorithm is not supported.
 * @throws InvalidKeyException if the given key is inappropriate for initializing the specified algorithm.
 */
byte[] createSignatureFor(String algorithm, byte[] secretBytes, byte[] headerBytes, byte[] payloadBytes) throws NoSuchAlgorithmException, InvalidKeyException {
  final Mac mac = Mac.getInstance(algorithm);
  mac.init(new SecretKeySpec(secretBytes, algorithm));
  mac.update(headerBytes);
  mac.update(JWT_PART_SEPARATOR);
  return mac.doFinal(payloadBytes);
}

代码示例来源:origin: prestodb/presto

private ByteString hmac(String algorithm, ByteString key) {
 try {
  Mac mac = Mac.getInstance(algorithm);
  mac.init(new SecretKeySpec(key.toByteArray(), algorithm));
  if (head != null) {
   mac.update(head.data, head.pos, head.limit - head.pos);
   for (Segment s = head.next; s != head; s = s.next) {
    mac.update(s.data, s.pos, s.limit - s.pos);
   }
  }
  return ByteString.of(mac.doFinal());
 } catch (NoSuchAlgorithmException e) {
  throw new AssertionError();
 } catch (InvalidKeyException e) {
  throw new IllegalArgumentException(e);
 }
}

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

static void addIterations(final byte[] hi, final Mac hmac, final int currentIterationCount, final int newIterationCount) {
  // compute U2 ... Ui, performing the xor with the previous result as we iterate.
  byte[] current = hi;
  for (int i = currentIterationCount; i < newIterationCount; i++) {
    hmac.update(current);
    current = hmac.doFinal();
    for (int j = 0; j < hi.length; j++) {
      hi[j] ^= current[j];
    }
  }
}

代码示例来源:origin: mpusher/mpush

public static String hmacSha1(String data, String encryptKey) {
  final String HMAC_SHA1 = "HmacSHA1";
  SecretKeySpec signingKey = new SecretKeySpec(encryptKey.getBytes(Constants.UTF_8), HMAC_SHA1);
  try {
    Mac mac = Mac.getInstance(HMAC_SHA1);
    mac.init(signingKey);
    mac.update(data.getBytes(Constants.UTF_8));
    return toHex(mac.doFinal());
  } catch (Exception e) {
    return Strings.EMPTY;
  }
}

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

/**
 * Returns the digest for the stream.
 *
 * @param valueToDigest
 *            the data to use
 *            <p>
 *            The InputStream must not be null and will not be closed
 *            </p>
 * @return the digest
 * @throws IOException
 *             If an I/O error occurs.
 * @since 1.11
 */
public byte[] hmac(final InputStream valueToDigest) throws IOException {
  final byte[] buffer = new byte[STREAM_BUFFER_LENGTH];
  int read;
  while ((read = valueToDigest.read(buffer, 0, STREAM_BUFFER_LENGTH) ) > -1) {
    mac.update(buffer, 0, read);
  }
  return mac.doFinal();
}

代码示例来源:origin: twosigma/beakerx

public String signBytes(List<byte[]> msg) {
 try {
  final Mac mac = Mac.getInstance(TYPE);
  mac.init(spec);
  msg.forEach(it -> mac.update(it));
  byte[] digest = mac.doFinal();
  return toHex(digest);
 } catch (InvalidKeyException e) {
  throw new RuntimeException(INVALID_HMAC_EXCEPTION, e);
 } catch (NoSuchAlgorithmException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: knowm/XChange

String digest(String httpMethod, String invocationUrl, String reqContentType, String now) {
  Mac mac256 = getMac();
  mac256.update(httpMethod.toLowerCase().getBytes());
  mac256.update(invocationUrl.toLowerCase().getBytes());
  if (!"GET".equals(httpMethod)) {
   mac256.update(reqContentType.toLowerCase().getBytes());
  }
  mac256.update(now.toLowerCase().getBytes());
  return Base64.getEncoder().encodeToString(mac256.doFinal());
 }
}

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

public byte[] hi(byte[] str, byte[] salt, int iterations) throws InvalidKeyException {
  mac.init(new SecretKeySpec(str, mac.getAlgorithm()));
  mac.update(salt);
  byte[] u1 = mac.doFinal(new byte[]{0, 0, 0, 1});
  byte[] prev = u1;
  byte[] result = u1;
  for (int i = 2; i <= iterations; i++) {
    byte[] ui = hmac(str, prev);
    result = xor(result, ui);
    prev = ui;
  }
  return result;
}

代码示例来源:origin: knowm/XChange

String digest(String url, String nonce, String requestBody) {
  Mac mac = getMac();
  if (!url.startsWith("/")) {
   url = "/" + url;
  }
  mac.update(url.getBytes());
  mac.update("\n".getBytes());
  mac.update(nonce.getBytes());
  mac.update("\n".getBytes());
  if (requestBody != null && !requestBody.isEmpty()) {
   mac.update(requestBody.getBytes());
  }

  return Base64.getEncoder().encodeToString(mac.doFinal());
 }
}

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

private byte[] calculateHMAC(byte[] key, byte[] seqNum, byte[] msg, int start,
  int len) throws SaslException {
 byte[] seqAndMsg = new byte[4+len];
 System.arraycopy(seqNum, 0, seqAndMsg, 0, 4);
 System.arraycopy(msg, start, seqAndMsg, 4, len);
 try {
  SecretKey keyKi = new SecretKeySpec(key, "HmacMD5");
  Mac m = Mac.getInstance("HmacMD5");
  m.init(keyKi);
  m.update(seqAndMsg);
  byte[] hMAC_MD5 = m.doFinal();
  /* First 10 bytes of HMAC_MD5 digest */
  byte macBuffer[] = new byte[10];
  System.arraycopy(hMAC_MD5, 0, macBuffer, 0, 10);
  return macBuffer;
 } catch (InvalidKeyException e) {
  throw new SaslException("Invalid bytes used for key of HMAC-MD5 hash.", e);
 } catch (NoSuchAlgorithmException e) {
  throw new SaslException("Error creating instance of MD5 MAC algorithm", e);
 }
}

代码示例来源:origin: knowm/XChange

@Override
 public String digestParams(RestInvocation restInvocation) {

  Mac mac256 = getMac();
  mac256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
  mac256.update(clientId.getBytes());
  mac256.update(apiKey.getBytes());

  return String.format("%064x", new BigInteger(1, mac256.doFinal())).toUpperCase();
 }
}

代码示例来源:origin: org.mongodb/mongo-java-driver

private byte[] hi(final byte[] password, final byte[] salt, final int iterations) throws SaslException {
  try {
    SecretKeySpec key = new SecretKeySpec(password, hmacAlgorithm);
    Mac mac = Mac.getInstance(hmacAlgorithm);
    mac.init(key);
    mac.update(salt);
    mac.update(INT_1);
    byte[] result = mac.doFinal();
    byte[] previous = null;
    for (int i = 1; i < iterations; i++) {
      mac.update(previous != null ? previous : result);
      previous = mac.doFinal();
      xorInPlace(result, previous);
    }
    return result;
  } catch (NoSuchAlgorithmException e) {
    throw new SaslException(format("Algorithm for '%s' could not be found.", hmacAlgorithm), e);
  } catch (InvalidKeyException e) {
    throw new SaslException(format("Invalid key for %s", hmacAlgorithm), e);
  }
}

代码示例来源:origin: igniterealtime/Openfire

public static byte[] createSaltedPassword(byte[] salt, String password, int iters) throws SaslException {
  Mac mac = createSha1Hmac(password.getBytes(StandardCharsets.UTF_8));
  mac.update(salt);
  mac.update(new byte[]{0, 0, 0, 1});
  byte[] result = mac.doFinal();
  byte[] previous = null;
  for (int i = 1; i < iters; i++) {
    mac.update(previous != null ? previous : result);
    previous = mac.doFinal();
    for (int x = 0; x < result.length; x++) {
      result[x] ^= previous[x];
    }
  }
  return result;
}

代码示例来源:origin: signalapp/Signal-Server

private byte[] getCiphertext(byte[] plaintext, SecretKeySpec cipherKey, SecretKeySpec macKey)
  throws CryptoEncodingException
{
 try {
  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, cipherKey);
  Mac hmac = Mac.getInstance("HmacSHA256");
  hmac.init(macKey);
  hmac.update(VERSION);
  byte[] ivBytes = cipher.getIV();
  hmac.update(ivBytes);
  byte[] ciphertext   = cipher.doFinal(plaintext);
  byte[] mac          = hmac.doFinal(ciphertext);
  byte[] truncatedMac = new byte[MAC_SIZE];
  System.arraycopy(mac, 0, truncatedMac, 0, truncatedMac.length);
  return Util.combine(VERSION, ivBytes, ciphertext, truncatedMac);
 } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
  throw new AssertionError(e);
 } catch (InvalidKeyException e) {
  logger.warn("Invalid Key", e);
  throw new CryptoEncodingException("Invalid key!");
 }
}

代码示例来源:origin: knowm/XChange

@Override
 public String digestParams(RestInvocation restInvocation) {

  Mac mac256 = getMac();
  mac256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
  mac256.update(clientId.getBytes());
  mac256.update(apiKey.getBytes());

  return String.format("%064x", new BigInteger(1, mac256.doFinal())).toUpperCase();
 }
}

代码示例来源:origin: google/guava

public void testMultipleUpdates() throws Exception {
 Mac mac = Mac.getInstance("HmacSHA1");
 mac.init(SHA1_KEY);
 mac.update("hello".getBytes(UTF_8));
 mac.update("world".getBytes(UTF_8));
 assertEquals(
   HashCode.fromBytes(mac.doFinal()),
   Hashing.hmacSha1(SHA1_KEY)
     .newHasher()
     .putString("hello", UTF_8)
     .putString("world", UTF_8)
     .hash());
}

代码示例来源:origin: knowm/XChange

@Override
 public String digestParams(RestInvocation restInvocation) {
  Mac mac256 = getMac();
  mac256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
  mac256.update(clientId.getBytes());
  mac256.update(apiKey.getBytes());

  return String.format("%064x", new BigInteger(1, mac256.doFinal())).toUpperCase();
 }
}

代码示例来源:origin: google/guava

private static void assertMacHashing(
  byte[] input, String algorithm, SecretKey key, HashFunction hashFunc) throws Exception {
 Mac mac = Mac.getInstance(algorithm);
 mac.init(key);
 mac.update(input);
 assertEquals(HashCode.fromBytes(mac.doFinal()), hashFunc.hashBytes(input));
 assertEquals(HashCode.fromBytes(mac.doFinal(input)), hashFunc.hashBytes(input));
}

代码示例来源:origin: knowm/XChange

@Override
 public String digestParams(RestInvocation restInvocation) {

  Mac mac256 = getMac();
  mac256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
  mac256.update(clientId.getBytes());
  mac256.update(publicApiKey.getBytes());

  return String.format("%064x", new BigInteger(1, mac256.doFinal())).toUpperCase();
 }
}

相关文章