Example usage for javax.crypto Mac getAlgorithm

List of usage examples for javax.crypto Mac getAlgorithm

Introduction

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

Prototype

public final String getAlgorithm() 

Source Link

Document

Returns the algorithm name of this Mac object.

Usage

From source file:Main.java

public static String createHMACWithMD5(String source, String key)
        throws NoSuchAlgorithmException, InvalidKeyException {
    Mac hmac = Mac.getInstance("HmacMD5");
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), hmac.getAlgorithm());
    hmac.init(secretKey);//from  w ww .ja  v a2s  .c om

    byte[] signature = hmac.doFinal(source.getBytes());
    return Base64.encodeToString(signature, Base64.DEFAULT);
}

From source file:com.google.resting.rest.util.oauth.SignatureUtil.java

/**
 * Sign request.//from  w w  w  .  j  av a2 s .c  om
 * 
 * @param keyString Consumer key for request signing.
 * @param targetDomain Domain of the REST endpoint (Ex. login.yahoo.com)
 * @param verb Type of REST operation (GET/POST/PUT/DELETE)
 * @param isSecureInvocation HTTP/HTTPS
 * @param contextPathElement Path element in the base REST uri (Ex. /weather/india)
 * @param inputParams Collection of request params for REST request (Ex. city=calcutta )
 * @return
 * @throws NoSuchAlgorithmException The exception is thrown if the encryption algorithm is not supported.
 * @throws InvalidKeyException The exception is thrown if the consumer key is invalid
 * @throws IllegalStateException 
 * @throws UnsupportedEncodingException The exception is thrown if the URL encoding is incorrect.
 */
public static String getSignature(String keyString, String targetDomain, Verb verb, boolean isSecureInvocation,
        String contextPathElement, List<NameValuePair> inputParams, String messageEncoding)
        throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException,
        UnsupportedEncodingException {

    String baseString = getBaseString(targetDomain, verb.toString(), isSecureInvocation, contextPathElement,
            inputParams, messageEncoding).replace("+", "%20").replace("*", "%2A").replace("%7E", "~");

    System.out.println("Base string is " + baseString);
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(keyString.getBytes(messageEncoding), mac.getAlgorithm());
    mac.init(secret);
    byte[] digest = mac.doFinal(baseString.getBytes(messageEncoding));
    return new String(Base64.encodeBase64(digest)).replace(RequestConstants.CARRIAGE_RETURN,
            RequestConstants.EMPTY_STRING);
}

From source file:kcb.billerengine.utils.Utils.java

public static String computeToken(String key, String data) {
    String token = null;/*from  w  w  w  .  j  av  a  2s . c o  m*/
    try {
        SecretKey secretKey = null;
        byte[] keyBytes = key.getBytes("UTF-8");
        Mac mac = Mac.getInstance("HMACSHA256");
        secretKey = new SecretKeySpec(keyBytes, mac.getAlgorithm());
        mac.init(secretKey);
        byte[] text = data.getBytes("UTF-8");
        byte[] encodedText = mac.doFinal(text);

        token = new String(Base64.encodeBase64(encodedText)).trim();
    } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException ex) {
        LOG.error("ComputeToken error : " + ex);
    }

    return token;
}

From source file:Main.java

private static String generateSignature(String base, String type, String nonce, String timestamp, String token,
        String tokenSecret, String verifier, ArrayList<String> parameters)
        throws NoSuchAlgorithmException, InvalidKeyException {
    String encodedBase = Uri.encode(base);

    StringBuilder builder = new StringBuilder();

    //Create an array of all the parameters
    //So that we can sort them
    //OAuth requires that we sort all parameters
    ArrayList<String> sortingArray = new ArrayList<String>();

    sortingArray.add("oauth_consumer_key=" + oauthConsumerKey);
    sortingArray.add("oauth_nonce=" + nonce);
    sortingArray.add("oauth_signature_method=HMAC-SHA1");
    sortingArray.add("oauth_timestamp=" + timestamp);
    sortingArray.add("oauth_version=1.0");

    if (parameters != null) {
        sortingArray.addAll(parameters);
    }//from   www .j  ava2s.  c  om

    if (token != "" && token != null) {
        sortingArray.add("oauth_token=" + token);
    }
    if (verifier != "" && verifier != null) {
        sortingArray.add("oauth_verifier=" + verifier);
    }

    Collections.sort(sortingArray);

    //Append all parameters to the builder in the right order
    for (int i = 0; i < sortingArray.size(); i++) {
        if (i > 0)
            builder.append("&" + sortingArray.get(i));
        else
            builder.append(sortingArray.get(i));

    }

    String params = builder.toString();
    //Percent encoded the whole url
    String encodedParams = Uri.encode(params);

    String completeUrl = type + "&" + encodedBase + "&" + encodedParams;

    String completeSecret = oauthSecretKey;

    if (tokenSecret != null && tokenSecret != "") {
        completeSecret = completeSecret + "&" + tokenSecret;
    } else {
        completeSecret = completeSecret + "&";
    }

    Log.v("Complete URL: ", completeUrl);
    Log.v("Complete Key: ", completeSecret);

    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(completeSecret.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] sig = mac.doFinal(completeUrl.getBytes());

    String signature = Base64.encodeToString(sig, 0);
    signature = signature.replace("+", "%2b"); //Specifically encode all +s to %2b

    return signature;
}

