List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:org.apache.myfaces.shared.util.StateUtils.java
public static byte[] encrypt(byte[] insecure, ExternalContext ctx) { if (ctx == null) { throw new NullPointerException("ExternalContext ctx"); }/*from w w w . ja v a 2 s. c o m*/ testConfiguration(ctx); SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.ENCRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("encrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); byte[] secure = new byte[cipher.getOutputSize(insecure.length) + macLenght]; int secureCount = cipher.doFinal(insecure, 0, insecure.length, secure); mac.update(secure, 0, secureCount); mac.doFinal(secure, secureCount); return secure; } catch (Exception e) { throw new FacesException(e); } }
From source file:org.apache.myfaces.shared.util.StateUtils.java
public static byte[] decrypt(byte[] secure, ExternalContext ctx) { if (ctx == null) { throw new NullPointerException("ExternalContext ctx"); }//from w ww. j a v a2 s .co m testConfiguration(ctx); SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.DECRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("decrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); mac.update(secure, 0, secure.length - macLenght); byte[] signedDigestHash = mac.doFinal(); boolean isMacEqual = true; for (int i = 0; i < signedDigestHash.length; i++) { if (signedDigestHash[i] != secure[secure.length - macLenght + i]) { isMacEqual = false; // MYFACES-2934 Must compare *ALL* bytes of the hash, // otherwise a side-channel timing attack is theorically possible // but with a very very low probability, because the // comparison time is too small to be measured compared to // the overall request time and in real life applications, // there are too many uncertainties involved. //break; } } if (!isMacEqual) { throw new ViewExpiredException(); } return cipher.doFinal(secure, 0, secure.length - macLenght); } catch (Exception e) { throw new FacesException(e); } }
From source file:com.cloud.servlet.ConsoleProxyServlet.java
public static String genAccessTicket(String host, String port, String sid, String tag, Date normalizedHashTime) { String params = "host=" + host + "&port=" + port + "&sid=" + sid + "&tag=" + tag; try {//from w ww . j av a 2 s . c o m Mac mac = Mac.getInstance("HmacSHA1"); long ts = normalizedHashTime.getTime(); ts = ts / 60000; // round up to 1 minute String secretKey = _ms.getHashKey(); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(params.getBytes()); mac.update(String.valueOf(ts).getBytes()); byte[] encryptedBytes = mac.doFinal(); return Base64.encodeBase64String(encryptedBytes); } catch (Exception e) { s_logger.error("Unexpected exception ", e); } return ""; }
From source file:com.microsoft.azure.keyvault.cryptography.algorithms.AesCbcHmacSha2.java
private static Triple<byte[], byte[], Mac> GetAlgorithmParameters(String algorithm, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException { byte[] aes_key; byte[] hmac_key; Mac hmac; if (algorithm.equalsIgnoreCase(Aes128CbcHmacSha256.ALGORITHM_NAME)) { if ((key.length << 3) < 256) { throw new IllegalArgumentException( String.format("%s key length in bits %d < 256", algorithm, key.length << 3)); }//from w w w . j a v a2 s . com hmac_key = new byte[128 >> 3]; aes_key = new byte[128 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 128 >> 3); System.arraycopy(key, 128 >> 3, aes_key, 0, 128 >> 3); hmac = Mac.getInstance("HmacSHA256"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256")); } else if (algorithm.equalsIgnoreCase(Aes192CbcHmacSha384.ALGORITHM_NAME)) { if ((key.length << 3) < 384) { throw new IllegalArgumentException( String.format("%s key length in bits %d < 384", algorithm, key.length << 3)); } hmac_key = new byte[192 >> 3]; aes_key = new byte[192 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 192 >> 3); System.arraycopy(key, 192 >> 3, aes_key, 0, 192 >> 3); hmac = Mac.getInstance("HmacSHA384"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA384")); } else if (algorithm.equalsIgnoreCase(Aes256CbcHmacSha512.ALGORITHM_NAME)) { if ((key.length << 3) < 512) { throw new IllegalArgumentException( String.format("%s key length in bits %d < 512", algorithm, key.length << 3)); } hmac_key = new byte[256 >> 3]; aes_key = new byte[256 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 256 >> 3); System.arraycopy(key, 256 >> 3, aes_key, 0, 256 >> 3); hmac = Mac.getInstance("HmacSHA512"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA512")); } else { throw new IllegalArgumentException(String.format("Unsupported algorithm: %s", algorithm)); } return Triple.of(aes_key, hmac_key, hmac); }
From source file:com.microsoft.azure.keyvault.extensions.cryptography.algorithms.AesCbcHmacSha2.java
private static Triple<byte[], byte[], Mac> GetAlgorithmParameters(String algorithm, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException { byte[] aes_key; byte[] hmac_key; Mac hmac; if (algorithm.equalsIgnoreCase(Aes128CbcHmacSha256.AlgorithmName)) { if ((key.length << 3) < 256) { throw new IllegalArgumentException( String.format("%s key length in bits %d < 256", algorithm, key.length << 3)); }/*from www.j av a 2s.c om*/ hmac_key = new byte[128 >> 3]; aes_key = new byte[128 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 128 >> 3); System.arraycopy(key, 128 >> 3, aes_key, 0, 128 >> 3); hmac = Mac.getInstance("HmacSHA256"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256")); } else if (algorithm.equalsIgnoreCase(Aes192CbcHmacSha384.AlgorithmName)) { if ((key.length << 3) < 384) { throw new IllegalArgumentException( String.format("%s key length in bits %d < 384", algorithm, key.length << 3)); } hmac_key = new byte[192 >> 3]; aes_key = new byte[192 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 192 >> 3); System.arraycopy(key, 192 >> 3, aes_key, 0, 192 >> 3); hmac = Mac.getInstance("HmacSHA384"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA384")); } else if (algorithm.equalsIgnoreCase(Aes256CbcHmacSha512.AlgorithmName)) { if ((key.length << 3) < 512) { throw new IllegalArgumentException( String.format("%s key length in bits %d < 512", algorithm, key.length << 3)); } hmac_key = new byte[256 >> 3]; aes_key = new byte[256 >> 3]; // The HMAC key precedes the AES key System.arraycopy(key, 0, hmac_key, 0, 256 >> 3); System.arraycopy(key, 256 >> 3, aes_key, 0, 256 >> 3); hmac = Mac.getInstance("HmacSHA512"); hmac.init(new SecretKeySpec(hmac_key, "HmacSHA512")); } else { throw new IllegalArgumentException(String.format("Unsupported algorithm: %s", algorithm)); } return Triple.of(aes_key, hmac_key, hmac); }
From source file:com.algolia.search.saas.APIClient.java
static String hmac(String key, String msg) { Mac hmac; try {/* ww w. j a v a2 s . c o m*/ hmac = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException e) { throw new Error(e); } try { hmac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256")); } catch (InvalidKeyException e) { throw new Error(e); } byte[] rawHmac = hmac.doFinal(msg.getBytes()); byte[] hexBytes = new Hex().encode(rawHmac); return new String(hexBytes); }
From source file:com.microsoft.tfs.jni.internal.ntlm.JavaNTLM.java
private static byte[] createLm2Response(final String username, final String password, final String domain, final NTLMType2Message type2) throws NTLMException { final byte[] ntlm2Hash = ntlm2Hash(username, password, domain); final byte[] clientNonce = createClientNonce(); final byte[] challenges = new byte[type2.challenge.length + clientNonce.length]; addBytes(challenges, 0, type2.challenge); addBytes(challenges, type2.challenge.length, clientNonce); // used HMAC-MD5 on the concatenated challenges w/ the NTLMv2 hash as a // key/*from w ww. ja v a 2 s .c o m*/ byte[] hashedChallenges; try { final Mac mac = Mac.getInstance("HmacMD5"); //$NON-NLS-1$ mac.init(new SecretKeySpec(ntlm2Hash, "HmacMD5")); //$NON-NLS-1$ hashedChallenges = mac.doFinal(challenges); } catch (final Exception e) { LOG.error("Could not load HmacMD5 for NTLM", e); //$NON-NLS-1$ throw new NTLMException(e.getMessage()); } // concatenate the hashed challenges with the client nonce final byte[] lm2Response = new byte[hashedChallenges.length + clientNonce.length]; addBytes(lm2Response, 0, hashedChallenges); addBytes(lm2Response, hashedChallenges.length, clientNonce); return lm2Response; }
From source file:com.microsoft.tfs.jni.internal.ntlm.JavaNTLM.java
private static byte[] ntlm2Hash(final String username, final String password, final String domain) throws NTLMException { // we must get the ntlmHash here, which depends on MD4 which // we sneakily implemented using Cryptix's implementation // this is a requirement for the ntlm2 response (unlike the // type3 ntlm response, which may work despite having no // ntlm message) final byte[] ntlmHash = ntlmHash(password); // we need the username and domain concatenated final byte[] usernameBytes = getBytes(username.toUpperCase(), "UTF-16LE"); //$NON-NLS-1$ final byte[] domainBytes = getBytes(domain.toUpperCase(), "UTF-16LE"); //$NON-NLS-1$ final byte[] usernameDomainBytes = new byte[usernameBytes.length + domainBytes.length]; int i;/*from ww w . ja v a2s. com*/ for (i = 0; i < usernameBytes.length; i++) { usernameDomainBytes[i] = usernameBytes[i]; } for (int j = 0; j < domainBytes.length; j++) { usernameDomainBytes[i + j] = domainBytes[j]; } // ntlm2 hash is created by running HMAC-MD5 on the unicode // username and domain (uppercased), with the ntlmHash as a // key byte[] ntlm2Hash; try { final Mac mac = Mac.getInstance("HmacMD5"); //$NON-NLS-1$ mac.init(new SecretKeySpec(ntlmHash, "HmacMD5")); //$NON-NLS-1$ ntlm2Hash = mac.doFinal(usernameDomainBytes); } catch (final Exception e) { LOG.error("Could not load HmacMD5 for NTLM", e); //$NON-NLS-1$ throw new NTLMException(e.getMessage()); } return ntlm2Hash; }
From source file:com.microsoft.tfs.jni.internal.ntlm.JavaNTLM.java
private static byte[] createNtlm2Response(final String username, final String password, final String domain, final NTLMType2Message type2) throws NTLMException { final byte[] ntlm2Hash = ntlm2Hash(username, password, domain); final int targetInfoLen = type2.targetInfo != null ? type2.targetInfo.length : 0; final byte[] ntlm2Blob = new byte[40 + targetInfoLen]; // construct the "blob" addBytes(ntlm2Blob, 0, new byte[] { 0x01, 0x01, 0x00, 0x00 }); // "blob" signature addLong(ntlm2Blob, 4, 0); // "reserved" addBytes(ntlm2Blob, 8, createTimestamp()); addBytes(ntlm2Blob, 16, createClientNonce()); addBytes(ntlm2Blob, 24, new byte[] { (byte) 0xad, (byte) 0xde, (byte) 0x15, (byte) 0xed }); // unknown if (targetInfoLen > 0) { addBytes(ntlm2Blob, 28, type2.targetInfo); }/*from w w w.j ava2 s.co m*/ // insert obligatory pixies reference here addBytes(ntlm2Blob, (28 + targetInfoLen), new byte[] { (byte) 0xad, (byte) 0xde, (byte) 0x15, (byte) 0xed }); // again unknown // the end? of the blob // concatenate the type 2 message's challenge with the blob final byte[] challengedBlob = new byte[type2.challenge.length + ntlm2Blob.length]; addBytes(challengedBlob, 0, type2.challenge); addBytes(challengedBlob, type2.challenge.length, ntlm2Blob); // now we get the HMAC-MD5 of the blob using the ntlm2 hash as a key // ick. byte[] blobHash; try { final Mac mac = Mac.getInstance("HmacMD5"); //$NON-NLS-1$ mac.init(new SecretKeySpec(ntlm2Hash, "HmacMD5")); //$NON-NLS-1$ blobHash = mac.doFinal(challengedBlob); } catch (final Exception e) { LOG.error("Could not load HmacMD5 for NTLM", e); //$NON-NLS-1$ throw new NTLMException(e.getMessage()); } final byte[] ntlm2Response = new byte[blobHash.length + ntlm2Blob.length]; // concatenate the blob with its hash addBytes(ntlm2Response, 0, blobHash); addBytes(ntlm2Response, blobHash.length, ntlm2Blob); return ntlm2Response; }
From source file:me.whitmarbut.mfa.TOTP.java
private byte[] getHmac(int timestamp, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException { SecretKeySpec key_spec = new SecretKeySpec(key, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(key_spec); byte[] bin_timestamp = ByteBuffer.allocate(4).putInt(timestamp).array(); ByteBuffer bbuff = ByteBuffer.allocate(8); bbuff.putInt(0); //Left pad 4 bytes to make a 64 bit int bbuff.putInt(timestamp);//from ww w . j a va 2s. co m return mac.doFinal(bbuff.array()); }