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() throws IllegalStateException 

Source Link

Document

Finishes the MAC operation.

Usage

From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java

private String getHMAC256(final String input, final String secret) {
    String temp = null;/*  w  ww  .  j a va  2  s .  com*/
    final SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(keySpec);
        // update method adds the given byte to the Mac's input data. 
        mac.update(input.getBytes());
        final byte[] m = mac.doFinal();
        // The base64-encoder in Commons Codec
        temp = base64Encode(m);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return temp;
}

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

public boolean verify(String raAuthenticationSecret)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    lastUsedRaSecret = raAuthenticationSecret;
    boolean ret = false;
    // Verify the PasswordBased protection of the message
    if (!pAlg.getAlgorithm().equals(CMPObjectIdentifiers.passwordBasedMac)) {
        errMsg = INTRES.getLocalizedMessage("cmp.errorunknownprotalg", pAlg.getAlgorithm().getId());
        LOG.error(errMsg);/* www  .ja v  a 2  s .  c o  m*/
        return ret;
    } else {
        if (iterationCount > 10000) {
            LOG.info("Received message with too many iterations in PBE protection: " + iterationCount);
            throw new InvalidKeyException("Iteration count can not exceed 10000");
        }
        byte[] raSecret = raAuthenticationSecret.getBytes();
        byte[] basekey = new byte[raSecret.length + salt.length];
        System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
        System.arraycopy(salt, 0, basekey, raSecret.length, salt.length);
        // Construct the base key according to rfc4210, section 5.1.3.1
        MessageDigest dig = MessageDigest.getInstance(owfOid, "BC");
        for (int i = 0; i < iterationCount; i++) {
            basekey = dig.digest(basekey);
            dig.reset();
        }
        // HMAC/SHA1 is normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7 
        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();
        // My out should now be the same as the protection bits
        byte[] pb = protection.getBytes();
        ret = Arrays.equals(out, pb);
    }
    return ret;
}

From source file:org.alfresco.encryption.MACUtils.java

public byte[] generateMAC(String keyAlias, MACInput macInput) {
    try {/*from  w w w  .java 2  s. c o  m*/
        InputStream fullMessage = macInput.getMACInput();

        if (logger.isDebugEnabled()) {
            logger.debug("Generating MAC for " + macInput + "...");
        }

        Mac mac = getMac(keyAlias);

        byte[] buf = new byte[1024];
        int len;
        while ((len = fullMessage.read(buf, 0, 1024)) != -1) {
            mac.update(buf, 0, len);
        }
        byte[] newMAC = mac.doFinal();

        if (logger.isDebugEnabled()) {
            logger.debug("...done. MAC is " + Arrays.toString(newMAC));
        }

        return newMAC;
    } catch (Exception e) {
        throw new AlfrescoRuntimeException("Failed to generate MAC", e);
    }
}

From source file:com.skplanet.syruppay.token.tav.TransactionAuthenticationValue.java

public String getChecksumBy(final String key)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException {
    final Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm()));
    mac.update((cardToken + mctTransAuthId + ocTransAuthId
            + new ObjectMapper().writeValueAsString(paymentAuthenticationDetail)).getBytes("UTF-8"));
    return Base64.encodeBase64URLSafeString(mac.doFinal());
}

From source file:com.skplanet.syruppay.token.tav.TransactionAuthenticationValue.java

public boolean isValidBy(final String key, final String checksum)
        throws NoSuchAlgorithmException, IOException, InvalidKeyException {
    final Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm()));
    mac.update((cardToken + mctTransAuthId + ocTransAuthId
            + new ObjectMapper().writeValueAsString(paymentAuthenticationDetail)).getBytes("UTF-8"));
    return Base64.encodeBase64URLSafeString(mac.doFinal()).equals(checksum);
}

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  ww . j  av  a2  s  . c o  m
    // 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:org.janusgraph.graphdb.tinkerpop.gremlin.server.auth.HMACAuthenticator.java

