Example usage for javax.crypto Mac doFinal

List of usage examples for javax.crypto Mac doFinal

Introduction

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

Prototype

public final byte[] doFinal(byte[] input) throws IllegalStateException 

Source Link

Document

Processes the given array of bytes and finishes the MAC operation.

Usage

From source file:com.predic8.membrane.core.interceptor.authentication.session.totp.OtpProvider.java

static Signer getSigningOracle(String secret) {
    try {// www.ja  va  2  s . c  o m
        byte[] keyBytes = decodeKey(secret);
        final Mac mac = Mac.getInstance("HMACSHA1");
        mac.init(new SecretKeySpec(keyBytes, ""));

        // Create a signer object out of the standard Java MAC
        // implementation.
        return new Signer() {
            @Override
            public byte[] sign(byte[] data) {
                return mac.doFinal(data);
            }
        };
    } catch (NoSuchAlgorithmException error) {
        log.error("", error);
    } catch (InvalidKeyException error) {
        log.error("", error);
    }

    return null;
}

From source file:com.alibaba.openapi.client.util.SignatureUtil.java

public static byte[] hmacSha1(byte[] data, SecretKeySpec signingKey) {
    Mac mac = null;
    try {// ww w .  j av  a  2  s. c  o  m
        mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    return mac.doFinal(data);
}

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

private static byte[] sign(String s, byte[] key) throws RequestSigningException {
    try {/*from ww  w . jav a2  s.c om*/
        SecretKeySpec signingKey = new SecretKeySpec(key, SIGNING_ALGORITHM);
        Mac mac = Mac.getInstance(SIGNING_ALGORITHM);
        mac.init(signingKey);

        byte[] valueBytes = s.getBytes(StandardCharsets.UTF_8);
        return mac.doFinal(valueBytes);
    } catch (NoSuchAlgorithmException e) {
        throw new RequestSigningException(
                "Failed to sign: your JDK does not recognize signing algorithm <" + SIGNING_ALGORITHM + ">", e);
    } catch (InvalidKeyException e) {
        throw new RequestSigningException("Failed to sign: invalid key", e);
    }
}

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;/*w w  w  .j  av  a 2s  . com*/
    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.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Base64 decodes a given string/*from  www. j a  v  a2  s  . c o  m*/
 *
 * @param variance - The allowed differences in OTP values
 * @param algorithm - The algorithm to encrypt the data with
 * @param instance - The security instance to utilize
 * @param secret - The OTP secret
 * @param code - The OTP code
 * @return <code>true</code> if successful, <code>false</code> otherwise
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final boolean validateOtpValue(final int variance, final String algorithm, final String instance,
        final String secret, final int code) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#validateOtpValue(final int variance, final String algorithm, final String instance, final String secret, final int code) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", variance);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", instance);
        DEBUGGER.debug("Value: {}", secret);
        DEBUGGER.debug("Value: {}", code);
    }

    long truncatedHash = 0;
    byte[] data = new byte[8];
    long timeIndex = System.currentTimeMillis() / 1000 / 30;

    final Base32 codec = new Base32();
    final byte[] decoded = codec.decode(secret);
    SecretKeySpec signKey = new SecretKeySpec(decoded, algorithm);

    if (DEBUG) {
        DEBUGGER.debug("long: {}", timeIndex);
    }

    try {
        for (int i = 8; i-- > 0; timeIndex >>>= 8) {
            data[i] = (byte) timeIndex;
        }

        Mac mac = Mac.getInstance(instance);
        mac.init(signKey);
        byte[] hash = mac.doFinal(data);
        int offset = hash[20 - 1] & 0xF;

        for (int i = 0; i < 4; i++) {
            truncatedHash <<= 8;
            truncatedHash |= (hash[offset + i] & 0xFF);
        }

        truncatedHash &= 0x7FFFFFFF;
        truncatedHash %= 1000000;

        if (DEBUG) {
            DEBUGGER.debug("truncatedHash: {}", truncatedHash);
        }

        return (truncatedHash == code);
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    }
}

