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.apache.abdera.ext.oauth.OAuthScheme.java

private String sign(String method, String baseString, Certificate cert) throws AuthenticationException {
    if (method.equalsIgnoreCase("HMAC-MD5") || method.equalsIgnoreCase("HMAC-SHA1")) {
        try {//from  www .  j a v  a  2s . c  o m
            String[] tokens = method.split("-");
            String methodName = tokens[0].substring(0, 1).toUpperCase() + tokens[0].substring(1).toLowerCase()
                    + tokens[1];
            KeyGenerator kg = KeyGenerator.getInstance(methodName);

            Mac mac = Mac.getInstance(kg.getAlgorithm());
            mac.init(kg.generateKey());
            byte[] result = mac.doFinal(baseString.getBytes());

            return new String(Base64.encodeBase64(result));
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e);
        }
    } else if (method.equalsIgnoreCase("md5")) {
        return new String(Base64.encodeBase64(DigestUtils.md5(baseString)));
    } else if (method.equalsIgnoreCase("sha1")) {
        return new String(Base64.encodeBase64(DigestUtils.sha(baseString)));
    } else if (method.equalsIgnoreCase("RSA-SHA1")) {
        if (cert == null) {
            throw new AuthenticationException("a cert is mandatory to use SHA1 with RSA");
        }
        try {
            Cipher cipher = Cipher.getInstance("SHA1withRSA");
            cipher.init(Cipher.ENCRYPT_MODE, cert);
            byte[] result = cipher.doFinal(baseString.getBytes());
            return new String(Base64.encodeBase64(result));
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e);
        }
    } else {
        throw new AuthenticationException("unsupported algorithm method: " + method);
    }
}

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);//  w ww .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:com.amediamanager.util.S3FormSigner.java

/**
 * The SignRequest method takes a set of AWS credentials and the S3 upload policy string and returns the encoded policy and the signature.
 *
 * @param creds        the AWS credentials to be used for signing the request
 * @param policy    the policy file to applied to the upload
 * @return            an array of strings containing the base 64 encoded policy (index 0) and the signature (index 1).
 *//*from   w  w  w.ja  v  a2s  .  c  o  m*/
