Example usage for javax.crypto Mac init

List of usage examples for javax.crypto Mac init

Introduction

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

Prototype

public final void init(Key key) throws InvalidKeyException 

Source Link

Document

Initializes this Mac object with the given key.

Usage

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

protected static PKIMessage protectPKIMessage(PKIMessage msg, boolean badObjectId, String password,
        String keyId, int iterations)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    // Create the PasswordBased protection of the message
    PKIHeaderBuilder head = CmpMessageHelper.getHeaderBuilder(msg.getHeader());
    if (keyId != null) {
        head.setSenderKID(new DEROctetString(keyId.getBytes()));
    }/*  w w w  .ja va2  s .  c  om*/
    // SHA1
    AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26"));
    // 567 iterations
    int iterationCount = iterations;
    ASN1Integer iteration = new ASN1Integer(iterationCount);
    // HMAC/SHA1
    AlgorithmIdentifier macAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.113549.2.7"));
    byte[] salt = "foo123".getBytes();
    DEROctetString derSalt = new DEROctetString(salt);

    // Create the new protected return message
    String objectId = "1.2.840.113533.7.66.13";
    if (badObjectId) {
        objectId += ".7";
    }
    PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg);
    AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp);
    head.setProtectionAlg(pAlg);
    PKIHeader header = head.build();
    // Calculate the protection bits
    byte[] raSecret = password.getBytes();
    byte[] basekey = new byte[raSecret.length + salt.length];
    System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
    for (int i = 0; i < salt.length; i++) {
        basekey[raSecret.length + i] = salt[i];
    }
    // Construct the base key according to rfc4210, section 5.1.3.1
    MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC");
    for (int i = 0; i < iterationCount; i++) {
        basekey = dig.digest(basekey);
        dig.reset();
    }
    // For HMAC/SHA1 there is another oid, that is not known in BC, but the
    // result is the same so...
    String macOid = macAlg.getAlgorithm().getId();
    PKIBody body = msg.getBody();
    byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(header, body);
    Mac mac = Mac.getInstance(macOid, "BC");
    SecretKey key = new SecretKeySpec(basekey, macOid);
    mac.init(key);
    mac.reset();
    mac.update(protectedBytes, 0, protectedBytes.length);
    byte[] out = mac.doFinal();
    DERBitString bs = new DERBitString(out);

    return new PKIMessage(header, body, bs);
}

From source file:nl.esciencecenter.octopus.webservice.mac.MacScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data/*from w  ww  .j  a v a2  s .c  o  m*/
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @param algorithm
 *            MAC algorithm implemented by javax.crypto.MAC
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AuthenticationException
 *             when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException {
    try {
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec macKey = new SecretKeySpec(key.getBytes(), "RAW");
        mac.init(macKey);
        byte[] signature = mac.doFinal(data.getBytes());
        return Base64.encodeBase64String(signature);
    } catch (InvalidKeyException e) {
        throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AuthenticationException("Algorithm is not supported", e);
    }
}

From source file:com.auditmark.jscrambler.client.JScrambler.java

private String generateHMACSignature(String requestMethod, String resourcePath, Map<String, String> params)
        throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
    String data = hmacSignatureData(requestMethod, resourcePath, apiHost, params);
    try {//from  w ww .  j  a v a 2  s. c o  m
        SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);
        byte[] digest = mac.doFinal(data.getBytes());
        return new sun.misc.BASE64Encoder().encode(digest);

    } catch (InvalidKeyException e) {
        System.err.println("Invalid key: " + e.getMessage());
        throw e;
    } catch (NoSuchAlgorithmException e) {
        System.err.println("No such algorithm: " + e.getMessage());
        throw e;
    }
}

From source file:org.androdyne.StacktraceUploader.java

/**
 * Given the NameValuePairs forming a stacktrace submission request, creates a
 * signature over the parameters that the API should recognize.
 **///  w ww  .  ja  v  a  2  s  . c  o m
private String createSignature(List<NameValuePair> params) {
    // First, sort the parameter keys. That'll help later.
    List<String> sortedKeys = new LinkedList<String>();
    for (NameValuePair pair : params) {
        sortedKeys.add(pair.getName());
    }
    Collections.sort(sortedKeys, String.CASE_INSENSITIVE_ORDER);

    // Create signature.
    Mac hmac = null;
    try {
        hmac = Mac.getInstance("HmacSHA1");
        hmac.init(new SecretKeySpec(mAPISecret.getBytes(), "HmacSHA1"));
    } catch (NoSuchAlgorithmException ex) {
        android.util.Log.e(LTAG, "No HmacSHA1 available on this phone.");
        return null;
    } catch (InvalidKeyException ex) {
        android.util.Log.e(LTAG, "Invalid secret; shouldn't be possible.");
        return null;
    }

    final int size = sortedKeys.size();
    for (int i = 0; i < size; ++i) {
        String key = sortedKeys.get(i);

        for (NameValuePair pair : params) {
            if (!key.equals(pair.getName())) {
                continue;
            }

            // This pair is next!
            try {
                hmac.update(String.format("%s=%s", key, URLEncoder.encode(pair.getValue(), "utf8")).getBytes());
            } catch (java.io.UnsupportedEncodingException ex) {
                android.util.Log.e(LTAG, "URLEncoder reports 'utf8' is an unsupported encoding...");
                return null;
            }
            if (i < size - 1) {
                hmac.update("&".getBytes());
            }
        }
    }

    String signature = new BigInteger(1, hmac.doFinal()).toString(16);
    // android.util.Log.d(LTAG, "signature: " + signature);
    return signature;
}

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);
    byte[] digest = mac.doFinal(signatureBaseString.getBytes());
    return encodeURL(Base64.encodeBytes(digest));
}