From source file:com.siphyc.utils.Utilities.java

public static String getHMACSHA256(String secret, String message) {
    try {/*from  w w w  .  j a v  a2 s.  c om*/
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
        return hash;
    } catch (Exception e) {
        System.out.println("Error");
    }
    return null;
}

From source file:org.jenkinsci.plugins.gogs.GogsWebHook.java

/**
 * encode sha256 hmac//ww  w .j a v  a 2 s.  c om
 *
 * @param data data to hex
 * @param key key of HmacSHA256
 */
public static String encode(String data, String key) throws Exception {
    final Charset asciiCs = Charset.forName("UTF-8");
    final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(asciiCs.encode(key).array(),
            "HmacSHA256");
    sha256_HMAC.init(secret_key);
    return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes("UTF-8")));
}

From source file:com.zimbra.cs.service.account.GetAccountInfo.java

static void addUrls(Element response, Account account) throws ServiceException {
    Provisioning prov = Provisioning.getInstance();

    Server server = prov.getServer(account);
    String hostname = server.getAttr(Provisioning.A_zimbraServiceHostname);
    Domain domain = prov.getDomain(account);
    if (server != null && hostname != null) {
        String httpSoap = URLUtil.getSoapPublicURL(server, domain, false);
        String httpsSoap = URLUtil.getSoapPublicURL(server, domain, true);

        if (httpSoap != null) {
            response.addAttribute(AccountConstants.E_SOAP_URL /* soapURL */, httpSoap,
                    Element.Disposition.CONTENT);
        }/*w  w w .ja  v a  2 s. c o m*/
        if (httpsSoap != null && !httpsSoap.equalsIgnoreCase(httpSoap)) {
            /* Note: addAttribute with Element.Disposition.CONTENT REPLACEs any previous attribute with the same name.
             * i.e. Will NOT end up with both httpSoap and httpsSoap as values for "soapURL"
             */
            response.addAttribute(AccountConstants.E_SOAP_URL /* soapURL */, httpsSoap,
                    Element.Disposition.CONTENT);
        }
        String pubUrl = URLUtil.getPublicURLForDomain(server, domain, "", true);
        if (pubUrl != null) {
            response.addAttribute(AccountConstants.E_PUBLIC_URL, pubUrl, Element.Disposition.CONTENT);
        }
        if (AccessManager.getInstance().isAdequateAdminAccount(account)) {
            String publicAdminUrl = URLUtil.getPublicAdminConsoleURLForDomain(server, domain);
            if (publicAdminUrl != null) {
                response.addAttribute(AccountConstants.E_ADMIN_URL, publicAdminUrl,
                        Element.Disposition.CONTENT);
            }
        }
        String changePasswordUrl = null;
        if (domain != null) {
            changePasswordUrl = domain.getAttr(Provisioning.A_zimbraChangePasswordURL);
        }
        if (changePasswordUrl != null) {
            response.addAttribute(AccountConstants.E_CHANGE_PASSWORD_URL, changePasswordUrl,
                    Element.Disposition.CONTENT);
        }
    }
    //add a Community redirect URL
    if (account.getBooleanAttr(Provisioning.A_zimbraFeatureSocialExternalEnabled, false)) {
        String clientID = account.getAttr(Provisioning.A_zimbraCommunityAPIClientID);
        if (clientID == null) {
            ZimbraLog.account.debug(
                    "Zimbra Community client ID is not properly configured. zimbraCommunityAPIClientID cannot be empty.");
        }
        String clientSecret = account.getAttr(Provisioning.A_zimbraCommunityAPIClientSecret);
        if (clientSecret == null) {
            ZimbraLog.account.debug(
                    "Zimbra Community client secret is not properly configured. zimbraCommunityAPIClientSecret cannot be empty.");
        }
        String nameAttribute = account.getAttr(Provisioning.A_zimbraCommunityUsernameMapping);
        if (nameAttribute == null) {
            ZimbraLog.account.debug(
                    "Zimbra Community name mapping is not properly configured. zimbraCommunityUsernameMapping cannot be empty");
        }
        String socialBaseURL = account.getAttr(Provisioning.A_zimbraCommunityBaseURL);
        if (socialBaseURL == null) {
            ZimbraLog.account.debug(
                    "Zimbra Community base URL is not properly configured. zimbraCommunityBaseURL cannot be empty");
        } else {
            if (socialBaseURL.endsWith("/")) { //avoid double slashes
                socialBaseURL = socialBaseURL.substring(0, socialBaseURL.length() - 1);
            }
        }
        String socialTabURL = account.getAttr(Provisioning.A_zimbraCommunityHomeURL);
        if (socialTabURL == null) {
            ZimbraLog.account.debug(
                    "Zimbra Community home URL is not properly configured. zimbraCommunityHomeURL cannot be empty");
        } else {
            if (!socialTabURL.startsWith("/")) { //make sure the path is relative
                socialTabURL = "/".concat(socialTabURL);
            }
        }
        if (clientID != null && clientSecret != null && nameAttribute != null && socialBaseURL != null
                && socialTabURL != null) {
            try {
                Date today = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
                Mac mac = Mac.getInstance("HmacSHA256");
                SecretKeySpec key = new SecretKeySpec(clientSecret.getBytes("UTF8"), "HmacSHA256");
                mac.init(key);
                byte[] rawHmac = mac.doFinal(String.format("%s%s%s%s", account.getUid(),
                        formatter.format(today), socialBaseURL, socialTabURL).getBytes("UTF8"));
                String Base64Signature = Base64.encodeBase64String(rawHmac);

                String szURL = String.format(
                        "%s/api.ashx/v2/oauth/redirect?client_id=%s&username=%s&time_stamp=%s&redirect_uri=%s&signature=%s",
                        socialBaseURL, URLEncoder.encode(clientID, "UTF8"), account.getAttr(nameAttribute),
                        URLEncoder.encode(formatter.format(today), "UTF8"),
                        URLEncoder.encode(socialBaseURL.concat(socialTabURL), "UTF8"),
                        URLEncoder.encode(Base64Signature, "UTF8"));
                response.addAttribute(AccountConstants.E_COMMUNITY_URL, szURL, Element.Disposition.CONTENT);
            } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) {
                throw ServiceException.FAILURE("Failed to generate community URL", e);
            }
        }
    }

    //add BOSH URL if Chat is enabled
    if (account.getBooleanAttr(Provisioning.A_zimbraFeatureChatEnabled, false)) {
        response.addAttribute(AccountConstants.E_BOSH_URL, server.getReverseProxyXmppBoshLocalHttpBindURL());
    }
}

From source file:com.ironchain.common.kits.DigestKit.java

/**
 * HMAC-SHA1???, ,20.//from  ww  w.  j  a  v  a  2  s  .c o  m
 * 
 * @param input
 *            
 * @param key
 *            HMAC-SHA1
 */
public static byte[] hmacSha1(byte[] input, byte[] key) {
    try {
        SecretKey secretKey = new SecretKeySpec(key, HMACSHA1);
        Mac mac = Mac.getInstance(HMACSHA1);
        mac.init(secretKey);
        return mac.doFinal(input);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.artifactory.security.crypto.CryptoHelper.java

public static String generateUniqueApiKey() throws GeneralSecurityException {
    byte[] hmacData;

    try {/* w  w  w  .  ja v a2  s.c  o  m*/
        SecretKeySpec secretKey = new SecretKeySpec("secretKey".getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKey);
        String data = UUID.randomUUID().toString();
        hmacData = mac.doFinal(data.getBytes("UTF-8"));
        return new Base64Encoder().encode(hmacData);
    } catch (UnsupportedEncodingException e) {
        throw new GeneralSecurityException(e);
    }
}