private String generateToken(final String username, final String salt, final String time) {
    try {//from  ww  w  . j a  va 2s.c om
        final CharBuffer secretAndSalt = CharBuffer.allocate(secret.length + salt.length() + 1);
        secretAndSalt.put(secret);
        secretAndSalt.put(":");
        secretAndSalt.put(salt);
        final String tokenPrefix = username + ":" + time.toString() + ":";
        final SecretKeySpec keySpec = new SecretKeySpec(toBytes(secretAndSalt.array()), hmacAlgo);
        final Mac hmac = Mac.getInstance(hmacAlgo);
        hmac.init(keySpec);
        hmac.update(username.getBytes());
        hmac.update(time.toString().getBytes());
        final Base64.Encoder encoder = Base64.getUrlEncoder();
        final byte[] hmacbytes = encoder.encode(hmac.doFinal());
        final byte[] tokenbytes = tokenPrefix.getBytes();
        final byte[] token = ByteBuffer.wrap(new byte[tokenbytes.length + hmacbytes.length]).put(tokenbytes)
                .put(hmacbytes).array();
        return new String(encoder.encode(token));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.sharextras.webscripts.connector.HttpOAuthConnector.java

private String generateSignature(Map<String, String> authParams, Map<String, String> extraParams,
        String httpMethod, String url) {
    Map<String, String> sigParams = new HashMap<String, String>(authParams);
    if (extraParams != null)
        sigParams.putAll(extraParams);//from www .  ja v a2  s . c  om

    String sigMethod = sigParams.get(OAUTH_SIGNATURE_METHOD);

    if (sigMethod.equals(SIGNATURE_METHOD_PLAINTEXT)) {
        if (logger.isDebugEnabled())
            logger.debug("Generating PLAINTEXT signature");
        String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET);
        StringBuffer signatureBuffer = new StringBuffer(getConsumerSecret()).append("&");
        signatureBuffer.append(tokenSecret != null ? tokenSecret : "");
        return signatureBuffer.toString();
    } else if (sigMethod.equals(SIGNATURE_METHOD_HMACSHA1)) {
        if (logger.isDebugEnabled())
            logger.debug("Generating HMAC-SHA1 signature");

        StringBuffer baseStrBuffer = new StringBuffer();

        baseStrBuffer.append(httpMethod).append("&");
        baseStrBuffer.append(encodeParameter(url));
        baseStrBuffer.append("&");

        // Add all request params to the list, combine request and auth params in a single map
        // as per http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
        // TODO Support multiple parameters with same name

        // Sort keys by param name
        // TODO Sort *after* encoding
        List<String> keys = new ArrayList<String>(sigParams.keySet());
        Collections.sort(keys);
        int i = 0;
        for (String key : keys) {
            if (!key.equals(OAUTH_REALM) && !key.equals(OAUTH_SIGNATURE) && !key.equals(OAUTH_TOKEN_SECRET)) {
                if (i > 0)
                    baseStrBuffer.append(encodeParameter("&"));
                baseStrBuffer.append(
                        encodeParameter(encodeParameter(key) + "=" + encodeParameter(sigParams.get(key))));
                i++;
            }
        }

        // Final base string
        String baseString = baseStrBuffer.toString();

        // Key to use for signing
        String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET);
        String key = encodeParameter(getConsumerSecret()) + "&"
                + encodeParameter(tokenSecret != null ? tokenSecret : "");

        if (logger.isDebugEnabled())
            logger.debug("Generating signature with key '" + key + "', base string '" + baseString + "'");

        try {
            SecretKey keyStr = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            Mac m = Mac.getInstance("HmacSHA1");
            m.init(keyStr);
            m.update(baseString.getBytes());
            byte[] mac = m.doFinal();
            return new String(Base64.encodeBytes(mac)).trim();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    } else {
        throw new UnsupportedOperationException();
    }
}

From source file:com.cloud.test.stress.StressTestDirectAttach.java

public static String signRequest(String request, String key) {
    try {//from  w  w  w  . j  a  v a  2 s.  c  o m
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(request.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        return Base64.encodeBase64String(encryptedBytes);
    } catch (Exception ex) {
        s_logger.error("unable to sign request", ex);
    }
    return null;
}