congrats Icon
New! Announcing Tabnine Chat Beta
Learn More
Tabnine Logo
Mac
Code IndexAdd Tabnine to your IDE (free)

How to use
Mac
in
javax.crypto

Best Java code snippets using javax.crypto.Mac (Showing top 20 results out of 7,731)

Refine searchRefine arrow

  • SecretKeySpec
  • MessageDigest
  • Cipher
  • Hex
  • IvParameterSpec
  • Base64
origin: prestodb/presto

private ByteString hmac(String algorithm, ByteString key) {
 try {
  Mac mac = Mac.getInstance(algorithm);
  mac.init(new SecretKeySpec(key.toByteArray(), algorithm));
  return ByteString.of(mac.doFinal(data));
 } catch (NoSuchAlgorithmException e) {
  throw new AssertionError(e);
 } catch (InvalidKeyException e) {
  throw new IllegalArgumentException(e);
 }
}
origin: knowm/XChange

 @Override
 public String digestParams(RestInvocation restInvocation) {

  MessageDigest sha256;
  try {
   sha256 = MessageDigest.getInstance("SHA-256");
  } catch (NoSuchAlgorithmException e) {
   throw new RuntimeException(
     "Illegal algorithm for post body digest. Check the implementation.");
  }
  sha256.update(restInvocation.getParamValue(FormParam.class, "nonce").toString().getBytes());
  sha256.update(restInvocation.getRequestBody().getBytes());

  Mac mac512 = getMac();
  mac512.update(("/" + restInvocation.getPath()).getBytes());
  mac512.update(sha256.digest());

  return Base64.getEncoder().encodeToString(mac512.doFinal()).trim();
 }
}
origin: google/guava

private static Mac getMac(String algorithmName, Key key) {
 try {
  Mac mac = Mac.getInstance(algorithmName);
  mac.init(key);
  return mac;
 } catch (NoSuchAlgorithmException e) {
  throw new IllegalStateException(e);
 } catch (InvalidKeyException e) {
  throw new IllegalArgumentException(e);
 }
}
origin: apache/kafka

public byte[] hmac(byte[] key, byte[] bytes) throws InvalidKeyException {
  mac.init(new SecretKeySpec(key, mac.getAlgorithm()));
  return mac.doFinal(bytes);
}
origin: com.h2database/h2

private static Mac initMac(byte[] key) {
  // Java forbids empty keys
  if (key.length == 0) {
    key = new byte[1];
  }
  try {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key, "HmacSHA256"));
    return mac;
  } catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
  }
}
origin: hierynomus/sshj

