javax.crypto.Mac类的使用及代码示例

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

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

Mac介绍

[英]This class provides the public API for Message Authentication Code (MAC) algorithms.
[中]此类为消息身份验证码(MAC)算法提供公共API。

代码示例

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

  1. private ByteString hmac(String algorithm, ByteString key) {
  2. try {
  3. Mac mac = Mac.getInstance(algorithm);
  4. mac.init(new SecretKeySpec(key.toByteArray(), algorithm));
  5. return ByteString.of(mac.doFinal(data));
  6. } catch (NoSuchAlgorithmException e) {
  7. throw new AssertionError(e);
  8. } catch (InvalidKeyException e) {
  9. throw new IllegalArgumentException(e);
  10. }
  11. }

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

  1. @Override
  2. public String digestParams(RestInvocation restInvocation) {
  3. MessageDigest sha256;
  4. try {
  5. sha256 = MessageDigest.getInstance("SHA-256");
  6. } catch (NoSuchAlgorithmException e) {
  7. throw new RuntimeException(
  8. "Illegal algorithm for post body digest. Check the implementation.");
  9. }
  10. sha256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
  11. sha256.update(restInvocation.getRequestBody().getBytes());
  12. Mac mac512 = getMac();
  13. mac512.update(("/" + restInvocation.getPath()).getBytes());
  14. mac512.update(sha256.digest());
  15. return Base64.getEncoder().encodeToString(mac512.doFinal()).trim();
  16. }
  17. }

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

  1. private static Mac getMac(String algorithmName, Key key) {
  2. try {
  3. Mac mac = Mac.getInstance(algorithmName);
  4. mac.init(key);
  5. return mac;
  6. } catch (NoSuchAlgorithmException e) {
  7. throw new IllegalStateException(e);
  8. } catch (InvalidKeyException e) {
  9. throw new IllegalArgumentException(e);
  10. }
  11. }

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

  1. public byte[] hmac(byte[] key, byte[] bytes) throws InvalidKeyException {
  2. mac.init(new SecretKeySpec(key, mac.getAlgorithm()));
  3. return mac.doFinal(bytes);
  4. }

代码示例来源:origin: com.h2database/h2

  1. private static Mac initMac(byte[] key) {
  2. // Java forbids empty keys
  3. if (key.length == 0) {
  4. key = new byte[1];
  5. }
  6. try {
  7. Mac mac = Mac.getInstance("HmacSHA256");
  8. mac.init(new SecretKeySpec(key, "HmacSHA256"));
  9. return mac;
  10. } catch (GeneralSecurityException e) {
  11. throw new RuntimeException(e);
  12. }
  13. }