String[] signRequest(AWSCredentialsProvider credsProvider, String policy) {

    String[] policyAndSignature = new String[2];

    try {
        // Create a Base64 encoded version of the policy string for placement in the form and
        // for use in signature generation.  Returns are stripped out from the policy string.
        String encodedPolicy = new String(
                Base64.encodeBase64(policy.replaceAll("\n", "").replaceAll("\r", "").getBytes("UTF-8")));

        // AWS signatures are generated using SHA1 HMAC signing.
        Mac hmac = Mac.getInstance("HmacSHA1");

        // Generate the signature using the Secret Key from the AWS credentials
        hmac.init(new SecretKeySpec(credsProvider.getCredentials().getAWSSecretKey().getBytes("UTF-8"),
                "HmacSHA1"));

        String signature = new String(Base64.encodeBase64(hmac.doFinal(encodedPolicy.getBytes("UTF-8"))));

        // Pack the encoded policy and the signature into a string array
        policyAndSignature[0] = encodedPolicy;
        policyAndSignature[1] = signature;

    } catch (UnsupportedEncodingException e) {
        LOG.error("Unsupport encoding", e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error("No such algorithm", e);
    } catch (InvalidKeyException e) {
        LOG.error("Invalid key", e);
    }

    return policyAndSignature;
}

From source file:co.edu.uniandes.csw.Arquidalgos.usuario.service._UsuarioService.java

@POST
@Path("/crearUsuario")
public UsuarioDTO crearUsuario(UsuarioDTO usuario) throws Exception {

    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    String key = "123";
    SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);

    System.out.println("TO String: " + usuario.toString());

    String hash = Hex.encodeHexString(sha256_HMAC.doFinal(usuario.toString().getBytes()));
    System.out.println("CODIGO HASH: " + hash);
    System.out.println("CODIGO HASH JSON " + usuario.getHash());

    boolean alterado = !(hash.equalsIgnoreCase(usuario.getHash()));
    System.out.println("Alterado: " + alterado);

    if (alterado) {
        throw new Exception("Se han alterado los datos");
    }//from  w ww  . jav a 2 s . c om
    return createUsuario(usuario);
}

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 {//ww  w. j a  v a  2  s . 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:br.com.argonavis.jaspictut.service.FacebookConnectService.java

/**
 * Source: https://jira.spring.io/browse/SOCIALFB-148
 * @param token/* w  ww.j  a  v  a  2 s .co m*/
 * @param appSecret
 * @return
 * @throws Exception 
 */
private String calculateAppSecretProof(String token, String appSecret) {
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(appSecret.getBytes("UTF-8"), "HmacSHA256");
        mac.init(secretKey);
        byte[] digest = mac.doFinal(token.getBytes());
        return new String(Hex.encodeHex(digest));
    } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException ex) {
        Logger.getLogger(FacebookConnectService.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.zegoggles.smssync.auth.XOAuthConsumer.java

private String generateSig(HttpRequest request, HttpParameters requestParameters) throws Exception {
    String keyString = percentEncode(getConsumerSecret()) + '&' + percentEncode(getTokenSecret());

    SecretKey key = new SecretKeySpec(keyString.getBytes(ENCODING), MAC_NAME);
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);

    String sbs = new SignatureBaseString(request, requestParameters).generate();
    return base64(mac.doFinal(sbs.getBytes(ENCODING)));
}

From source file:com.jpeterson.littles3.bo.S3Authenticator.java

/**
 * Authenticate the request using the prescribed Amazon S3 authentication
 * mechanisms.//ww w .  jav  a2 s  .  c  om
 * 
 * @param req
 *            The original HTTP request.
 * @param s3Request
 *            The S3 specific information for authenticating the request.
 * @return The authenticated <code>CanonicalUser</code> making the request.
 * @throws RequestTimeTooSkewedException
 *             Thrown if the request timestamp is outside of the allotted
 *             timeframe.
 */
public CanonicalUser authenticate(HttpServletRequest req, S3ObjectRequest s3Request)
        throws AuthenticatorException {
    // check to see if anonymous request
    String authorization = req.getHeader(HEADER_AUTHORIZATION);

    if (authorization == null) {
        return new CanonicalUser(CanonicalUser.ID_ANONYMOUS);
    }

    // attempting to be authenticated request

    if (false) {
        // check timestamp of request
        Date timestamp = s3Request.getTimestamp();
        if (timestamp == null) {
            throw new RequestTimeTooSkewedException("No timestamp provided");
        }

        GregorianCalendar calendar = new GregorianCalendar();
        Date now = calendar.getTime();
        calendar.add(Calendar.MINUTE, 15);
        Date maximumDate = calendar.getTime();
        calendar.add(Calendar.MINUTE, -30);
        Date minimumDate = calendar.getTime();

        if (timestamp.before(minimumDate)) {
            throw new RequestTimeTooSkewedException(
                    "Timestamp [" + timestamp + "] too old. System time: " + now);
        }

        if (timestamp.after(maximumDate)) {
            throw new RequestTimeTooSkewedException(
                    "Timestamp [" + timestamp + "] too new. System time: " + now);
        }
    }

    // authenticate request
    String[] fields = authorization.split(" ");

    if (fields.length != 2) {
        throw new InvalidSecurityException("Unsupported authorization format");
    }

    if (!fields[0].equals(AUTHORIZATION_TYPE)) {
        throw new InvalidSecurityException("Unsupported authorization type: " + fields[0]);
    }

    String[] keys = fields[1].split(":");

    if (keys.length != 2) {
        throw new InvalidSecurityException("Invalid AWSAccesskeyId:Signature");
    }

    String accessKeyId = keys[0];
    String signature = keys[1];
    String secretAccessKey = userDirectory.getAwsSecretAccessKey(accessKeyId);
    String calculatedSignature;

    try {
        SecretKey key = new SecretKeySpec(secretAccessKey.getBytes(), "HmacSHA1");
        Mac m = Mac.getInstance("HmacSHA1");
        m.init(key);
        m.update(s3Request.getStringToSign().getBytes());
        byte[] mac = m.doFinal();
        calculatedSignature = new String(Base64.encodeBase64(mac));
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidSecurityException(e);
    } catch (InvalidKeyException e) {
        throw new InvalidSecurityException(e);
    }

    System.out.println("-----------------");
    System.out.println("signature: " + signature);
    System.out.println("calculatedSignature: " + calculatedSignature);
    System.out.println("-----------------");

    if (calculatedSignature.equals(signature)) {
        // authenticated!
        return userDirectory.getCanonicalUser(secretAccessKey);
    } else {
        throw new SignatureDoesNotMatchException("Provided signature doesn't match calculated value");
    }
}

From source file:org.springframework.social.facebook.web.RealTimeUpdateController.java

private boolean verifySignature(String payload, String signature) throws Exception {
    if (!signature.startsWith("sha1=")) {
        return false;
    }//from   w  ww  . j ava 2  s  .  c o m
    String expected = signature.substring(5);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    SecretKeySpec signingKey = new SecretKeySpec(applicationSecret.getBytes(), HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    byte[] rawHmac = mac.doFinal(payload.getBytes());
    String actual = new String(Hex.encode(rawHmac));
    return expected.equals(actual);
}

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

/** {@inheritDoc} */
@Override//ww w  . j  a v a 2  s . c  om
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);
}