Example usage for javax.crypto Mac getInstance

List of usage examples for javax.crypto Mac getInstance

Introduction

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

Prototype

public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Mac object that implements the specified MAC algorithm.

Usage

From source file:com.imaginary.home.controller.CloudService.java

static public String sign(byte[] key, String stringToSign) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");

    mac.init(new SecretKeySpec(key, "HmacSHA256"));
    return new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes("utf-8"))));
}

From source file:org.apache.jcp.xml.dsig.internal.dom.DOMHMACSignatureMethod.java

byte[] sign(Key key, SignedInfo si, XMLSignContext context) throws InvalidKeyException, XMLSignatureException {
    if (key == null || si == null) {
        throw new NullPointerException();
    }//from w ww .  j av  a 2  s.  c om
    if (!(key instanceof SecretKey)) {
        throw new InvalidKeyException("key must be SecretKey");
    }
    if (hmac == null) {
        try {
            hmac = Mac.getInstance(getJCAAlgorithm());
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLSignatureException(nsae);
        }
    }
    if (outputLengthSet && outputLength < getDigestLength()) {
        throw new XMLSignatureException("HMACOutputLength must not be less than " + getDigestLength());
    }
    hmac.init((SecretKey) key);
    ((DOMSignedInfo) si).canonicalize(context, new MacOutputStream(hmac));
    return hmac.doFinal();
}

From source file:com.jivesoftware.sdk.service.filter.JiveAuthorizationValidator.java

@Nonnull
private String sign(@Nonnull String str, @Nonnull String clientSecret, @Nonnull String algorithm)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    byte[] secret = Base64.decodeBase64(clientSecret);
    SecretKeySpec secretKeySpec = new SecretKeySpec(secret, algorithm);
    Mac mac = Mac.getInstance(algorithm);
    mac.init(secretKeySpec);// www .j ava 2s.  c o  m
    mac.update(str.getBytes("UTF-8"));
    return Base64.encodeBase64String(mac.doFinal()).replaceAll("\\s+", "");
}

From source file:com.chbase.android.simplexml.SodaAuthenticator.java

/**
 * Sign content./*  w  w  w  .  j a  v  a2s.  co  m*/
 * 
 * @param content the content
 * 
 * @return the byte[]
 */
private byte[] signContent(byte[] content) {
    try {
        SecretKeySpec sks = new SecretKeySpec(authenticationSecret, "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(sks);

        return mac.doFinal(content);
    } catch (Exception e) {
        throw new HVSystemException("Could not sign request", e);
    }
}

From source file:org.wso2.carbon.appfactory.s4.integration.utils.CloudUtils.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 * * @param data//from ww  w.  j  a va 2 s. co m
 * The data to be signed.
 * 
 * @param key
 *            The signing key.
 * @return
 *         The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AppFactoryException
 * @throws java.security.SignatureException
 *             when signature generation fails
 */
public static String calculateRFC2104HMAC(String stringToSign, String secrectAccessKey)
        throws AppFactoryException {

    // get an hmac_sha1 key from the raw key bytes
    SecretKeySpec signingKey = new SecretKeySpec(secrectAccessKey.getBytes(), HMAC_SHA1_ALGORITHM);

    // get an hmac_sha1 Mac instance and initialize with the signing key
    Mac mac = null;
    try {
        mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
    } catch (NoSuchAlgorithmException e) {
        String msg = "Error occured while computing RFC 2104-compliant HMAC signature";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);

    } catch (InvalidKeyException e) {
        String msg = "Error occured while computing RFC 2104-compliant HMAC signature";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);

    }

    // compute the hmac on input data bytes
    byte[] rawHmac = mac.doFinal(stringToSign.getBytes());

    // base64-encode the hmac
    return new String(Base64.encodeBase64(rawHmac));

}

From source file:org.artifactory.security.crypto.CryptoHelper.java

public static String generateUniqueApiKey() throws GeneralSecurityException {
    byte[] hmacData;

    try {/* www.  ja va 2  s .c  o m*/
        SecretKeySpec secretKey = new SecretKeySpec("secretKey".getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKey);
        String data = UUID.randomUUID().toString();
        hmacData = mac.doFinal(data.getBytes("UTF-8"));
        return new Base64Encoder().encode(hmacData);
    } catch (UnsupportedEncodingException e) {
        throw new GeneralSecurityException(e);
    }
}

From source file:de.hybris.platform.integration.cis.payment.strategies.impl.CisPaymentIntegrationTestHelper.java

public static String getPublicDigest(final String customValues) throws Exception {
    final String pub = getSharedSecret();
    final BASE64Encoder encoder = new BASE64Encoder();
    final Mac sha1Mac = Mac.getInstance("HmacSHA1");
    final SecretKeySpec publicKeySpec = new SecretKeySpec(pub.getBytes(), "HmacSHA1");
    sha1Mac.init(publicKeySpec);/*from w w  w  . j av a 2 s .  c  o m*/
    final byte[] publicBytes = sha1Mac.doFinal(customValues.getBytes());
    final String publicDigest = encoder.encodeBuffer(publicBytes);

    return publicDigest.replaceAll("\n", "");
}

From source file:com.cloud.test.utils.UtilsForTest.java

public static String signRequest(String request, String key) {
    try {//from ww w  . jav  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();
        //System.out.println("HmacSHA1 hash: " + encryptedBytes);
        return Base64.encodeBase64String(encryptedBytes);
    } catch (Exception ex) {
        System.out.println("unable to sign request");
        ex.printStackTrace();
    }
    return null;
}

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

private String generateSig(HttpRequest request, HttpParameters requestParameters) throws Exception {
    String keyString = OAuth.percentEncode(getConsumerSecret()) + '&' + OAuth.percentEncode(getTokenSecret());
    byte[] keyBytes = keyString.getBytes(OAuth.ENCODING);

    SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
    Mac mac = Mac.getInstance(MAC_NAME);
    mac.init(key);/*w w  w.  j a v  a2  s  .c om*/

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

From source file:com.google.gwtjsonrpc.server.SignedToken.java

private Mac newMac() throws XsrfException {
    try {//w ww  .j  av a  2 s .  c om
        final Mac m = Mac.getInstance(MAC_ALG);
        m.init(key);
        return m;
    } catch (NoSuchAlgorithmException e) {
        throw new XsrfException(MAC_ALG + " not supported", e);
    } catch (InvalidKeyException e) {
        throw new XsrfException("Invalid private key", e);
    }
}