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.microsoft.tfs.jni.internal.ntlm.JavaNTLM.java

private static byte[] createNtlm2Response(final String username, final String password, final String domain,
        final NTLMType2Message type2) throws NTLMException {
    final byte[] ntlm2Hash = ntlm2Hash(username, password, domain);

    final int targetInfoLen = type2.targetInfo != null ? type2.targetInfo.length : 0;
    final byte[] ntlm2Blob = new byte[40 + targetInfoLen];

    // construct the "blob"
    addBytes(ntlm2Blob, 0, new byte[] { 0x01, 0x01, 0x00, 0x00 }); // "blob" signature
    addLong(ntlm2Blob, 4, 0); // "reserved"
    addBytes(ntlm2Blob, 8, createTimestamp());
    addBytes(ntlm2Blob, 16, createClientNonce());
    addBytes(ntlm2Blob, 24, new byte[] { (byte) 0xad, (byte) 0xde, (byte) 0x15, (byte) 0xed }); // unknown

    if (targetInfoLen > 0) {
        addBytes(ntlm2Blob, 28, type2.targetInfo);
    }//w w w.  j a  va 2 s . c o  m

    // insert obligatory pixies reference here
    addBytes(ntlm2Blob, (28 + targetInfoLen),
            new byte[] { (byte) 0xad, (byte) 0xde, (byte) 0x15, (byte) 0xed }); // again unknown
    // the end? of the blob

    // concatenate the type 2 message's challenge with the blob
    final byte[] challengedBlob = new byte[type2.challenge.length + ntlm2Blob.length];
    addBytes(challengedBlob, 0, type2.challenge);
    addBytes(challengedBlob, type2.challenge.length, ntlm2Blob);

    // now we get the HMAC-MD5 of the blob using the ntlm2 hash as a key
    // ick.
    byte[] blobHash;
    try {
        final Mac mac = Mac.getInstance("HmacMD5"); //$NON-NLS-1$
        mac.init(new SecretKeySpec(ntlm2Hash, "HmacMD5")); //$NON-NLS-1$
        blobHash = mac.doFinal(challengedBlob);
    } catch (final Exception e) {
        LOG.error("Could not load HmacMD5 for NTLM", e); //$NON-NLS-1$
        throw new NTLMException(e.getMessage());
    }

    final byte[] ntlm2Response = new byte[blobHash.length + ntlm2Blob.length];

    // concatenate the blob with its hash
    addBytes(ntlm2Response, 0, blobHash);
    addBytes(ntlm2Response, blobHash.length, ntlm2Blob);

    return ntlm2Response;
}

From source file:de.andreas_rueckert.trade.site.mtgox.client.MtGoxClient.java

/**
 * Create authentication entries for a HTTP post header.
 *
 * @param postData The data to post via HTTP.
 * @param userAccount The account of the user on the exchange. Null, if the default account should be used.
 *
 * @return The header entries as a map or null if an error occured.
 *//* w  w  w.j  a  v  a2 s .  com*/
Map<String, String> getAuthenticationHeader(String postData, TradeSiteUserAccount userAccount) {
    HashMap<String, String> result = new HashMap<String, String>();
    Mac mac;
    String accountKey = null;
    String accountSecret = null;

    // Try to get user account and secret.
    if (userAccount != null) {

        accountKey = userAccount.getAPIkey();
        accountSecret = userAccount.getSecret();

    } else { // Use the default account from the API implementation.

        accountKey = _key;
        accountSecret = _secret;
    }

    // Check, if key and secret are available for the request.
    if (accountKey == null) {
        throw new MissingAccountDataException("Key not available for authenticated request to MtGox");
    }
    if (accountSecret == null) {
        throw new MissingAccountDataException("Secret not available for authenticated request to MtGox");
    }

    result.put("Rest-Key", accountKey);

    // Create a new secret key
    SecretKeySpec key = new SecretKeySpec(Base64.decodeBase64(accountSecret), "HmacSHA512");

    // Create a new mac
    try {

        mac = Mac.getInstance("HmacSHA512");

    } catch (NoSuchAlgorithmException nsae) {

        System.err.println("No such algorithm exception: " + nsae.toString());

        return null;
    }

    // Init mac with key.
    try {

        mac.init(key);

    } catch (InvalidKeyException ike) {

        System.err.println("Invalid key exception: " + ike.toString());

        return null;
    }

    // Encode the post data by the secret and encode the result as base64.
    try {

        result.put("Rest-Sign", Base64.encodeBase64String(mac.doFinal(postData.getBytes("UTF-8"))));

    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());

        return null;
    }

    return result;
}

From source file:net.sf.xfd.provider.PublicProvider.java

