List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:uk.bowdlerize.API.java
private static String createSignatureHash(String value, String key) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { String type = "HmacSHA512"; SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type); Mac mac = Mac.getInstance(type); mac.init(secret);//from w ww .j a v a 2 s . c o m byte[] bytes = mac.doFinal(value.getBytes()); return bytesToHex(bytes); }
From source file:com.telesign.util.TeleSignRequest.java
/** * Creates the Signature component for the Authorization header field. * Uses your Secret Key to encode the stringToSign. * This is a <em>helper method</em>, used internally by the {@link TeleSignRequest#executeRequest()} method. * * @param data/*w w w . j av a 2 s. co m*/ * [Required] The stringToSign. * @param key * [Required] Your TeleSign API Key. Also known as your Secret * Key, and your Shared Cryptographic Key. It s a bese64-encoded * string value. * @return A String containing the Base64-encoded hash-based message * authentication code. * @throws java.security.SignatureException * Failed to generate HMAC. IllegalArgumentException - if * algorithm is null or key is null or empty. */ private String encode(String data, String key) throws java.security.SignatureException { String result; byte[] decoded_key = Base64.decodeBase64(key); try { // Get an hmac_sha key from the raw key bytes. SecretKeySpec signingKey = new SecretKeySpec(decoded_key, auth.value()); // Get an hmac_sha Mac instance, and initialize it with the signing key. Mac mac = Mac.getInstance(auth.value()); mac.init(signingKey); // Compute the HMAC on input data bytes. byte[] rawHmac = mac.doFinal(data.getBytes()); // Base64-encode the HMAC. result = new String(Base64.encodeBase64(rawHmac)); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return result; }
From source file:com.streamreduce.util.AWSClient.java
private String calculateSignature(String rawUrl, String key, Map<String, String> params) { StringBuilder canonical = new StringBuilder(); try {/*w ww. j a v a 2 s. co m*/ canonical.append("GET").append("\n"); canonical.append(new URL(rawUrl).getHost()).append("\n"); canonical.append("/").append("\n"); SortedMap<String, String> sorted = new TreeMap<>(params); canonical.append(getQueryString(sorted)); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256")); byte[] sign = mac.doFinal(canonical.toString().getBytes("UTF-8")); return new String(Base64.encodeBase64(sign)); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.microsoft.tfs.jni.internal.ntlm.JavaNTLM.java
private static byte[] ntlm2Hash(final String username, final String password, final String domain) throws NTLMException { // we must get the ntlmHash here, which depends on MD4 which // we sneakily implemented using Cryptix's implementation // this is a requirement for the ntlm2 response (unlike the // type3 ntlm response, which may work despite having no // ntlm message) final byte[] ntlmHash = ntlmHash(password); // we need the username and domain concatenated final byte[] usernameBytes = getBytes(username.toUpperCase(), "UTF-16LE"); //$NON-NLS-1$ final byte[] domainBytes = getBytes(domain.toUpperCase(), "UTF-16LE"); //$NON-NLS-1$ final byte[] usernameDomainBytes = new byte[usernameBytes.length + domainBytes.length]; int i;/*from ww w.j a v a 2 s .c om*/ for (i = 0; i < usernameBytes.length; i++) { usernameDomainBytes[i] = usernameBytes[i]; } for (int j = 0; j < domainBytes.length; j++) { usernameDomainBytes[i + j] = domainBytes[j]; } // ntlm2 hash is created by running HMAC-MD5 on the unicode // username and domain (uppercased), with the ntlmHash as a // key byte[] ntlm2Hash; try { final Mac mac = Mac.getInstance("HmacMD5"); //$NON-NLS-1$ mac.init(new SecretKeySpec(ntlmHash, "HmacMD5")); //$NON-NLS-1$ ntlm2Hash = mac.doFinal(usernameDomainBytes); } catch (final Exception e) { LOG.error("Could not load HmacMD5 for NTLM", e); //$NON-NLS-1$ throw new NTLMException(e.getMessage()); } return ntlm2Hash; }
From source file:de.andreas_rueckert.trade.site.anx.client.ANXClient.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. *//* ww w .j ava 2 s. co m*/ 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 { // Throw an error. throw new MissingAccountDataException("No user account given for " + _name + " request"); } // Check, if key and secret are available for the request. if (accountKey == null) { throw new MissingAccountDataException("Key not available for authenticated request to " + _name); } if (accountSecret == null) { throw new MissingAccountDataException("Secret not available for authenticated request to " + _name); } 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:com.streamreduce.util.AWSClient.java
private String calculateS3Signature(String rawUrl, String key, String date) { StringBuilder canonical = new StringBuilder(); try {/*from w w w. j a va2 s.c o m*/ canonical.append("GET").append("\n"); canonical.append("\n"); canonical.append("\n"); canonical.append(date).append("\n"); canonical.append(rawUrl); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1")); byte[] sign = mac.doFinal(canonical.toString().getBytes("UTF-8")); return new String(Base64.encodeBase64(sign)); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.apache.ws.security.message.token.UsernameToken.java
/** * Gets the secret key as per WS-Trust spec. * // ww w . j a va2s .c o m * @param keylen How many bytes to generate for the key * @param labelString the label used to generate the seed * @return a secret key constructed from information contained in this * username token */ public byte[] getSecretKey(int keylen, String labelString) { byte[] key = null; try { Mac mac = Mac.getInstance("HMACSHA1"); byte[] password; if (passwordsAreEncoded) { password = Base64.decode(rawPassword); } else { password = rawPassword.getBytes("UTF-8"); // enhancement by Alberto Coletti } byte[] label = labelString.getBytes("UTF-8"); byte[] nonce = Base64.decode(getNonce()); byte[] created = getCreated().getBytes("UTF-8"); byte[] seed = new byte[label.length + nonce.length + created.length]; int offset = 0; System.arraycopy(label, 0, seed, offset, label.length); offset += label.length; System.arraycopy(nonce, 0, seed, offset, nonce.length); offset += nonce.length; System.arraycopy(created, 0, seed, offset, created.length); key = P_hash(password, seed, mac, keylen); if (LOG.isDebugEnabled()) { LOG.debug("password :" + Base64.encode(password)); LOG.debug("label :" + Base64.encode(label)); LOG.debug("nonce :" + Base64.encode(nonce)); LOG.debug("created :" + Base64.encode(created)); LOG.debug("seed :" + Base64.encode(seed)); LOG.debug("Key :" + Base64.encode(key)); } } catch (Exception e) { if (DO_DEBUG) { LOG.debug(e.getMessage(), e); } return null; } return key; }
From source file:com.sangupta.jerry.oauth.OAuthUtils.java
/** * Generate the signature using the given signing method for the signable * using the key string. For OAuth the key string should already be * URI-percent-encoded if need be./*from w ww. j av a 2s . co m*/ * * @param signable * the string for which the signature needs to be generated * * @param keyString * the key string to be used * * @param signingMethod * the signing method to be used * * @return the signature generated, or <code>null</code> if some exception * occurs * * @throws NullPointerException * if the signable string is <code>null</code>/empty. */ public static String createSignature(String signable, String keyString, OAuthSignatureMethod signingMethod) { if (AssertUtils.isEmpty(signable)) { throw new IllegalArgumentException("Signable string cannot be null/empty"); } if (signingMethod == OAuthSignatureMethod.PLAIN_TEXT) { return keyString; } SecretKeySpec key = new SecretKeySpec((keyString).getBytes(StringUtils.CHARSET_UTF8), signingMethod.getAlgorithmName()); Mac mac; try { mac = Mac.getInstance(signingMethod.getAlgorithmName()); mac.init(key); byte[] bytes = mac.doFinal(signable.getBytes(StringUtils.CHARSET_UTF8)); return Base64Encoder.encodeToString(bytes, false); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } return null; }
From source file:org.dasein.cloud.skeleton.RESTMethod.java
private @Nonnull String getSignature(@Nonnull byte[] accessKey, @Nonnull byte[] privateKey, @Nonnull String method, @Nonnull String resource, @Nullable String id, long timestamp) throws InternalException { // TODO: implement this for real; this is the signature code for the enStratus API (sorta) try {/* ww w .j a v a 2s . c o m*/ String stringToSign = (new String(accessKey, "utf-8")) + ":" + method; if (resource.startsWith("/")) { stringToSign = stringToSign + resource; } else { stringToSign = stringToSign + "/" + resource; } if (id != null) { if (id.startsWith("/")) { stringToSign = stringToSign + id; } else { stringToSign = stringToSign + "/" + id; } } stringToSign = stringToSign + ":" + timestamp + ":Dasein Cloud"; try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(privateKey, "HmacSHA256")); return new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes("utf-8")))); } catch (NoSuchAlgorithmException e) { throw new InternalException(e); } catch (InvalidKeyException e) { throw new InternalException(e); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } }
From source file:com.algolia.search.saas.APIClient.java
static String hmac(String key, String msg) { Mac hmac;/*from w ww. ja v a 2 s . c o m*/ try { hmac = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException e) { throw new Error(e); } try { hmac.init(new SecretKeySpec(key.getBytes(), "HmacSHA256")); } catch (InvalidKeyException e) { throw new Error(e); } byte[] rawHmac = hmac.doFinal(msg.getBytes()); byte[] hexBytes = new Hex().encode(rawHmac); return new String(hexBytes); }