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:mitm.common.util.StandardHttpURLBuilder.java

@Override
public String addHMAC(String name, Mac mac) throws URLBuilderException {
    Check.notNull(mac, "mac");

    if (parameters.size() == 0) {
        throw new URLBuilderException("There are no values.");
    }/*from   w  w w  .j av  a  2  s  .  c om*/

    for (Parameter parameter : parameters) {
        mac.update(MiscStringUtils.toAsciiBytes(parameter.getName()));
        mac.update(MiscStringUtils.toAsciiBytes(parameter.getValue()));
    }

    byte[] hmac = mac.doFinal();

    String base32 = Base32.encode(hmac);

    parameters.add(new Parameter(name, base32));

    return base32;
}

From source file:org.callimachusproject.behaviours.AuthenticationManagerSupport.java

private String sig(String text) throws OpenRDFException, IOException, GeneralSecurityException {
    String secret = this.getRealm().getOriginSecret();
    SecretKey key = new SecretKeySpec(readBytes(secret), "HmacSHA256");
    Mac m = Mac.getInstance("HmacSHA256");
    m.init(key);//from   w ww .  jav  a  2 s  .  co m
    m.update(text.getBytes("UTF-8"));
    return Base64.encodeBase64String(m.doFinal());
}

From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java

/**
 * @throws NoSuchAlgorithmException// ww w .  j  ava2s.c om
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws IllegalStateException
 * @throws NullPointerException if <code>tokenFile</code> is
 *             <code>null</code>.
 */
TokenStore(final File tokenFile, final long sessionTimeout, final boolean fastSeed)
        throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException,
        UnsupportedEncodingException {

    if (tokenFile == null) {
        throw new NullPointerException("tokenfile");
    }

    this.random = SecureRandom.getInstance(SHA1PRNG);
    this.ttl = sessionTimeout;
    this.tokenFile = tokenFile;
    this.tmpTokenFile = new File(tokenFile + ".tmp");

    // prime the secret keys from persistence
    loadTokens();

    // warm up the crypto API
    if (fastSeed) {
        random.setSeed(getFastEntropy());
    } else {
        log.info("Seeding the secure random number generator can take "
                + "up to several minutes on some operating systems depending "
                + "upon environment factors. If this is a problem for you, "
                + "set the system property 'java.security.egd' to "
                + "'file:/dev/./urandom' or enable the Fast Seed Generator " + "in the Web Console");
    }
    byte[] b = new byte[20];
    random.nextBytes(b);
    final SecretKey secretKey = new SecretKeySpec(b, HMAC_SHA1);
    final Mac m = Mac.getInstance(HMAC_SHA1);
    m.init(secretKey);
    m.update(UTF_8.getBytes(UTF_8));
    m.doFinal();
}

From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java

private String encode(final long expires, final String userId, final int token, final SecretKey key)
        throws IllegalStateException, UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException {/*  w ww .  j  a  v a 2  s  . c  om*/

    String cookiePayload = String.valueOf(token) + String.valueOf(expires) + "@" + userId;
    Mac m = Mac.getInstance(HMAC_SHA1);
    m.init(key);
    m.update(cookiePayload.getBytes(UTF_8));
    String cookieValue = byteToHex(m.doFinal());
    return cookieValue + "@" + cookiePayload;
}

From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java

public static byte[] decrypt(byte[] secure, ExternalContext ctx) {
    if (ctx == null)
        throw new NullPointerException("ExternalContext ctx");

    testConfiguration(ctx);//from  w  w w  .  ja  v a2 s .  c  o  m

    SecretKey secretKey = (SecretKey) getSecret(ctx);
    String algorithm = findAlgorithm(ctx);
    String algorithmParams = findAlgorithmParams(ctx);
    byte[] iv = findInitializationVector(ctx);

    SecretKey macSecretKey = (SecretKey) getMacSecret(ctx);
    String macAlgorithm = findMacAlgorithm(ctx);

    try {
        // keep local to avoid threading issue
        Mac mac = Mac.getInstance(macAlgorithm);
        mac.init(macSecretKey);
        Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams);
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
        }
        if (log.isLoggable(Level.FINE)) {
            log.fine("decrypting w/ " + algorithm + "/" + algorithmParams);
        }

        //EtM Composition Approach
        int macLenght = mac.getMacLength();
        mac.update(secure, 0, secure.length - macLenght);
        byte[] signedDigestHash = mac.doFinal();

        boolean isMacEqual = true;
        for (int i = 0; i < signedDigestHash.length; i++) {
            if (signedDigestHash[i] != secure[secure.length - macLenght + i]) {
                isMacEqual = false;
                // MYFACES-2934 Must compare *ALL* bytes of the hash, 
                // otherwise a side-channel timing attack is theorically possible
                // but with a very very low probability, because the
                // comparison time is too small to be measured compared to
                // the overall request time and in real life applications,
                // there are too many uncertainties involved.
                //break;
            }
        }
        if (!isMacEqual) {
            throw new ViewExpiredException();
        }

        return cipher.doFinal(secure, 0, secure.length - macLenght);
    } catch (Exception e) {
        throw new FacesException(e);
    }
}