代码示例来源:origin: hierynomus/sshj

  1. try {
  2. MessageDigest digest = MessageDigest.getInstance("SHA-1");
  3. digest.update("putty-private-key-file-mac-key".getBytes());
  4. if (passphrase != null) {
  5. digest.update(passphrase.getBytes());
  6. final byte[] key = digest.digest();
  7. final Mac mac = Mac.getInstance("HmacSHA1");
  8. mac.init(new SecretKeySpec(key, 0, 20, mac.getAlgorithm()));
  9. data.write(privateKey);
  10. final String encoded = Hex.toHexString(mac.doFinal(out.toByteArray()));
  11. final String reference = headers.get("Private-MAC");
  12. if (!encoded.equals(reference)) {

代码示例来源:origin: plutext/docx4j

  1. Cipher cipher = Cipher.getInstance("RSA");
  2. cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
  3. byte keyspec[] = cipher.doFinal(ace.encryptedKey);
  4. SecretKeySpec secretKey = new SecretKeySpec(keyspec, ver.getCipherAlgorithm().jceId);
  5. x509Hmac.init(secretKey);
  6. byte certVerifier[] = x509Hmac.doFinal(ace.x509.getEncoded());

代码示例来源:origin: apache/incubator-dubbo

  1. MessageDigest md = MessageDigest.getInstance("SHA1");
  2. md.update(encoded);
  3. byte[] fingerprint = md.digest();
  4. Cipher keyCipher = Cipher.getInstance(keyAlgorithm);
  5. keyCipher.init(Cipher.WRAP_MODE, _privateKey);
  6. byte[] encKey = keyCipher.wrap(sharedKey);
  7. _out.writeBytes(encKey);
  8. _mac = Mac.getInstance(_algorithm);
  9. _mac.init(sharedKey);

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

  1. final Mac mac = Mac.getInstance(getMechanism().getHmacName());
  2. final MessageDigest messageDigest = MessageDigest.getInstance(getMechanism().getMessageDigestName());
  3. mac.reset();
  4. byte[] saltedPassword = initialResult.getScramDigestPassword().getDigest();
  5. mac.init(new SecretKeySpec(saltedPassword, mac.getAlgorithm()));
  6. mac.update(ScramUtil.CLIENT_KEY_BYTES);
  7. clientKey = mac.doFinal();
  8. if(trace) saslScram.tracef("[S] Client key: %s%n", ByteIterator.ofBytes(clientKey).hexEncode().drainToString());
  9. mac.reset();
  10. mac.init(new SecretKeySpec(storedKey, mac.getAlgorithm()));
  11. final byte[] clientFirstMessage = clientMessage.getInitialResponse().getRawMessageBytes();
  12. final int clientFirstMessageBareStart = clientMessage.getInitialResponse().getInitialPartIndex();
  13. mac.update(clientFirstMessage, clientFirstMessageBareStart, clientFirstMessage.length - clientFirstMessageBareStart);
  14. if(trace) saslScram.tracef("[S] Using client first message: %s%n", ByteIterator.ofBytes(copyOfRange(clientFirstMessage, clientFirstMessageBareStart, clientFirstMessage.length)).hexEncode().drainToString());
  15. mac.update((byte) ',');
  16. final byte[] serverFirstMessage = initialResult.getScramInitialChallenge().getRawMessageBytes();
  17. mac.update(serverFirstMessage);
  18. if(trace) saslScram.tracef("[S] Using server first message: %s%n", ByteIterator.ofBytes(serverFirstMessage).hexEncode().drainToString());
  19. mac.update((byte) ',');
  20. final byte[] response = clientMessage.getRawMessageBytes();
  21. final int proofOffset = clientMessage.getProofOffset();
  22. mac.update(response, 0, proofOffset); // client-final-message-without-proof
  23. if(trace) saslScram.tracef("[S] Using client final message without proof: %s%n", ByteIterator.ofBytes(copyOfRange(response, 0, proofOffset)).hexEncode().drainToString());
  24. byte[] clientSignature = mac.doFinal();
  25. if(trace) saslScram.tracef("[S] Client signature: %s%n", ByteIterator.ofBytes(clientSignature).hexEncode().drainToString());
  26. mac.reset();

代码示例来源:origin: crsmoro/scplayer

  1. MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
  2. byte[] checksum = Arrays.copyOfRange(blobBytes, blobBytes.length-20, blobBytes.length); // checksum
  3. Key base = new SecretKeySpec(Arrays.copyOfRange(messageDigest.digest(clampArray(sharedKey, 96)), 0, 16), "HmacSHA1");
  4. Mac mac = Mac.getInstance("HmacSHA1");
  5. mac.init(base);
  6. Key checksumKey = new SecretKeySpec(mac.doFinal("checksum".getBytes()), "HmacSHA1");
  7. Mac checksumMac = Mac.getInstance("HmacSHA1");
  8. checksumMac.init(checksumKey);
  9. byte[] actualChecksum = checksumMac.doFinal(encrypted);
  10. assert Arrays.equals(checksum, actualChecksum);
  11. Key encryptionKey = new SecretKeySpec(Arrays.copyOfRange(mac.doFinal("encryption".getBytes()), 0, 16), "AES");
  12. Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");
  13. cipher.init(Cipher.DECRYPT_MODE, encryptionKey,new IvParameterSpec(iv));
  14. byte[] decrypted = cipher.doFinal(encrypted);
  15. String decryptedBlob = new String(decrypted);

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

  1. private byte[] decipherCache(byte[] bundle) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException{
  2. Cipher cipher;
  3. byte[] ivData;
  4. IvParameterSpec iv;
  5. Mac mac;
  6. byte[] cipheredContent;
  7. byte[] decipheredContent;
  8. cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  9. mac = Mac.getInstance("HmacSHA1");
  10. mac.init(new SecretKeySpec(this.keyHMAC, "HmacSHA1"));
  11. if (bundle.length < cipher.getBlockSize()+mac.getMacLength()){
  12. return null; /* null - correto */
  13. }
  14. cipheredContent = Arrays.copyOfRange(bundle, cipher.getBlockSize()+mac.getMacLength(),bundle.length);
  15. if (!Arrays.equals(mac.doFinal(cipheredContent), Arrays.copyOfRange(bundle, cipher.getBlockSize(),cipher.getBlockSize()+mac.getMacLength()))){
  16. return null;
  17. }
  18. ivData = Arrays.copyOfRange(bundle, 0, cipher.getBlockSize());
  19. iv = new IvParameterSpec(ivData);
  20. cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(this.keyAES, "AES"), iv);
  21. decipheredContent = cipher.doFinal(cipheredContent);
  22. long cacheDate = ((ByteBuffer) (ByteBuffer.allocate(Long.SIZE / Byte.SIZE).put(Arrays.copyOfRange(decipheredContent, 0, 8)).flip())).getLong();
  23. return cacheStatus.isValid(cacheDate) ? Arrays.copyOfRange(decipheredContent, 8, decipheredContent.length) : null;
  24. }

代码示例来源:origin: stackoverflow.com

  1. SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
  2. IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
  3. mac.init(keySpec);
  4. verifyMac(mac.doFinal(ciphertext), macBytes);
  5. cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
  6. byte[] results = cipher.doFinal(ciphertext);
  7. return new String(results, "UTF-8");
  8. MessageDigest sha = MessageDigest.getInstance("SHA1");
  9. byte[] mac1_hash = sha.digest(mac1);
  10. sha.reset();
  11. byte[] mac2_hash = sha.digest(mac2);

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

  1. final Mac mac = Mac.getInstance(getMechanism().getHmacName());
  2. final MessageDigest messageDigest = MessageDigest.getInstance(getMechanism().getMessageDigestName());
  3. mac.init(new SecretKeySpec(saltedPassword, mac.getAlgorithm()));
  4. final byte[] clientKey = mac.doFinal(ScramUtil.CLIENT_KEY_BYTES);
  5. if(trace) saslScram.tracef("[C] Client key: %s", ByteIterator.ofBytes(clientKey).hexEncode().drainToString());
  6. final byte[] storedKey = messageDigest.digest(clientKey);
  7. if(trace) saslScram.tracef("[C] Stored key: %s%n", ByteIterator.ofBytes(storedKey).hexEncode().drainToString());
  8. mac.init(new SecretKeySpec(storedKey, mac.getAlgorithm()));
  9. final byte[] initialResponseBytes = initialResponse.getRawMessageBytes();
  10. mac.update(initialResponseBytes, initialResponse.getInitialPartIndex(), initialResponseBytes.length - initialResponse.getInitialPartIndex());
  11. if (trace) saslScram.tracef("[C] Using client first message: %s%n", ByteIterator.ofBytes(initialResponseBytes, initialResponse.getInitialPartIndex(), initialResponseBytes.length - initialResponse.getInitialPartIndex()).hexEncode().drainToString());
  12. mac.update((byte) ',');
  13. mac.update(initialChallenge.getRawMessageBytes());
  14. if(trace) saslScram.tracef("[C] Using server first message: %s%n", ByteIterator.ofBytes(initialChallenge.getRawMessageBytes()).hexEncode().drainToString());
  15. mac.update((byte) ',');
  16. encoded.updateMac(mac);
  17. if(trace) saslScram.tracef("[C] Using client final message without proof: %s%n", ByteIterator.ofBytes(encoded.toArray()).hexEncode().drainToString());
  18. final byte[] clientProof = mac.doFinal();
  19. if(trace) saslScram.tracef("[C] Client signature: %s%n", ByteIterator.ofBytes(clientProof).hexEncode().drainToString());
  20. ScramUtil.xor(clientProof, clientKey);

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

  1. @Override
  2. public String digestParams(RestInvocation restInvocation) {
  3. try {
  4. String urlMethod = restInvocation.getInvocationUrl();
  5. String nonce = String.valueOf(nonceFactory.createValue());
  6. String body = restInvocation.getRequestBody();
  7. String md5 =
  8. Base64.getEncoder()
  9. .encodeToString(MessageDigest.getInstance("MD5").digest(body.getBytes("UTF-8")));
  10. String reqSignature =
  11. apiKey
  12. + "POST"
  13. + URLEncoder.encode(urlMethod, StandardCharsets.UTF_8.toString()).toLowerCase()
  14. + nonce
  15. + md5;
  16. return "amx "
  17. + apiKey
  18. + ":"
  19. + Base64.getEncoder().encodeToString(getMac().doFinal(reqSignature.getBytes("UTF-8")))
  20. + ":"
  21. + nonce;
  22. } catch (Exception e) {
  23. throw new IllegalStateException("Faile to sign request", e);
  24. }
  25. }
  26. }

代码示例来源:origin: stackoverflow.com

  1. String message = "[1312701386,transactioncreate,[account_code:ABC,amount_in_cents:5000,currency:USD]]";
  2. String privateKey = "0123456789ABCDEF0123456789ABCDEF";
  3. MessageDigest md = MessageDigest.getInstance("SHA-1");
  4. byte[] keyBytes = md.digest(privateKey.getBytes("UTF-8"));
  5. SecretKey sk = new SecretKeySpec(keyBytes, "HmacSHA1");
  6. Mac mac = Mac.getInstance("HmacSHA1");
  7. mac.init(sk);
  8. byte[] result = mac.doFinal(message.getBytes("ASCII"));
  9. System.out.println(" Message: " + message);
  10. System.out.println(" Key: " + privateKey + "\n");
  11. System.out.println("Key Bytes: " + toHex(keyBytes));
  12. System.out.println(" Results: " + toHex(result));

代码示例来源:origin: RNCryptor/JNCryptor

  1. @Override
  2. public byte[] encryptData(byte[] plaintext, SecretKey encryptionKey,
  3. SecretKey hmacKey) throws CryptorException {
  4. Validate.notNull(plaintext, "Plaintext cannot be null.");
  5. Validate.notNull(encryptionKey, "Encryption key cannot be null.");
  6. Validate.notNull(hmacKey, "HMAC key cannot be null.");
  7. byte[] iv = getSecureRandomData(AES_BLOCK_SIZE);
  8. try {
  9. Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
  10. cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(iv));
  11. byte[] ciphertext = cipher.doFinal(plaintext);
  12. AES256v3Ciphertext output = new AES256v3Ciphertext(iv, ciphertext);
  13. Mac mac = Mac.getInstance(HMAC_ALGORITHM);
  14. mac.init(hmacKey);
  15. byte[] hmac = mac.doFinal(output.getDataToHMAC());
  16. output.setHmac(hmac);
  17. return output.getRawData();
  18. } catch (GeneralSecurityException e) {
  19. throw new CryptorException("Failed to generate ciphertext.", e);
  20. }
  21. }