try {
  MessageDigest digest = MessageDigest.getInstance("SHA-1");
  digest.update("putty-private-key-file-mac-key".getBytes());
  if (passphrase != null) {
    digest.update(passphrase.getBytes());
  final byte[] key = digest.digest();
  final Mac mac = Mac.getInstance("HmacSHA1");
  mac.init(new SecretKeySpec(key, 0, 20, mac.getAlgorithm()));
  data.write(privateKey);
  final String encoded = Hex.toHexString(mac.doFinal(out.toByteArray()));
  final String reference = headers.get("Private-MAC");
  if (!encoded.equals(reference)) {
origin: plutext/docx4j

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
byte keyspec[] = cipher.doFinal(ace.encryptedKey);
SecretKeySpec secretKey = new SecretKeySpec(keyspec, ver.getCipherAlgorithm().jceId);
x509Hmac.init(secretKey);
byte certVerifier[] = x509Hmac.doFinal(ace.x509.getEncoded());
origin: apache/incubator-dubbo

MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(encoded);
byte[] fingerprint = md.digest();
Cipher keyCipher = Cipher.getInstance(keyAlgorithm);
keyCipher.init(Cipher.WRAP_MODE, _privateKey);
byte[] encKey = keyCipher.wrap(sharedKey);
_out.writeBytes(encKey);
_mac = Mac.getInstance(_algorithm);
_mac.init(sharedKey);
origin: wildfly/wildfly

final Mac mac = Mac.getInstance(getMechanism().getHmacName());
final MessageDigest messageDigest = MessageDigest.getInstance(getMechanism().getMessageDigestName());
mac.reset();
byte[] saltedPassword = initialResult.getScramDigestPassword().getDigest();
mac.init(new SecretKeySpec(saltedPassword, mac.getAlgorithm()));
mac.update(ScramUtil.CLIENT_KEY_BYTES);
clientKey = mac.doFinal();
if(trace) saslScram.tracef("[S] Client key: %s%n", ByteIterator.ofBytes(clientKey).hexEncode().drainToString());
mac.reset();
mac.init(new SecretKeySpec(storedKey, mac.getAlgorithm()));
final byte[] clientFirstMessage = clientMessage.getInitialResponse().getRawMessageBytes();
final int clientFirstMessageBareStart = clientMessage.getInitialResponse().getInitialPartIndex();
mac.update(clientFirstMessage, clientFirstMessageBareStart, clientFirstMessage.length - clientFirstMessageBareStart);
if(trace) saslScram.tracef("[S] Using client first message: %s%n", ByteIterator.ofBytes(copyOfRange(clientFirstMessage, clientFirstMessageBareStart, clientFirstMessage.length)).hexEncode().drainToString());
mac.update((byte) ',');
final byte[] serverFirstMessage = initialResult.getScramInitialChallenge().getRawMessageBytes();
mac.update(serverFirstMessage);
if(trace) saslScram.tracef("[S] Using server first message: %s%n", ByteIterator.ofBytes(serverFirstMessage).hexEncode().drainToString());
mac.update((byte) ',');
final byte[] response = clientMessage.getRawMessageBytes();
final int proofOffset = clientMessage.getProofOffset();
mac.update(response, 0, proofOffset); // client-final-message-without-proof
if(trace) saslScram.tracef("[S] Using client final message without proof: %s%n", ByteIterator.ofBytes(copyOfRange(response, 0, proofOffset)).hexEncode().drainToString());
byte[] clientSignature = mac.doFinal();
if(trace) saslScram.tracef("[S] Client signature: %s%n", ByteIterator.ofBytes(clientSignature).hexEncode().drainToString());
mac.reset();
origin: crsmoro/scplayer

MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
byte[] checksum = Arrays.copyOfRange(blobBytes, blobBytes.length-20, blobBytes.length); // checksum
Key base = new SecretKeySpec(Arrays.copyOfRange(messageDigest.digest(clampArray(sharedKey, 96)), 0, 16), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(base);
Key checksumKey = new SecretKeySpec(mac.doFinal("checksum".getBytes()), "HmacSHA1");
Mac checksumMac = Mac.getInstance("HmacSHA1");
checksumMac.init(checksumKey);
byte[] actualChecksum = checksumMac.doFinal(encrypted);
assert Arrays.equals(checksum, actualChecksum);
Key encryptionKey = new SecretKeySpec(Arrays.copyOfRange(mac.doFinal("encryption".getBytes()), 0, 16), "AES");
Cipher cipher = Cipher.getInstance("AES/CTR/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, encryptionKey,new IvParameterSpec(iv));
byte[] decrypted = cipher.doFinal(encrypted);
String decryptedBlob = new String(decrypted);
origin: poreid/poreid

private byte[] decipherCache(byte[] bundle) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException{
  Cipher cipher;
  byte[] ivData;
  IvParameterSpec iv;
  Mac mac;
  byte[] cipheredContent;
  byte[] decipheredContent;
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");       
  mac = Mac.getInstance("HmacSHA1");
  mac.init(new SecretKeySpec(this.keyHMAC, "HmacSHA1"));
  
  if (bundle.length < cipher.getBlockSize()+mac.getMacLength()){
    return null; /* null - correto */ 
  }
  
  cipheredContent = Arrays.copyOfRange(bundle, cipher.getBlockSize()+mac.getMacLength(),bundle.length);
  if (!Arrays.equals(mac.doFinal(cipheredContent), Arrays.copyOfRange(bundle, cipher.getBlockSize(),cipher.getBlockSize()+mac.getMacLength()))){
    return null;
  }
  
  ivData = Arrays.copyOfRange(bundle, 0, cipher.getBlockSize());
  iv = new IvParameterSpec(ivData);
  cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(this.keyAES, "AES"), iv);        
  decipheredContent = cipher.doFinal(cipheredContent);
  
  long cacheDate = ((ByteBuffer) (ByteBuffer.allocate(Long.SIZE / Byte.SIZE).put(Arrays.copyOfRange(decipheredContent, 0, 8)).flip())).getLong();
  return cacheStatus.isValid(cacheDate) ? Arrays.copyOfRange(decipheredContent, 8, decipheredContent.length) : null;        
}
 
origin: stackoverflow.com

SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(keyBytes);
mac.init(keySpec);
verifyMac(mac.doFinal(ciphertext), macBytes);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] results = cipher.doFinal(ciphertext);
return new String(results, "UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA1");
byte[] mac1_hash = sha.digest(mac1);
sha.reset();
byte[] mac2_hash = sha.digest(mac2);
origin: wildfly/wildfly

final Mac mac = Mac.getInstance(getMechanism().getHmacName());
final MessageDigest messageDigest = MessageDigest.getInstance(getMechanism().getMessageDigestName());
mac.init(new SecretKeySpec(saltedPassword, mac.getAlgorithm()));
final byte[] clientKey = mac.doFinal(ScramUtil.CLIENT_KEY_BYTES);
if(trace) saslScram.tracef("[C] Client key: %s", ByteIterator.ofBytes(clientKey).hexEncode().drainToString());
final byte[] storedKey = messageDigest.digest(clientKey);
if(trace) saslScram.tracef("[C] Stored key: %s%n", ByteIterator.ofBytes(storedKey).hexEncode().drainToString());
mac.init(new SecretKeySpec(storedKey, mac.getAlgorithm()));
final byte[] initialResponseBytes = initialResponse.getRawMessageBytes();
mac.update(initialResponseBytes, initialResponse.getInitialPartIndex(), initialResponseBytes.length - initialResponse.getInitialPartIndex());
if (trace) saslScram.tracef("[C] Using client first message: %s%n", ByteIterator.ofBytes(initialResponseBytes, initialResponse.getInitialPartIndex(), initialResponseBytes.length - initialResponse.getInitialPartIndex()).hexEncode().drainToString());
mac.update((byte) ',');
mac.update(initialChallenge.getRawMessageBytes());
if(trace) saslScram.tracef("[C] Using server first message: %s%n", ByteIterator.ofBytes(initialChallenge.getRawMessageBytes()).hexEncode().drainToString());
mac.update((byte) ',');
encoded.updateMac(mac);
if(trace) saslScram.tracef("[C] Using client final message without proof: %s%n", ByteIterator.ofBytes(encoded.toArray()).hexEncode().drainToString());
final byte[] clientProof = mac.doFinal();
if(trace) saslScram.tracef("[C] Client signature: %s%n", ByteIterator.ofBytes(clientProof).hexEncode().drainToString());
ScramUtil.xor(clientProof, clientKey);
origin: knowm/XChange

 @Override
 public String digestParams(RestInvocation restInvocation) {
  try {
   String urlMethod = restInvocation.getInvocationUrl();
   String nonce = String.valueOf(nonceFactory.createValue());

   String body = restInvocation.getRequestBody();
   String md5 =
     Base64.getEncoder()
       .encodeToString(MessageDigest.getInstance("MD5").digest(body.getBytes("UTF-8")));

   String reqSignature =
     apiKey
       + "POST"
       + URLEncoder.encode(urlMethod, StandardCharsets.UTF_8.toString()).toLowerCase()
       + nonce
       + md5;

   return "amx "
     + apiKey
     + ":"
     + Base64.getEncoder().encodeToString(getMac().doFinal(reqSignature.getBytes("UTF-8")))
     + ":"
     + nonce;
  } catch (Exception e) {
   throw new IllegalStateException("Faile to sign request", e);
  }
 }
}
origin: stackoverflow.com

 String message = "[1312701386,transactioncreate,[account_code:ABC,amount_in_cents:5000,currency:USD]]";
String privateKey = "0123456789ABCDEF0123456789ABCDEF";

MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] keyBytes = md.digest(privateKey.getBytes("UTF-8"));

SecretKey sk = new SecretKeySpec(keyBytes, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(sk);
byte[] result = mac.doFinal(message.getBytes("ASCII"));

System.out.println("  Message: " + message);
System.out.println("      Key: " + privateKey + "\n");
System.out.println("Key Bytes: " + toHex(keyBytes));
System.out.println("  Results: " + toHex(result));
origin: RNCryptor/JNCryptor

@Override
public byte[] encryptData(byte[] plaintext, SecretKey encryptionKey,
  SecretKey hmacKey) throws CryptorException {
 Validate.notNull(plaintext, "Plaintext cannot be null.");
 Validate.notNull(encryptionKey, "Encryption key cannot be null.");
 Validate.notNull(hmacKey, "HMAC key cannot be null.");
 byte[] iv = getSecureRandomData(AES_BLOCK_SIZE);
 try {
  Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
  cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(iv));
  byte[] ciphertext = cipher.doFinal(plaintext);
  AES256v3Ciphertext output = new AES256v3Ciphertext(iv, ciphertext);
  Mac mac = Mac.getInstance(HMAC_ALGORITHM);
  mac.init(hmacKey);
  byte[] hmac = mac.doFinal(output.getDataToHMAC());
  output.setHmac(hmac);
  return output.getRawData();
 } catch (GeneralSecurityException e) {
  throw new CryptorException("Failed to generate ciphertext.", e);
 }
}
origin: aws/aws-sdk-java

  throw new IllegalArgumentException("Max buffer size should not be less than chunk size");
try {
  this.sha256 = MessageDigest.getInstance("SHA-256");
  final String signingAlgo = SigningAlgorithm.HmacSHA256.toString();
  this.hmacSha256 = Mac.getInstance(signingAlgo);
  hmacSha256.init(new SecretKeySpec(kSigning, signingAlgo));
} catch (NoSuchAlgorithmException e) {
  throw new IllegalStateException(e);
origin: com.google.crypto.tink/tink

/**
 * Encrypts the next plaintext segment. This uses encryptedSegments as the segment number for
 * the encryption.
 */
@Override
public synchronized void encryptSegment(
  ByteBuffer plaintext, boolean isLastSegment, ByteBuffer ciphertext)
  throws GeneralSecurityException {
 int position = ciphertext.position();
 byte[] nonce = nonceForSegment(noncePrefix, encryptedSegments, isLastSegment);
 cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(nonce));
 encryptedSegments++;
 cipher.doFinal(plaintext, ciphertext);
 ByteBuffer ctCopy = ciphertext.duplicate();
 ctCopy.flip();
 ctCopy.position(position);
 mac.init(hmacKeySpec);
 mac.update(nonce);
 mac.update(ctCopy);
 byte[] tag = mac.doFinal();
 ciphertext.put(tag, 0, tagSizeInBytes);
}
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: prestodb/presto

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

Javadoc

This class provides the public API for Message Authentication Code (MAC) algorithms.

Most used methods

  • doFinal
    Computes the digest of this MAC based on the data previously specified in #update calls and stores t
  • init
    Initializes this Mac instance with the specified key and algorithm parameters.
  • getInstance
    Creates a new Mac instance that provides the specified MAC algorithm from the specified provider.
  • update
    Updates this Mac instance with the data from the specified buffer input from the specified offset an
  • getMacLength
    Returns the length of this MAC (in bytes).
  • reset
    Resets this Mac instance to its initial state. This Mac instance is reverted to its initial state an
  • getAlgorithm
    Returns the name of the MAC algorithm.
  • clone
    Clones this Mac instance and the underlying implementation.
  • <init>
    Creates a new Mac instance.
  • getProvider
    Returns the provider of this Mac instance.
  • getMacSize
  • getMacSize

Popular in Java

  • Parsing JSON documents to java classes using gson
  • getSystemService (Context)
  • onRequestPermissionsResult (Fragment)
  • getExternalFilesDir (Context)
  • Menu (java.awt)
  • OutputStream (java.io)
    A writable sink for bytes.Most clients will use output streams that write data to the file system (
  • PrintWriter (java.io)
    Wraps either an existing OutputStream or an existing Writerand provides convenience methods for prin
  • Callable (java.util.concurrent)
    A task that returns a result and may throw an exception. Implementors define a single method with no
  • CountDownLatch (java.util.concurrent)
    A synchronization aid that allows one or more threads to wait until a set of operations being perfor
  • IsNull (org.hamcrest.core)
    Is the value null?
  • CodeWhisperer alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now