List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal(byte[] input) throws IllegalStateException
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private static byte[] signMessage(byte[] data, byte[] key, String algorithm) throws InvalidKeyException, NoSuchAlgorithmException { Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key, algorithm)); return mac.doFinal(data); }
From source file:com.google.acre.script.HostEnv.java
@JSFunction public String hmac(String algorithm, String key, String data, boolean to_hex) { try {/*w w w . j a va 2s . c o m*/ SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(signingKey); if (to_hex) { return new String(Hex.encodeHex(mac.doFinal(data.getBytes()))); } else { return new String(Base64.encodeBase64(mac.doFinal(data.getBytes()))); } } catch (InvalidKeyException e) { throw new JSConvertableException("Invalid key: " + key).newJSException(this); } catch (NoSuchAlgorithmException e) { throw new JSConvertableException("Unable to load algoritm: " + algorithm).newJSException(this); } }
From source file:org.dasein.cloud.azure.AzureStorageMethod.java
private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method, @Nonnull Map<String, String> queryParams) throws CloudException, InternalException { fetchKeys();//w w w . jav a 2 s.c om ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new AzureConfigException("No context was specified for this request"); } Header h = method.getFirstHeader("content-type"); String contentType = (h == null ? null : h.getValue()); if (contentType == null) { contentType = ""; } StringBuilder stringToSign = new StringBuilder(); stringToSign.append(method.getMethod().toUpperCase()).append("\n"); stringToSign.append("\n"); // content-md5 stringToSign.append(contentType).append("\n"); stringToSign.append(method.getFirstHeader("date").getValue()).append("\n"); Header[] headers = method.getAllHeaders(); TreeSet<String> keys = new TreeSet<String>(); for (Header header : headers) { if (header.getName().startsWith(Header_Prefix_MS)) { keys.add(header.getName().toLowerCase()); } } for (String key : keys) { Header header = method.getFirstHeader(key); if (header != null) { Header[] all = method.getHeaders(key); stringToSign.append(key.toLowerCase().trim()).append(":"); if (all != null && all.length > 0) { for (Header current : all) { String v = (current.getValue() != null ? current.getValue() : ""); stringToSign.append(v.trim().replaceAll("\n", " ")).append(","); } } stringToSign.deleteCharAt(stringToSign.lastIndexOf(",")); } else { stringToSign.append(key.toLowerCase().trim()).append(":"); } stringToSign.append("\n"); } stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath()); keys.clear(); for (String key : queryParams.keySet()) { if (key.equalsIgnoreCase("comp")) { key = key.toLowerCase(); keys.add(key); } } if (!keys.isEmpty()) { stringToSign.append("?"); for (String key : keys) { String value = queryParams.get(key); if (value == null) { value = ""; } stringToSign.append(key).append("=").append(value).append("&"); } stringToSign.deleteCharAt(stringToSign.lastIndexOf("&")); } try { if (logger.isDebugEnabled()) { logger.debug("BEGIN STRING TO SIGN"); logger.debug(stringToSign.toString()); logger.debug("END STRING TO SIGN"); } Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256")); String signature = new String( Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8")))); if (logger.isDebugEnabled()) { logger.debug("signature=" + signature); } return signature; } catch (UnsupportedEncodingException e) { logger.error("UTF-8 not supported: " + e.getMessage()); throw new InternalException(e); } catch (NoSuchAlgorithmException e) { logger.error("No such algorithm: " + e.getMessage()); throw new InternalException(e); } catch (InvalidKeyException e) { logger.error("Invalid key: " + e.getMessage()); throw new InternalException(e); } }
From source file:org.dasein.cloud.aws.AWSCloud.java
private String sign(byte[] key, String authString, String algorithm) throws InternalException { try {// ww w .j a v a 2s . com Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key, algorithm)); return new String(Base64.encodeBase64(mac.doFinal(authString.getBytes("utf-8")))); } catch (NoSuchAlgorithmException e) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } catch (InvalidKeyException e) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } catch (IllegalStateException e) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } catch (UnsupportedEncodingException e) { logger.error(e); e.printStackTrace(); throw new InternalException(e); } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
/** * Create Amazon V2 signature. Reference: * http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html *///from w ww. ja v a2 s . c om private static String createAuthorizationSignature(HttpServletRequest request, String uri, String credential) { // sort Amazon headers SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create(); for (String headerName : Collections.list(request.getHeaderNames())) { Collection<String> headerValues = Collections.list(request.getHeaders(headerName)); headerName = headerName.toLowerCase(); if (!headerName.startsWith("x-amz-")) { continue; } if (headerValues.isEmpty()) { canonicalizedHeaders.put(headerName, ""); } for (String headerValue : headerValues) { canonicalizedHeaders.put(headerName, Strings.nullToEmpty(headerValue)); } } // build string to sign StringBuilder builder = new StringBuilder().append(request.getMethod()).append('\n') .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_MD5))).append('\n') .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_TYPE))).append('\n'); String expires = request.getParameter("Expires"); if (expires != null) { builder.append(expires); } else if (!canonicalizedHeaders.containsKey("x-amz-date")) { builder.append(request.getHeader(HttpHeaders.DATE)); } builder.append('\n'); for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) { builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n'); } builder.append(uri); char separator = '?'; List<String> subresources = Collections.list(request.getParameterNames()); Collections.sort(subresources); for (String subresource : subresources) { if (SIGNED_SUBRESOURCES.contains(subresource)) { builder.append(separator).append(subresource); String value = request.getParameter(subresource); if (!"".equals(value)) { builder.append('=').append(value); } separator = '&'; } } String stringToSign = builder.toString(); logger.trace("stringToSign: {}", stringToSign); // sign string Mac mac; try { mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1")); } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))); }
From source file:com.emc.esu.test.EsuApiTest.java
@Test public void testHmac() throws Exception { // Compute the signature hash String input = "Hello World"; byte[] secret = Base64.decodeBase64("D7qsp4j16PBHWSiUbc/bt3lbPBY=".getBytes("UTF-8")); Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec key = new SecretKeySpec(secret, "HmacSHA1"); mac.init(key);//w w w . j a v a 2s. co m l4j.debug("Hashing: \n" + input.toString()); byte[] hashData = mac.doFinal(input.toString().getBytes("ISO-8859-1")); // Encode the hash in Base64. String hashOut = new String(Base64.encodeBase64(hashData), "UTF-8"); l4j.debug("Hash: " + hashOut); }
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 ww .j a v a 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 { // 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: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. *//*from w ww . j av a2s .c o 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:org.gaul.s3proxy.S3ProxyHandler.java
private void handlePostBlob(HttpServletRequest request, HttpServletResponse response, InputStream is, BlobStore blobStore, String containerName) throws IOException, S3Exception { String boundaryHeader = request.getHeader(HttpHeaders.CONTENT_TYPE); if (boundaryHeader == null || !boundaryHeader.startsWith("multipart/form-data; boundary=")) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return;// w w w.j a va2 s.c o m } String boundary = boundaryHeader.substring(boundaryHeader.indexOf('=') + 1); String blobName = null; String contentType = null; String identity = null; // TODO: handle policy byte[] policy = null; String signature = null; byte[] payload = null; MultipartStream multipartStream = new MultipartStream(is, boundary.getBytes(StandardCharsets.UTF_8), 4096, null); boolean nextPart = multipartStream.skipPreamble(); while (nextPart) { String header = multipartStream.readHeaders(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { multipartStream.readBodyData(baos); if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"acl\"")) { // TODO: acl } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"AWSAccessKeyId\"")) { identity = new String(baos.toByteArray()); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"Content-Type\"")) { contentType = new String(baos.toByteArray()); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"file\"")) { // TODO: buffers entire payload payload = baos.toByteArray(); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"key\"")) { blobName = new String(baos.toByteArray()); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"policy\"")) { policy = baos.toByteArray(); } else if (startsWithIgnoreCase(header, "Content-Disposition: form-data;" + " name=\"signature\"")) { signature = new String(baos.toByteArray()); } } nextPart = multipartStream.readBoundary(); } if (identity == null || signature == null || blobName == null || policy == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } Map.Entry<String, BlobStore> provider = blobStoreLocator.locateBlobStore(identity, null, null); if (provider == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } String credential = provider.getKey(); Mac mac; try { mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1")); } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } String expectedSignature = BaseEncoding.base64().encode(mac.doFinal(policy)); if (!signature.equals(expectedSignature)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } BlobBuilder.PayloadBlobBuilder builder = blobStore.blobBuilder(blobName).payload(payload); if (contentType != null) { builder.contentType(contentType); } Blob blob = builder.build(); blobStore.putBlob(containerName, blob); response.setStatus(HttpServletResponse.SC_NO_CONTENT); }
From source file:com.emc.atmos.api.test.AtmosApiClientTest.java
@Test public void testHmac() throws Exception { // Compute the signature hash String input = "Hello World"; byte[] secret = Base64.decodeBase64("D7qsp4j16PBHWSiUbc/bt3lbPBY=".getBytes("UTF-8")); Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec key = new SecretKeySpec(secret, "HmacSHA1"); mac.init(key);/*from w w w. j a va 2s. c o m*/ l4j.debug("Hashing: \n" + input); byte[] hashData = mac.doFinal(input.getBytes("ISO-8859-1")); // Encode the hash in Base64. String hashOut = new String(Base64.encodeBase64(hashData), "UTF-8"); l4j.debug("Hash: " + hashOut); }