final void verifyMac(Uri path, String grantMode, String requested) throws FileNotFoundException {
    if (Process.myUid() == Binder.getCallingUid()) {
        return;//from   ww w.  ja  v  a 2 s  .  co  m
    }

    final int requestedMode = ParcelFileDescriptor.parseMode(requested);

    final String cookie = path.getQueryParameter(URI_ARG_COOKIE);
    final String expiry = path.getQueryParameter(URI_ARG_EXPIRY);

    if (TextUtils.isEmpty(cookie) || TextUtils.isEmpty(expiry)) {
        throw new FileNotFoundException("Invalid uri: MAC and expiry date are missing");
    }

    final long l;
    try {
        l = Long.parseLong(expiry);
    } catch (NumberFormatException nfe) {
        throw new FileNotFoundException("Invalid uri: unable to parse expiry date");
    }

    final Key key = getSalt(getContext());
    if (key == null) {
        throw new FileNotFoundException("Unable to verify hash: failed to produce key");
    }

    final int modeInt = ParcelFileDescriptor.parseMode(grantMode);

    if ((requestedMode & modeInt) != requestedMode) {
        throw new FileNotFoundException("Requested mode " + requested + " but limited to " + grantMode);
    }

    final byte[] encoded;
    final Mac hash;
    try {
        hash = Mac.getInstance("HmacSHA1");
        hash.init(key);

        final byte[] modeBits = new byte[] { (byte) (modeInt >> 24), (byte) (modeInt >> 16),
                (byte) (modeInt >> 8), (byte) modeInt, };
        hash.update(modeBits);

        final byte[] expiryDate = new byte[] { (byte) (l >> 56), (byte) (l >> 48), (byte) (l >> 40),
                (byte) (l >> 32), (byte) (l >> 24), (byte) (l >> 16), (byte) (l >> 8), (byte) l, };
        hash.update(expiryDate);

        encoded = hash.doFinal(path.getPath().getBytes());

        final String sample = Base64.encodeToString(encoded, URL_SAFE | NO_WRAP | NO_PADDING);

        if (!cookie.equals(sample)) {
            throw new FileNotFoundException("Expired uri");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new FileNotFoundException("Unable to verify hash: missing HmacSHA1");
    } catch (InvalidKeyException e) {
        throw new FileNotFoundException("Unable to verify hash: corrupted key?!");
    }
}

From source file:be.cytomine.client.HttpClient.java

public void authorize(String action, String url, String contentType, String accept) throws IOException {
    url = url.replace(host, "");
    url = url.replace("http://" + host, "");
    url = url.replace("https://" + host, "");

    TreeMap<String, String> headers = new TreeMap<String, String>();
    headers.put("accept", accept);
    headers.put("date", getActualDateStr());

    log.debug("AUTHORIZE: " + action + "\\n\\n" + contentType + "\\n" + headers.get("date") + "\n");

    String canonicalHeaders = action + "\n\n" + contentType + "\n" + headers.get("date") + "\n";

    String messageToSign = canonicalHeaders + url;

    log.debug("publicKey=" + publicKey);
    log.debug("privateKey=" + privateKey);
    log.debug("messageToSign=" + messageToSign);

    SecretKeySpec privateKeySign = new SecretKeySpec(privateKey.getBytes(), "HmacSHA1");

    try {//from  w w  w . jav a  2 s  .c o m
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(privateKeySign);
        byte[] rawHmac = mac.doFinal(new String(messageToSign.getBytes(), "UTF-8").getBytes());

        byte[] signatureBytes = Base64.encodeBase64(rawHmac);

        String signature = new String(signatureBytes);

        String authorization = "CYTOMINE " + publicKey + ":" + signature;

        log.debug("signature=" + signature);
        log.debug("authorization=" + authorization);

        headers.put("authorization", authorization);

        for (String key : headers.keySet()) {
            addHeader(key, headers.get(key));
        }

    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }

}

From source file:n3phele.storage.swift.CloudStorageImpl.java

private final String signSwiftQueryString(String stringToSign, Credential credential) {
    try {/*from   w  ww.  java  2  s.c  o 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:com.zimbra.cs.account.ZimbraAuthToken.java

@Override
public String getCrumb() throws AuthTokenException {
    String authToken = getEncoded();
    try {/*from  ww w .  j  a v  a 2  s. c o  m*/
        ByteKey bk = new ByteKey(getCurrentKey().getKey());
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(bk);
        return new String(Hex.encodeHex(mac.doFinal(authToken.getBytes())));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("fatal error", e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("fatal error", e);
    }
}

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);/*  w  w  w.  j a v a 2  s  .c o m*/
    mac.update(data);
    return mac.doFinal();
}

From source file:com.emc.esu.api.rest.AbstractEsuRestApi.java

public String sign(byte[] input)
        throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec key = new SecretKeySpec(secret, "HmacSHA1");
    mac.init(key);//w  w w.j  a v  a  2 s . c om

    byte[] hashData = mac.doFinal(input);

    // Encode the hash in Base64.
    return new String(Base64.encodeBase64(hashData), "UTF-8");
}

From source file:com.thoughtworks.go.server.controller.AgentRegistrationControllerTest.java

private String token(String uuid, String tokenGenerationKey) {
    try {//w ww .j av a2  s  .  c  o m
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(tokenGenerationKey.getBytes(), "HmacSHA256");
        mac.init(secretKey);
        return Base64.getEncoder().encodeToString(mac.doFinal(uuid.getBytes()));
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new RuntimeException(e);
    }
}

From source file:ac.elements.io.Signature.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 * /*from  w w w.  j av  a 2 s.  c  om*/
 * @param data
 *            the data
 * @param key
 *            the key
 * @param algorithm
 *            the algorithm
 * 
 * @return the string
 * @throws SignatureException
 */
private static String sign(String data, String key, String algorithm) throws SignatureException {
    if (key == null)
        throw new SignatureException("Encoding key is null.");
    byte[] signature = null;
    try {
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key.getBytes(), algorithm));
        signature = Base64.encodeBase64(mac.doFinal(data.getBytes(DEFAULT_ENCODING)));
    } catch (Exception e) {
        log.error("Failed to generate signature: " + e.getMessage(), e);
    }

    return new String(signature);
}