Example usage for javax.crypto Mac getInstance

List of usage examples for javax.crypto Mac getInstance

Introduction

In this page you can find the example usage for javax.crypto Mac getInstance.

Prototype

public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Mac object that implements the specified MAC algorithm.

Usage

From source file:ch.threema.apitool.CryptTool.java

/**
 * Hashes a phone number for identity lookup.
 *
 * @param phoneNo the phone number//from  w ww.ja va2s .  co m
 * @return the raw hash
 */
public static byte[] hashPhoneNo(String phoneNo) {
    try {
        Mac phoneMac = Mac.getInstance("HmacSHA256");
        phoneMac.init(new SecretKeySpec(PHONENO_HMAC_KEY, "HmacSHA256"));
        String normalizedPhoneNo = phoneNo.replaceAll("[^0-9]", "");
        return phoneMac.doFinal(normalizedPhoneNo.getBytes("US-ASCII"));
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.callimachusproject.behaviours.AuthenticationManagerSupport.java

private String sig(String text) throws OpenRDFException, IOException, GeneralSecurityException {
    String secret = this.getRealm().getOriginSecret();
    SecretKey key = new SecretKeySpec(readBytes(secret), "HmacSHA256");
    Mac m = Mac.getInstance("HmacSHA256");
    m.init(key);//from w  ww.  jav  a 2 s.  c om
    m.update(text.getBytes("UTF-8"));
    return Base64.encodeBase64String(m.doFinal());
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * Get a Mac instance for the key number.
 *
 * @param keyNo the key number./*from w w w .  j  av  a  2  s  . c o m*/
 * @return the mac instance.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 */
private Mac getMac(int keyNo)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    Mac m = Mac.getInstance("HmacSHA256");
    m.init(getKey(keyNo));
    return m;
}

From source file:uk.ac.tgac.bbsrc.miso.external.ajax.ExternalSectionControllerHelperService.java

public static String calculateHMAC(String data, String key) throws java.security.SignatureException {
    String result;/*ww w  .j  a v  a  2  s .c  o  m*/
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());

        // base64-encode the hmac
        result = Base64.encodeBase64URLSafeString(rawHmac);
    } catch (Exception e) {
        log.error("failed to generate HMAC", e);
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}

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//w w  w  .  j  ava  2s.  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:acp.sdk.SecureUtil.java

/**
 * MAC//from   w  w  w  . j a v  a 2  s  .co m
 * 
 * @param inputByte
 *            ?
 * @param inputkey
 *            
 * @return MAC
 * @throws Exception
 */
public String genmac(byte[] inputByte, byte[] inputkey) throws Exception {
    try {
        Mac mac = Mac.getInstance("HmacMD5");
        SecretKey key = new SecretKeySpec(inputkey, "DES");
        mac.init(key);

        byte[] macCode = mac.doFinal(inputByte);
        String strMac = this.byte2hex(macCode);
        return strMac;
    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    }
}

From source file:com.akamai.edgegrid.auth.EdgeGridV1Signer.java

/**
 * Helper method to calculate the HMAC signature of a given string.
 * /*www  .  j a  v a  2 s .  c  om*/
 * @param s the string to sign.
 * @param key the key for the signature.
 * @param algorithm the signing algorithm.
 * @return the HMac signature.
 * @throws RequestSigningException
 */
private static byte[] sign(String s, byte[] key, String algorithm) throws RequestSigningException {
    try {
        SecretKeySpec signingKey = new SecretKeySpec(key, algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(signingKey);

        byte[] valueBytes = s.getBytes(CHARSET);
        return mac.doFinal(valueBytes);
    } catch (NoSuchAlgorithmException nsae) {
        throw new RequestSigningException("Failed to sign: algorithm not found", nsae);
    } catch (InvalidKeyException ike) {
        throw new RequestSigningException("Failed to sign: invalid key", ike);
    } catch (UnsupportedEncodingException uee) {
        throw new RequestSigningException("Failed to sign: invalid string encoding", uee);
    }
}

From source file:net.mms_projects.copy_it.api.oauth.HeaderVerifier.java

/**
 * Validate the signature for the request, make sure you've called all verify* methods first
 * @param postRequestDecoder The post parameters for the request, pass null if it's a GET request instead
 * @param https Should we use https to generate our signature?
 * @throws OAuthException Thrown if the signature is invalid
 *//*from   w  w w.j  av a2s.  co  m*/
public void checkSignature(HttpPostRequestDecoder postRequestDecoder, boolean https)
        throws UnsupportedEncodingException, URISyntaxException, OAuthException {
    final String signed_with = oauth_params.get(OAuthParameters.OAUTH_SIGNATURE);
    final String raw = createRaw(postRequestDecoder, https);
    final String secretkey = consumer.getSecretKey() + "&" + user.getSecretKey();
    try {
        final Key signingKey = new SecretKeySpec(secretkey.getBytes(), HMAC_SHA1);
        final Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(raw.getBytes());
        final String signature = new String(Base64.encodeBase64(rawHmac));
        System.err.println("Signed with: " + URLDecoder.decode(signed_with, UTF_8));
        System.err.println("Should be::: " + signature);
        if (!URLDecoder.decode(signed_with, UTF_8).equals(signature))
            throw new OAuthException(ErrorMessages.INVALID_SIGNATURE);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
}

From source file:com.cloud.bridge.util.RestAuth.java

/**
 * Create a signature by the following method:
 *     new String( Base64( SHA1( key, byte array )))
 * /*from   w w w .  jav a  2s . c  o  m*/
 * @param signIt    - the data to generate a keyed HMAC over
 * @param secretKey - the user's unique key for the HMAC operation
 * @return String   - the recalculated string
 * @throws SignatureException
 */
private String calculateRFC2104HMAC(String signIt, String secretKey) throws SignatureException {
    String result = null;
    try {
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac hmacSha1 = Mac.getInstance("HmacSHA1");
        hmacSha1.init(key);
        byte[] rawHmac = hmacSha1.doFinal(signIt.getBytes());
        result = new String(Base64.encodeBase64(rawHmac));
    } catch (InvalidKeyException e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request because key " + secretKey
                + " is invalid" + e.getMessage());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage());
    }
    return result.trim();
}

From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java

public static byte[] decrypt(byte[] secure, ExternalContext ctx) {
    if (ctx == null)
        throw new NullPointerException("ExternalContext ctx");

    testConfiguration(ctx);/*w w w . j a v  a 2s  .  c o  m*/

    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);
    }
}