List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal(byte[] input) throws IllegalStateException
From source file:com.auditmark.jscrambler.client.JScrambler.java
private String generateHMACSignature(String requestMethod, String resourcePath, Map<String, String> params) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException { String data = hmacSignatureData(requestMethod, resourcePath, apiHost, params); try {//from w ww .j ava 2 s . c o m SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); byte[] digest = mac.doFinal(data.getBytes()); return new sun.misc.BASE64Encoder().encode(digest); } catch (InvalidKeyException e) { System.err.println("Invalid key: " + e.getMessage()); throw e; } catch (NoSuchAlgorithmException e) { System.err.println("No such algorithm: " + e.getMessage()); throw e; } }
From source file:org.davidmendoza.fileUpload.web.VideoController.java
private String sign(String toSign) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException { Mac hmac = Mac.getInstance("HmacSHA1"); hmac.init(new SecretKeySpec(awsSecretKey.getBytes("UTF-8"), "HmacSHA1")); String signature = DatatypeConverter.printBase64Binary(hmac.doFinal(toSign.getBytes("UTF-8"))) .replaceAll("\n", ""); return signature; }
From source file:com.epl.ticketws.services.QueryService.java
/** * Signs a string with the given key.//w w w. ja v a2 s . co m * * @param data * @param key * @return * @throws SignatureException */ private String generate_HMAC_SHA1_Signature(String data, String key) throws SignatureException { String result; try { // get an hmac_sha1 key from the raw key bytes SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), HMAC_SHA1_ALGORITHM); // get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); mac.init(signingKey); // compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(data.getBytes(UTF_8)); //byte[] base64 = Base64.encodeBase64(rawHmac); byte[] base64 = Base64.getEncoder().encode(rawHmac); // base64-encode the hmac result = new String(base64); } catch (Exception e) { throw new SignatureException("Failed to generate HMAC : " + e.getMessage()); } return AUTHORIZATION_HEADER_HMAC_PREFIX + result; }
From source file:com.microsoft.azure.iot.service.auth.IotHubServiceSasToken.java
/** * Helper function to build the token string * * @return Valid token string/*from w w w . j ava 2 s.co m*/ */ private String buildToken() { String targetUri; try { // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)] targetUri = URLEncoder.encode(this.resourceUri.toLowerCase(), String.valueOf(StandardCharsets.UTF_8)); // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string (one year)] String toSign = targetUri + "\n" + this.expiryTime; // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256] // Get an hmac_sha1 key from the raw key bytes byte[] keyBytes = Base64.decodeBase64(this.keyValue.getBytes("UTF-8")); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256"); // Get an hmac_sha1 Mac instance and initialize with the signing key Mac mac = Mac.getInstance("HmacSHA256"); mac.init(signingKey); // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key] // Compute the hmac on input data bytes byte[] rawHmac = mac.doFinal(toSign.getBytes("UTF-8")); // Convert raw bytes to Hex String signature = URLEncoder.encode(Base64.encodeBase64String(rawHmac), "UTF-8"); // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"] String token = String.format(TOKEN_FORMAT, targetUri, signature, this.expiryTime, this.keyName); return token; } catch (Exception e) { // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_007: [The constructor shall throw Exception if building the token failed] throw new RuntimeException(e); } }
From source file:org.jets3t.service.utils.ServiceUtils.java
/** * Calculate the HMAC/SHA1 on a string.//w ww. j ava 2 s .co m * * @param awsSecretKey * AWS secret key. * @param canonicalString * canonical string representing the request to sign. * @return Signature * @throws ServiceException */ public static String signWithHmacSha1(String awsSecretKey, String canonicalString) throws ServiceException { if (awsSecretKey == null) { if (log.isDebugEnabled()) { log.debug("Canonical string will not be signed, as no AWS Secret Key was provided"); } return null; } // The following HMAC/SHA1 code for the signature is taken from the // AWS Platform's implementation of RFC2104 (amazon.webservices.common.Signature) // // Acquire an HMAC/SHA1 from the raw key bytes. SecretKeySpec signingKey = null; try { signingKey = new SecretKeySpec(awsSecretKey.getBytes(Constants.DEFAULT_ENCODING), Constants.HMAC_SHA1_ALGORITHM); } catch (UnsupportedEncodingException e) { throw new ServiceException("Unable to get bytes from secret string", e); } // Acquire the MAC instance and initialize with the signing key. Mac mac = null; try { mac = Mac.getInstance(Constants.HMAC_SHA1_ALGORITHM); } catch (NoSuchAlgorithmException e) { // should not happen throw new RuntimeException("Could not find sha1 algorithm", e); } try { mac.init(signingKey); } catch (InvalidKeyException e) { // also should not happen throw new RuntimeException("Could not initialize the MAC algorithm", e); } // Compute the HMAC on the digest, and set it. try { byte[] b64 = Base64.encodeBase64(mac.doFinal(canonicalString.getBytes(Constants.DEFAULT_ENCODING))); return new String(b64); } catch (UnsupportedEncodingException e) { throw new ServiceException("Unable to get bytes from canonical string", e); } }
From source file:ch.icclab.cyclops.client.CloudStackAuth.java
/** * Simple SHA1 implementation with Base64 encoding of message * * @param query header to be signed/*from w w w . j av a 2s . c o m*/ * @return signed string * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws UnsupportedEncodingException */ private String signRequest(String query) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { logger.trace("Signing the CloudStack API query"); Mac sha1_HMAC = Mac.getInstance("HmacSHA1"); SecretKeySpec secret = new SecretKeySpec(apiConnection.getCloudStackSecretKey().getBytes(), "HmacSHA1"); sha1_HMAC.init(secret); // now sign it and return Base64 representation String signature = Base64.encodeBase64String(sha1_HMAC.doFinal(query.getBytes())); return URLEncoder.encode(signature, "UTF-8"); }
From source file:co.edu.uniandes.csw.Arquidalgos.usuario.service.UsuarioService.java
@POST @Path("/agregarAmigos") public List<UsuarioDTO> agregarAmigos(UsuarioAmigosDTO usuarioAmigos) throws Exception { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); String key = "123"; SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256"); sha256_HMAC.init(secret_key);// w w w. j av a2 s. c o m String x = usuarioAmigos.toString(); System.out.println("TO String: " + x); String hash = Hex.encodeHexString(sha256_HMAC.doFinal(x.getBytes())); System.out.println("CODIGO HASH: " + hash); System.out.println("CODIGO HASH JSON " + usuarioAmigos.getHash()); boolean alterado = !(hash.equalsIgnoreCase(usuarioAmigos.getHash())); System.out.println("Alterado: " + alterado); if (alterado) { System.out.println("Alterado el sistema"); } return this.usuarioLogicService.agregarAmigos(usuarioAmigos); }
From source file:nl.esciencecenter.osmium.mac.MacScheme.java
/** * Computes RFC 2104-compliant HMAC signature. * * @param data//from w w w. j ava 2 s . c om * The data to be signed. * @param key * The signing key. * @param algorithm * MAC algorithm implemented by javax.crypto.MAC * @return The Base64-encoded RFC 2104-compliant HMAC signature. * @throws AuthenticationException * when signature generation fails */ private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException { try { Mac mac = Mac.getInstance(algorithm); SecretKeySpec macKey = new SecretKeySpec(key.getBytes(StandardCharsets.US_ASCII), "RAW"); mac.init(macKey); byte[] signature = mac.doFinal(data.getBytes(StandardCharsets.US_ASCII)); return Base64.encodeBase64String(signature); } catch (InvalidKeyException e) { throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AuthenticationException("Algorithm is not supported", e); } }
From source file:com.amediamanager.util.S3FormSigner.java
/** * The SignRequest method takes a set of AWS credentials and the S3 upload policy string and returns the encoded policy and the signature. * * @param creds the AWS credentials to be used for signing the request * @param policy the policy file to applied to the upload * @return an array of strings containing the base 64 encoded policy (index 0) and the signature (index 1). *///from w ww.j a v a2 s. c o m String[] signRequest(AWSCredentialsProvider credsProvider, String policy) { String[] policyAndSignature = new String[2]; try { // Create a Base64 encoded version of the policy string for placement in the form and // for use in signature generation. Returns are stripped out from the policy string. String encodedPolicy = new String( Base64.encodeBase64(policy.replaceAll("\n", "").replaceAll("\r", "").getBytes("UTF-8"))); // AWS signatures are generated using SHA1 HMAC signing. Mac hmac = Mac.getInstance("HmacSHA1"); // Generate the signature using the Secret Key from the AWS credentials hmac.init(new SecretKeySpec(credsProvider.getCredentials().getAWSSecretKey().getBytes("UTF-8"), "HmacSHA1")); String signature = new String(Base64.encodeBase64(hmac.doFinal(encodedPolicy.getBytes("UTF-8")))); // Pack the encoded policy and the signature into a string array policyAndSignature[0] = encodedPolicy; policyAndSignature[1] = signature; } catch (UnsupportedEncodingException e) { LOG.error("Unsupport encoding", e); } catch (NoSuchAlgorithmException e) { LOG.error("No such algorithm", e); } catch (InvalidKeyException e) { LOG.error("Invalid key", e); } return policyAndSignature; }