代码示例来源:origin: aws/aws-sdk-java

  1. throw new IllegalArgumentException("Max buffer size should not be less than chunk size");
  2. try {
  3. this.sha256 = MessageDigest.getInstance("SHA-256");
  4. final String signingAlgo = SigningAlgorithm.HmacSHA256.toString();
  5. this.hmacSha256 = Mac.getInstance(signingAlgo);
  6. hmacSha256.init(new SecretKeySpec(kSigning, signingAlgo));
  7. } catch (NoSuchAlgorithmException e) {
  8. throw new IllegalStateException(e);

代码示例来源:origin: com.google.crypto.tink/tink

  1. /**
  2. * Encrypts the next plaintext segment. This uses encryptedSegments as the segment number for
  3. * the encryption.
  4. */
  5. @Override
  6. public synchronized void encryptSegment(
  7. ByteBuffer plaintext, boolean isLastSegment, ByteBuffer ciphertext)
  8. throws GeneralSecurityException {
  9. int position = ciphertext.position();
  10. byte[] nonce = nonceForSegment(noncePrefix, encryptedSegments, isLastSegment);
  11. cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(nonce));
  12. encryptedSegments++;
  13. cipher.doFinal(plaintext, ciphertext);
  14. ByteBuffer ctCopy = ciphertext.duplicate();
  15. ctCopy.flip();
  16. ctCopy.position(position);
  17. mac.init(hmacKeySpec);
  18. mac.update(nonce);
  19. mac.update(ctCopy);
  20. byte[] tag = mac.doFinal();
  21. ciphertext.put(tag, 0, tagSizeInBytes);
  22. }

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

  1. private byte[] getCiphertext(byte[] plaintext, SecretKeySpec cipherKey, SecretKeySpec macKey)
  2. throws CryptoEncodingException
  3. {
  4. try {
  5. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  6. cipher.init(Cipher.ENCRYPT_MODE, cipherKey);
  7. Mac hmac = Mac.getInstance("HmacSHA256");
  8. hmac.init(macKey);
  9. hmac.update(VERSION);
  10. byte[] ivBytes = cipher.getIV();
  11. hmac.update(ivBytes);
  12. byte[] ciphertext = cipher.doFinal(plaintext);
  13. byte[] mac = hmac.doFinal(ciphertext);
  14. byte[] truncatedMac = new byte[MAC_SIZE];
  15. System.arraycopy(mac, 0, truncatedMac, 0, truncatedMac.length);
  16. return Util.combine(VERSION, ivBytes, ciphertext, truncatedMac);
  17. } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
  18. throw new AssertionError(e);
  19. } catch (InvalidKeyException e) {
  20. logger.warn("Invalid Key", e);
  21. throw new CryptoEncodingException("Invalid key!");
  22. }
  23. }

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

  1. /**
  2. * Returns the hash of the bytes supplied thus far and resets the internal state of this source.
  3. *
  4. * <p><strong>Warning:</strong> This method is not idempotent. Each time this method is called its
  5. * internal state is cleared. This starts a new hash with zero bytes supplied.
  6. */
  7. public ByteString hash() {
  8. byte[] result = messageDigest != null ? messageDigest.digest() : mac.doFinal();
  9. return ByteString.of(result);
  10. }
  11. }

相关文章