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:com.stackmob.sdk.api.StackMobSession.java

public String generateMacToken(String method, String uri, String host, String port) {

    String ts = String.valueOf(new Date().getTime() / 1000);
    String nonce = String.format("n%d", Math.round(Math.random() * 10000));
    try {//w  w  w .  j  av  a  2s. com
        String baseString = getNormalizedRequestString(ts, nonce, method, uri, host, port);
        Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM);
        SecretKeySpec spec = new SecretKeySpec(oauth2MacKey.getBytes(), SIGNATURE_ALGORITHM);
        try {
            mac.init(spec);
        } catch (InvalidKeyException ike) {
            throw new IllegalStateException(ike);
        }
        byte[] rawMacBytes = mac.doFinal(baseString.getBytes());
        byte[] b64Bytes = Base64.encodeBase64(rawMacBytes);
        String calculatedMac = new String(b64Bytes);
        return String.format("MAC id=\"%s\",ts=\"%s\",nonce=\"%s\",mac=\"%s\"", oauth2Token, ts, nonce,
                calculatedMac);

    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("This device doesn't have SHA1");
    }
}

From source file:com.annuletconsulting.homecommand.server.HomeCommand.java

private static String getSignature(String timeStamp) {
    if (sharedKey != null)
        try {/*from w w  w. j  a v a2 s. c o m*/
            byte[] data = timeStamp.getBytes(ENCODING_FORMAT);
            Mac mac = Mac.getInstance(SIGNATURE_METHOD);
            mac.init(new SecretKeySpec(sharedKey.getBytes(ENCODING_FORMAT), SIGNATURE_METHOD));
            char[] signature = Hex.encodeHex(mac.doFinal(data));
            return new String(signature);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    return "Error in getSignature()";
}

From source file:fi.okm.mpass.shibboleth.authn.impl.ValidateWilmaResponse.java

/** {@inheritDoc} */
@Override//from   ww w.  jav a2s  . co  m
protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext,
        @Nonnull final AuthenticationContext authenticationContext) {
    final HttpServletRequest servletRequest = getHttpServletRequest();
    final WilmaAuthenticationContext wilmaContext = authenticationContext
            .getSubcontext(WilmaAuthenticationContext.class, false);
    final String nonce = wilmaContext.getNonce();
    if (!getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_NONCE).equals(nonce)) {
        log.warn("{}: Invalid nonce in the incoming Wilma response!", getLogPrefix());
        log.debug("{} vs {}", nonce,
                getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_NONCE));
        handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS,
                AuthnEventIds.NO_CREDENTIALS);
        return;
    }
    final String checksum = getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_CHECKSUM);
    final String query = servletRequest.getQueryString().substring(0, servletRequest.getQueryString()
            .indexOf("&" + WilmaAuthenticationContext.PARAM_NAME_CHECKSUM + "="));
    final String url = servletRequest.getRequestURL().append("?").append(query).toString();
    try {
        final Mac mac = Mac.getInstance(algorithm);
        mac.init(macKey);
        byte[] digest = mac.doFinal(url.getBytes("UTF-8"));
        if (!Arrays.equals(DatatypeConverter.parseHexBinary(checksum), digest)) {
            log.warn("{}: The checksum validation failed for user {}", getLogPrefix(),
                    getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_USER_ID));
            log.trace("{} (params) vs {}", checksum, new String(Hex.encodeHex(digest)));
            handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS,
                    AuthnEventIds.NO_CREDENTIALS);
            return;
        }
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException
            | UnsupportedEncodingException | IllegalArgumentException e) {
        log.error("{}: Could not verify the checksum {}", getLogPrefix(), checksum, e);
        handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS,
                AuthnEventIds.NO_CREDENTIALS);
        return;
    }
    log.trace("{}: Building authentication result for user {}", getLogPrefix(),
            getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_USER_ID));
    buildAuthenticationResult(profileRequestContext, authenticationContext);
}

From source file:org.hk.jt.client.core.Request.java

private String getSignature()
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    String keyString = String.format(SIGN_FORMAT, config.getConsumerSercret(), config.getAccessTokenSercret());
    String signatureBaseString = getSignatureBaseString();
    Mac mac = Mac.getInstance(this.config.getAlgolithm());
    Key key = new SecretKeySpec(keyString.getBytes(), this.config.getAlgolithm());
    mac.init(key);//w  ww . jav a 2  s .c  o  m
    byte[] digest = mac.doFinal(signatureBaseString.getBytes());
    return encodeURL(Base64.encodeBytes(digest));
}

From source file:com.example.android.vault.VaultProvider.java

/**
 * Load our symmetric secret key and use it to derive two different data and
 * MAC keys. The symmetric secret key is stored securely on disk by wrapping
 * it with a public/private key pair, possibly backed by hardware.
 *//*from   w  w  w.j  a v a 2 s  .co  m*/