From source file:org.apache.myfaces.shared.util.StateUtils.java

public static byte[] decrypt(byte[] secure, ExternalContext ctx) {
    if (ctx == null) {
        throw new NullPointerException("ExternalContext ctx");
    }/*from  w w  w. jav a  2 s .  c om*/

    testConfiguration(ctx);

    SecretKey secretKey = (SecretKey) getSecret(ctx);
    String algorithm = findAlgorithm(ctx);
    String algorithmParams = findAlgorithmParams(ctx);
    byte[] iv = findInitializationVector(ctx);

    SecretKey macSecretKey = (SecretKey) getMacSecret(ctx);
    String macAlgorithm = findMacAlgorithm(ctx);

    try {
        // keep local to avoid threading issue
        Mac mac = Mac.getInstance(macAlgorithm);
        mac.init(macSecretKey);
        Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams);
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
        }
        if (log.isLoggable(Level.FINE)) {
            log.fine("decrypting w/ " + algorithm + "/" + algorithmParams);
        }

        //EtM Composition Approach
        int macLenght = mac.getMacLength();
        mac.update(secure, 0, secure.length - macLenght);
        byte[] signedDigestHash = mac.doFinal();

        boolean isMacEqual = true;
        for (int i = 0; i < signedDigestHash.length; i++) {
            if (signedDigestHash[i] != secure[secure.length - macLenght + i]) {
                isMacEqual = false;
                // MYFACES-2934 Must compare *ALL* bytes of the hash, 
                // otherwise a side-channel timing attack is theorically possible
                // but with a very very low probability, because the
                // comparison time is too small to be measured compared to
                // the overall request time and in real life applications,
                // there are too many uncertainties involved.
                //break;
            }
        }
        if (!isMacEqual) {
            throw new ViewExpiredException();
        }

        return cipher.doFinal(secure, 0, secure.length - macLenght);
    } catch (Exception e) {
        throw new FacesException(e);
    }
}

From source file:mitm.application.djigzo.james.matchers.VerifyHMACHeader.java

private String calculateHMAC(String value, Mail mail) throws MessagingException, MissingSecretException {
    try {//  w w w .  ja  va  2 s .  c  o  m
        Mac mac = securityFactory.createMAC(ALGORITHM);

        byte[] secret = getSecret(mail);

        if (secret == null) {
            throw new MissingSecretException();
        }

        SecretKeySpec keySpec = new SecretKeySpec(secret, "raw");

        mac.init(keySpec);

        mac.update(MiscStringUtils.toAsciiBytes(value));

        return HexUtils.hexEncode(mac.doFinal());
    } catch (NoSuchAlgorithmException e) {
        throw new MessagingException("Error creating HMAC.", e);
    } catch (NoSuchProviderException e) {
        throw new MessagingException("Error creating HMAC.", e);
    } catch (InvalidKeyException e) {
        throw new MessagingException("Error creating HMAC.", e);
    }
}

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

