本文整理了Java中javax.crypto.Mac
类的一些代码示例,展示了Mac
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Mac
类的具体详情如下:
包路径:javax.crypto.Mac
类名称:Mac
[英]This class provides the public API for Message Authentication Code (MAC) algorithms.
[中]此类为消息身份验证码(MAC)算法提供公共API。
代码示例来源: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);
}
}
内容来源于网络,如有侵权,请联系作者删除!