From source file:com.restswitch.controlpanel.MainActivity.java

private void sendDevice(String devid, String host, String msg, String pwdHash) {
    try {/* w w w  .  j  a v  a 2s.c  om*/
        final long utcStart = System.currentTimeMillis();
        String b32UntilUtc = B32Coder.encodeDatetimeNow(8000); // valid for 8 sec
        String method = "PUT";
        String uri = ("/pub/" + devid);
        String val = (method + uri + msg + b32UntilUtc);

        String b64Hash = null;
        try {
            Mac hmacSha256 = Mac.getInstance("HmacSHA256");
            hmacSha256.init(new javax.crypto.spec.SecretKeySpec(pwdHash.getBytes("utf-8"), "HmacSHA256"));
            byte[] hash = hmacSha256.doFinal(val.getBytes("UTF-8"));
            b64Hash = Base64.encodeToString(hash, Base64.URL_SAFE | Base64.NO_PADDING | Base64.NO_WRAP);
        } catch (Exception ex) {
            alertError("Invalid password, verify app settings.");
            return;
        }

        Properties headers = new Properties();
        headers.setProperty("x-body", msg);
        headers.setProperty("x-auth1", b32UntilUtc);
        headers.setProperty("x-auth2", b64Hash);

        AjaxTask ajaxTask = new AjaxTask();
        ajaxTask.putAjaxEventHandler(this);
        //            // use to set a custom ca
        //            boolean rc = ajaxTask.putRootCaCert(rootCa, true);
        //            if(!rc) {
        //                alertError("Failed to initialize network task.");
        //                return;
        //            }
        AjaxTask.Data data = new AjaxTask.Data();
        data.param1 = devid;
        data.param2 = utcStart;
        ajaxTask.invoke("http", host, uri, method, headers, msg, data);
    } catch (Exception ex) {
        alertError(ex.getMessage());
    }
}

From source file:nl.esciencecenter.osmium.mac.MacScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data//from  ww  w .j a v  a  2s . co m
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @param algorithm
 *            MAC algorithm implemented by javax.crypto.MAC
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AuthenticationException
 *             when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException {
    try {
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec macKey = new SecretKeySpec(key.getBytes(StandardCharsets.US_ASCII), "RAW");
        mac.init(macKey);
        byte[] signature = mac.doFinal(data.getBytes(StandardCharsets.US_ASCII));
        return Base64.encodeBase64String(signature);
    } catch (InvalidKeyException e) {
        throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AuthenticationException("Algorithm is not supported", e);
    }
}

From source file:com.francetelecom.admindm.com.UDPConnectionRequest.java

/**
 * <p>//w  w w .ja  v  a2  s .  c om
 * Authenticate the UDPConnectionRequest.
 * </p>
 * <p>
 * The following actions are performed:
 * <ul>
 * <li>check if the RequestURI SIG attribute is equal to the computed
 * signature.</li>
 * </ul>
 * </p>
 * 
 * @return true if authentication phase succeed else false.
 */
private boolean authenticate() {
    Log.debug("enter authenticate");

    try {
        Parameter connectionRequestPasswordParameter = parameterData
                .createOrRetrieveParameter(parameterData.getRoot() + CONNECTION_REQUEST_PASSWORD);
        String password = (String) connectionRequestPasswordParameter.getValue();
        Log.debug("password = " + password);
        // create a secret key
        SecretKeySpec signinKey = new SecretKeySpec(password.getBytes(), HMAC_SHA1_ALGORITHM);
        // get a Mac instance
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signinKey);
        // compute value
        String text = requestURI.getAttribute(RequestURIParser.TS)
                + requestURI.getAttribute(RequestURIParser.ID) + requestURI.getAttribute(RequestURIParser.UN)
                + requestURI.getAttribute(RequestURIParser.CN);
        Log.debug("text = " + text);
        // computed signature (ensure lower case character)
        byte[] signature = mac.doFinal(text.getBytes());
        String computedSignature = new String(Hex.encodeHex(signature)).toLowerCase();
        Log.debug("computed signature = " + computedSignature);
        // get the signature from the message
        String receivedSignature = requestURI.getAttribute(RequestURIParser.SIG);
        // ensure lower case
        receivedSignature = receivedSignature.toLowerCase();
        if (receivedSignature == null) {
            Log.error("signature key null");
            return false;
        } else {
            if (!receivedSignature.equals(computedSignature)) {
                Log.error("invalid signature");
                return false;
            }
        }
    } catch (Fault e) {
        Log.error("unable to get the " + "IGD.ManagementServer.ConnectionRequestPassword");
        return false;
    } catch (NoSuchAlgorithmException e) {
        Log.error("Unable to get the HMAC-SHA1 algo");
        return false;
    } catch (InvalidKeyException e) {
        Log.error("Unable to sign the key");
        return false;
    }
    Log.info("UDP Connection Request authenticated");
    return true;
}

From source file:org.killbill.billing.plugin.payeezy.client.PayeezyClientWrapper.java

private String getMacValue(final String nonce, final String timeStamp, @Nullable final String payload)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    final Mac mac = Mac.getInstance(HMAC_SHA_256);
    final Key secretKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA_256);
    mac.init(secretKey);

    final StringBuilder buff = new StringBuilder();
    buff.append(apiKey).append(nonce).append(timeStamp);
    if (token != null) {
        buff.append(token);//from ww  w . ja  v a2 s .c o  m
    }
    if (payload != null) {
        buff.append(payload);
    }

    final String bufferData = buff.toString();
    final byte[] macHash = mac.doFinal(bufferData.getBytes("UTF-8"));
    return new String(Base64.encodeBase64(toHex(macHash)));
}