protected static void checkCmpResponseGeneral(byte[] retMsg, String issuerDN, X500Name userDN,
        Certificate cacert, byte[] senderNonce, byte[] transId, boolean signed, String pbeSecret,
        String expectedSignAlg)//w ww .jav  a2  s.  c o m
        throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    assertNotNull("No response from server.", retMsg);
    assertTrue("Response was of 0 length.", retMsg.length > 0);
    boolean pbe = (pbeSecret != null);
    //
    // Parse response message
    //
    ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg));
    PKIMessage respObject = null;
    try {
        respObject = PKIMessage.getInstance(asn1InputStream.readObject());
    } finally {
        asn1InputStream.close();
    }
    assertNotNull(respObject);

    // The signer, i.e. the CA, check it's the right CA
    PKIHeader header = respObject.getHeader();

    // Check that the message is signed with the correct digest alg
    if (StringUtils.isEmpty(expectedSignAlg)) {
        expectedSignAlg = PKCSObjectIdentifiers.sha1WithRSAEncryption.getId();
    }
    // if cacert is ECDSA we should expect an ECDSA signature alg
    //if (AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECDSA")) {
    //    expectedSignAlg = X9ObjectIdentifiers.ecdsa_with_SHA1.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("ECGOST3410")) {
    //    expectedSignAlg = CryptoProObjectIdentifiers.gostR3411_94_with_gostR3410_2001.getId();
    //} else if(AlgorithmTools.getSignatureAlgorithm(cacert).contains("DSTU4145")) {
    //    expectedSignAlg = (new ASN1ObjectIdentifier(CesecoreConfiguration.getOidDstu4145())).getId();
    //}
    if (signed) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a signed response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals(expectedSignAlg, algId.getAlgorithm().getId());
    }
    if (pbe) {
        AlgorithmIdentifier algId = header.getProtectionAlg();
        assertNotNull(
                "Protection algorithm was null when expecting a pbe protected response, this was propably an unprotected error message: "
                        + header.getFreeText(),
                algId);
        assertEquals("Protection algorithm id: " + algId.getAlgorithm().getId(),
                CMPObjectIdentifiers.passwordBasedMac.getId(), algId.getAlgorithm().getId()); // 1.2.840.113549.1.1.5 - SHA-1 with RSA Encryption
    }

    // Check that the signer is the expected CA    
    assertEquals(header.getSender().getTagNo(), 4);

    X500Name expissuer = new X500Name(issuerDN);
    X500Name actissuer = new X500Name(header.getSender().getName().toString());
    assertEquals(expissuer, actissuer);
    if (signed) {
        // Verify the signature
        byte[] protBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString bs = respObject.getProtection();
        Signature sig;
        try {
            sig = Signature.getInstance(expectedSignAlg, "BC");
            sig.initVerify(cacert);
            sig.update(protBytes);
            boolean ret = sig.verify(bs.getBytes());
            assertTrue(ret);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            assertTrue(false);
        } catch (SignatureException e) {
            e.printStackTrace();
            assertTrue(false);
        }
    }
    if (pbe) {
        ASN1OctetString os = header.getSenderKID();
        assertNotNull(os);
        String keyId = CmpMessageHelper.getStringFromOctets(os);
        log.debug("Found a sender keyId: " + keyId);
        // Verify the PasswordBased protection of the message
        byte[] protectedBytes = CmpMessageHelper.getProtectedBytes(respObject);
        DERBitString protection = respObject.getProtection();
        AlgorithmIdentifier pAlg = header.getProtectionAlg();
        log.debug("Protection type is: " + pAlg.getAlgorithm().getId());
        PBMParameter pp = PBMParameter.getInstance(pAlg.getParameters());
        int iterationCount = pp.getIterationCount().getPositiveValue().intValue();
        log.debug("Iteration count is: " + iterationCount);
        AlgorithmIdentifier owfAlg = pp.getOwf();
        // Normal OWF alg is 1.3.14.3.2.26 - SHA1
        log.debug("Owf type is: " + owfAlg.getAlgorithm().getId());
        AlgorithmIdentifier macAlg = pp.getMac();
        // Normal mac alg is 1.3.6.1.5.5.8.1.2 - HMAC/SHA1
        log.debug("Mac type is: " + macAlg.getAlgorithm().getId());
        byte[] salt = pp.getSalt().getOctets();
        // log.info("Salt is: "+new String(salt));
        byte[] raSecret = pbeSecret != null ? pbeSecret.getBytes() : new byte[0];
        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(),
                BouncyCastleProvider.PROVIDER_NAME);
        for (int i = 0; i < iterationCount; i++) {
            basekey = dig.digest(basekey);
            dig.reset();
        }
        // HMAC/SHA1 os normal 1.3.6.1.5.5.8.1.2 or 1.2.840.113549.2.7
        String macOid = macAlg.getAlgorithm().getId();
        Mac mac = Mac.getInstance(macOid, BouncyCastleProvider.PROVIDER_NAME);
        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();
        boolean ret = Arrays.equals(out, pb);
        assertTrue(ret);
    }

    // --SenderNonce
    // SenderNonce is something the server came up with, but it should be 16
    // chars
    byte[] nonce = header.getSenderNonce().getOctets();
    assertEquals(nonce.length, 16);

    // --Recipient Nonce
    // recipient nonce should be the same as we sent away as sender nonce
    nonce = header.getRecipNonce().getOctets();
    assertEquals(new String(nonce), new String(senderNonce));

    // --Transaction ID
    // transid should be the same as the one we sent
    nonce = header.getTransactionID().getOctets();
    assertEquals(new String(nonce), new String(transId));

}

From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java

private PKIMessage protectPKIMessageWithHMAC(PKIMessage msg, boolean badObjectId, String password,
        int iterations) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException {
    // Create the PasswordBased protection of the message
    PKIHeaderBuilder head = getHeaderBuilder(msg.getHeader());
    // SHA1// w w w . j a v  a 2s. com
    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 = 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.hardisonbrewing.s3j.FileSyncer.java

private byte[] hmacSHA1(String key, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException {

    SecretKey secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(secretKeySpec);//  ww  w . j  ava 2 s  .co  m
    mac.update(data);
    return mac.doFinal();
}