From source file:ch.cyberduck.core.sftp.openssh.OpenSSHHostKeyVerifier.java

private static byte[] hmacSha1Hash(byte[] salt, String hostname) throws IOException {
    try {/*  ww w.  ja v a 2 s  .co  m*/
        final Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(salt, 0, salt.length, mac.getAlgorithm()));
        mac.update(hostname.getBytes());
        return mac.doFinal();
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }
}

From source file:com.otaupdater.utils.Utils.java

public static String hmac(String str, String key) {
    try {/* ww  w .j  a  v a 2  s. co m*/
        Mac mac = Mac.getInstance(Config.HMAC_ALGORITHM);
        String salt = randomSaltString(mac.getMacLength());
        mac.init(new SecretKeySpec(key.getBytes(), mac.getAlgorithm()));
        return byteArrToStr(mac.doFinal((salt + str + salt).getBytes("UTF-8"))) + salt;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.cesecore.audit.impl.queued.entity.HmacLogManagementDataTest.java

@Test
public void test01LoadTokenConfigProps() throws Exception {

    AuditLogCryptoTokenConfigData tokenConfig = hmac.getTokenConfig();
    CryptoToken token = CryptoTokenFactory.createCryptoToken(tokenConfig.getClassname(),
            tokenConfig.getProperties(), tokenConfig.getTokenData(), 1);

    token.activate(//from w  ww  . j a v a  2s . co  m
            ((String) tokenConfig.getProperties().get(CryptoToken.AUTOACTIVATE_PIN_PROPERTY)).toCharArray());
    Key hMacKey = token.getKey(keyAlias);

    Mac hMac = Mac.getInstance(hmac.getAlgorithm(), token.getEncProviderName());
    hMac.init(hMacKey);
    hMac.update(dataToBeSigned.getBytes());
    byte[] signedData = hMac.doFinal();

    assertTrue(ArrayUtils.isEquals(signedData, signed));

}

From source file:org.cesecore.audit.impl.queued.entity.HmacLogManagementDataTest.java

@Before
public void createHmacConfig() throws Exception {
    log.trace(">setUp()");

    tokenConfigData = new AuditLogCryptoTokenConfigData();
    tokenConfigData.setClassname(SoftCryptoToken.class.getName());
    Properties props = new Properties();
    props.setProperty(CryptoToken.AUTOACTIVATE_PIN_PROPERTY, tokenPin);

    CryptoToken token = CryptoTokenFactory.createCryptoToken(SoftCryptoToken.class.getName(), props, null, 1);
    token.activate(tokenPin.toCharArray());
    token.generateKey("HmacSHA1", 256, keyAlias);

    tokenConfigData.setProperties(props);

    hmac = new HmacLogManagementData();
    hmac.setAlgorithm(algorithm);/*w  w  w.  j  av a 2  s.  com*/
    hmac.setKeyLabel(keyAlias);
    hmac.setFrequency(0l);
    hmac.setTokenConfig(tokenConfigData);

    byte[] tokenData = token.getTokenData();
    tokenConfigData.setTokenData(tokenData);

    Key hMacKey = token.getKey(keyAlias);

    Mac hMac = Mac.getInstance(hmac.getAlgorithm(), token.getEncProviderName());
    hMac.init(hMacKey);
    hMac.update(dataToBeSigned.getBytes());
    signed = hMac.doFinal();

    log.trace("<setUp()");
}

From source file:com.spartan.springmvc.bean.FacebookSignatureBean.java

/**
 * Parses and verifies a Facebook signed_request parameter. The data of the signed request is returned on successful verification.
 *
 * @param signedRequest//from www. j  ava2s .  c o  m
 * @param appSecret
 * @return 
 * @return
 * @throws FacebookSignatureVerificationFailedException
 */
@SuppressWarnings("unchecked")
public <T> T parseSignature(String signedRequest, String appSecret, Class<T> clazz)
        throws FacebookSignatureVerificationFailedException {

    String[] parts = signedRequest.split("\\.");
    if (parts.length != 2) {
        throw new FacebookSignatureVerificationFailedException("Invalid signature format.");
    }

    String encSig = parts[0];
    String encPayload = parts[1];
    Base64 decoder = new Base64(true);

    try {
        Mac mac = Mac.getInstance("HMACSHA256");
        mac.init(new SecretKeySpec(appSecret.getBytes(), mac.getAlgorithm()));
        byte[] calcSig = mac.doFinal(encPayload.getBytes());
        byte[] decodedSig = decoder.decode(encSig);
        boolean isVerified = Arrays.equals(decodedSig, calcSig);

        if (isVerified) {
            try {
                String unsignedData = new String(decoder.decode(encPayload));
                logger.debug("unsignedData: " + unsignedData);
                ObjectMapper mapper = new ObjectMapper();
                mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                T data = mapper.readValue(unsignedData, (Class<T>) clazz);
                return data;
            } catch (IOException e) {
                throw new FacebookSignatureVerificationFailedException(
                        "Failed to parse JSON data: " + e.getMessage(), e);
            }
        } else {
            throw new FacebookSignatureVerificationFailedException("Signatures do not match.");
        }

    } catch (NoSuchAlgorithmException e) {
        throw new FacebookSignatureVerificationFailedException(e);
    } catch (InvalidKeyException e) {
        throw new FacebookSignatureVerificationFailedException(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());
}