private void loadOrGenerateKeys(Context context, File keyFile) throws GeneralSecurityException, IOException {
    final SecretKeyWrapper wrapper = new SecretKeyWrapper(context, TAG);

    // Generate secret key if none exists
    if (!keyFile.exists()) {
        final byte[] raw = new byte[DATA_KEY_LENGTH];
        new SecureRandom().nextBytes(raw);

        final SecretKey key = new SecretKeySpec(raw, "AES");
        final byte[] wrapped = wrapper.wrap(key);

        writeFully(keyFile, wrapped);
    }

    // Even if we just generated the key, always read it back to ensure we
    // can read it successfully.
    final byte[] wrapped = readFully(keyFile);
    final SecretKey key = wrapper.unwrap(wrapped);

    final Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(key);

    // Derive two different keys for encryption and authentication.
    final byte[] rawDataKey = new byte[DATA_KEY_LENGTH];
    final byte[] rawMacKey = new byte[MAC_KEY_LENGTH];

    System.arraycopy(mac.doFinal(BLOB_DATA), 0, rawDataKey, 0, rawDataKey.length);
    System.arraycopy(mac.doFinal(BLOB_MAC), 0, rawMacKey, 0, rawMacKey.length);

    mDataKey = new SecretKeySpec(rawDataKey, "AES");
    mMacKey = new SecretKeySpec(rawMacKey, "HmacSHA256");
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

@SuppressWarnings("deprecation")
protected UriComponentsBuilder createUrl(Context context) throws PlayHavenException {
    try {/*www.ja  v a 2s.c  o m*/
        SharedPreferences pref = PlayHaven.getPreferences(context);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(getString(pref, APIServer));
        builder.path(context.getResources().getString(getApiPath(context)));
        builder.queryParam("app", getString(pref, AppPkg));
        builder.queryParam("opt_out", getString(pref, OptOut, "0"));
        builder.queryParam("app_version", getString(pref, AppVersion));
        builder.queryParam("os", getInt(pref, OSVersion, 0));
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        builder.queryParam("orientation", display.getRotation());
        builder.queryParam("hardware", getString(pref, DeviceModel));
        PlayHaven.ConnectionType connectionType = getConnectionType(context);
        builder.queryParam("connection", connectionType.ordinal());
        builder.queryParam("idiom",
                context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK);

        /**
         * For height/width we will use getSize(Point) not getRealSize(Point) as this will allow us to automatically
         * account for rotation and screen decorations like the status bar. We only want to know available space.
         *
         * @playhaven.apihack for SDK_INT < 13, have to use getHeight and getWidth!
         */
        Point size = new Point();
        if (Build.VERSION.SDK_INT >= 13) {
            display.getSize(size);
        } else {
            size.x = display.getWidth();
            size.y = display.getHeight();
        }
        builder.queryParam("width", size.x);
        builder.queryParam("height", size.y);

        /**
         * SDK Version needs to be reported as a dotted numeric value
         * So, if it is a -SNAPSHOT build, we will replace -SNAPSHOT with the date of the build
         * IE: 2.0.0.20130201
         * as opposed to an actual released build, which would be like 2.0.0
         */
        String sdkVersion = getString(pref, SDKVersion);
        String[] date = Version.PLUGIN_BUILD_TIME.split("[\\s]");
        sdkVersion = sdkVersion.replace("-SNAPSHOT", "." + date[0].replaceAll("-", ""));
        builder.queryParam("sdk_version", sdkVersion);

        builder.queryParam("plugin", getString(pref, PluginIdentifer));

        Locale locale = context.getResources().getConfiguration().locale;
        builder.queryParam("languages", String.format("%s,%s", locale.toString(), locale.getLanguage()));
        builder.queryParam("token", getString(pref, Token));

        builder.queryParam("device", getString(pref, DeviceId));
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        builder.queryParam("dpi", metrics.densityDpi);

        String uuid = UUID.randomUUID().toString();
        String nonce = base64Digest(uuid);
        builder.queryParam("nonce", nonce);

        ktsid = KontagentUtil.getSenderId(context);
        if (ktsid != null)
            builder.queryParam("sid", ktsid);

        addSignature(builder, pref, nonce);

        // Setup for signature verification
        String secret = getString(pref, Secret);
        SecretKeySpec key = new SecretKeySpec(secret.getBytes(UTF8), HMAC);
        sigMac = Mac.getInstance(HMAC);
        sigMac.init(key);
        sigMac.update(nonce.getBytes(UTF8));

        return builder;
    } catch (Exception e) {
        throw new PlayHavenException(e);
    }
}

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;/* ww  w. j av  a  2 s.c om*/

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

        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:ch.cyberduck.core.openstack.SwiftUrlProvider.java

protected String sign(final String secret, final String body) {
    try {//from   w w w. j a  va2s .com
        // Acquire an HMAC/SHA1 from the raw key bytes.
        final SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(Charset.forName("UTF-8")),
                Constants.HMAC_SHA1_ALGORITHM);
        // Acquire the MAC instance and initialize with the signing key.
        final Mac mac = Mac.getInstance(Constants.HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
        return Hex.encodeHexString(mac.doFinal(body.getBytes(Charset.forName("UTF-8"))));
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        log.error(String.format("Error signing %s %s", body, e.getMessage()));
        return null;
    }
}

From source file:com.baidubce.auth.BceV1Signer.java

private String sha256Hex(String signingKey, String stringToSign) {
    try {/*from   www  .  j a v  a 2 s.  c o  m*/
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(signingKey.getBytes(UTF8), "HmacSHA256"));
        return new String(Hex.encodeHex(mac.doFinal(stringToSign.getBytes(UTF8))));
    } catch (Exception e) {
        throw new BceClientException("Fail to generate the signature", e);
    }
}

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;//from w w w  .  j a v  a  2s .  co  m

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

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