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:com.sina.auth.AbstractAWSSigner.java

protected byte[] sign(byte[] data, byte[] key, SigningAlgorithm algorithm) throws SCSClientException {
    try {/*  www  . ja v  a  2 s.  c om*/
        Mac mac = Mac.getInstance(algorithm.toString());
        mac.init(new SecretKeySpec(key, algorithm.toString()));
        return mac.doFinal(data);
    } catch (Exception e) {
        throw new SCSClientException("Unable to calculate a request signature: " + e.getMessage(), e);
    }
}

From source file:org.hoteia.qalingo.core.service.openid.OpenIdService.java

String getHmacSha1(String data, byte[] key) {
    SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);
    Mac mac = null;
    try {//w w w .  ja va 2s  . co m
        mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
    } catch (NoSuchAlgorithmException e) {
        throw new OpenIdException(e);
    } catch (InvalidKeyException e) {
        throw new OpenIdException(e);
    }
    try {
        byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));
        return Base64.encodeBytes(rawHmac);
    } catch (IllegalStateException e) {
        throw new OpenIdException(e);
    } catch (UnsupportedEncodingException e) {
        throw new OpenIdException(e);
    }
}

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 w  w.  j a  va 2s.co m

    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.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);
    m.update(text.getBytes("UTF-8"));
    return Base64.encodeBase64String(m.doFinal());
}

From source file:org.dasein.cloud.cloudstack.CSMethod.java

private byte[] calculateHmac(String data, String key) throws SignatureException {
    try {//from  ww w .j av a 2  s  .  c  o  m
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        return mac.doFinal(data.getBytes());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
}

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

private String calculateHMAC(String value, Mail mail) throws MessagingException, MissingSecretException {
    try {//from w  w w. ja v  a2 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 w  w  . j av a 2  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:n3phele.storage.swift.CloudStorageImpl.java

private final String signSwiftQueryString(String stringToSign, Credential credential) {
    try {//from ww  w.j  ava 2 s .co  m
        byte[] keyBytes = credential.decrypt().getSecret().getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(stringToSign.getBytes());
        byte[] hexBytes = new Hex().encode(rawHmac);
        return new String(hexBytes, "UTF-8");
    } catch (IllegalStateException e) {
        log.log(Level.SEVERE, "Signing error", e);
        throw new IllegalArgumentException(e.getMessage());
    } catch (InvalidKeyException e) {
        log.log(Level.SEVERE, "Signing error", e);
        throw new IllegalArgumentException(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        log.log(Level.SEVERE, "Signing error", e);
        throw new IllegalArgumentException(e.getMessage());
    } catch (UnsupportedEncodingException e) {
        log.log(Level.SEVERE, "Signing error", e);
        throw new IllegalArgumentException(e.getMessage());
    }
}

From source file:net.mms_projects.copy_it.api.oauth.HeaderVerifier.java

/**
 * Validate the signature for the request, make sure you've called all verify* methods first
 * @param postRequestDecoder The post parameters for the request, pass null if it's a GET request instead
 * @param https Should we use https to generate our signature?
 * @throws OAuthException Thrown if the signature is invalid
 *//*from  w w  w  .  jav  a  2s  .c  om*/
public void checkSignature(HttpPostRequestDecoder postRequestDecoder, boolean https)
        throws UnsupportedEncodingException, URISyntaxException, OAuthException {
    final String signed_with = oauth_params.get(OAuthParameters.OAUTH_SIGNATURE);
    final String raw = createRaw(postRequestDecoder, https);
    final String secretkey = consumer.getSecretKey() + "&" + user.getSecretKey();
    try {
        final Key signingKey = new SecretKeySpec(secretkey.getBytes(), HMAC_SHA1);
        final Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(raw.getBytes());
        final String signature = new String(Base64.encodeBase64(rawHmac));
        System.err.println("Signed with: " + URLDecoder.decode(signed_with, UTF_8));
        System.err.println("Should be::: " + signature);
        if (!URLDecoder.decode(signed_with, UTF_8).equals(signature))
            throw new OAuthException(ErrorMessages.INVALID_SIGNATURE);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
}