List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal(byte[] input) throws IllegalStateException
From source file:com.stackmob.sdk.api.StackMobSession.java
public String generateMacToken(String method, String uri, String host, String port) { String ts = String.valueOf(new Date().getTime() / 1000); String nonce = String.format("n%d", Math.round(Math.random() * 10000)); try {/*from w w w . j a v a 2 s . c o m*/ String baseString = getNormalizedRequestString(ts, nonce, method, uri, host, port); Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); SecretKeySpec spec = new SecretKeySpec(oauth2MacKey.getBytes(), SIGNATURE_ALGORITHM); try { mac.init(spec); } catch (InvalidKeyException ike) { throw new IllegalStateException(ike); } byte[] rawMacBytes = mac.doFinal(baseString.getBytes()); byte[] b64Bytes = Base64.encodeBase64(rawMacBytes); String calculatedMac = new String(b64Bytes); return String.format("MAC id=\"%s\",ts=\"%s\",nonce=\"%s\",mac=\"%s\"", oauth2Token, ts, nonce, calculatedMac); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("This device doesn't have SHA1"); } }
From source file:com.sk89q.craftapi.auth.ConfigurationAuthentication.java
/** * Verify username and password pairs using a HMAC digest. * * @param username//from w w w . ja va2 s . c o m * @param password * @return */ public boolean verifyCredentials(Mac mac, String username, byte[] digest) { List credentials = config.configurationsAt("credential"); for (Object c : credentials) { HierarchicalConfiguration credential = (HierarchicalConfiguration) c; String user = credential.getString("username"); String pass = credential.getString("password"); if (user != null && pass != null && user.equals(username) && implementsService(credential)) { byte[] testDigest = mac.doFinal(pass.getBytes()); if (Arrays.equals(testDigest, digest)) { return true; } } } return false; }
From source file:com.mozilla.simplepush.simplepushdemoapp.MainActivity.java
private String genSignature(UrlEncodedFormEntity body) throws IOException { String content = EntityUtils.toString(body); SecretKeySpec key = new SecretKeySpec(this.SharedSecret.getBytes("UTF-8"), "HmacSHA256"); try {//from w w w .j a v a 2 s .c o m Mac mac = Mac.getInstance("HmacSHA256"); mac.init(key); byte[] bytes = mac.doFinal(content.getBytes("UTF-8")); return bytesToHex(bytes); } catch (NoSuchAlgorithmException x) { this.err("Invalid hash algo specified, failing " + x.toString()); throw new IOException("HmacSHA256 unavailable"); } catch (InvalidKeyException x) { this.err("Invalid key specified, failing " + x.toString()); throw new IOException("Invalid Key"); } }
From source file:org.mla.cbox.shibboleth.idp.authn.impl.ValidateUsernamePasswordAgainstMlaRest.java
/** {@inheritDoc} */ @Override//from www . ja va2s.c o m protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { log.debug("{} Attempting to authenticate user {}", getLogPrefix(), getUsernamePasswordContext().getUsername()); try { // Construct the URL composed of the API root, members method with id value equal // to the username entered in the login form, the API key, and time stamp. StringBuilder urlBuilder = new StringBuilder().append(this.apiRoot).append("members/") .append(getUsernamePasswordContext().getUsername()).append("?").append("key=") .append(this.apiKey).append("×tamp=") .append(String.valueOf(Instant.now().getEpochSecond())); // The signature is created by prepending the GET method with a '&' separator to the // URL and then computing the SHA256 HMAC hash using the key. // StringBuilder baseStringBuilder = new StringBuilder().append("GET").append("&") .append(UriUtils.encode(urlBuilder.toString(), "UTF-8")); Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKey = new SecretKeySpec(this.apiSecret.getBytes("UTF-8"), "HmacSHA256"); sha256_HMAC.init(secretKey); String signature = Hex .encodeHexString(sha256_HMAC.doFinal(baseStringBuilder.toString().getBytes("UTF-8"))); // Append the signature to the URL. urlBuilder.append("&signature=").append(signature); log.debug("{} MLA query URL is {}", getLogPrefix(), urlBuilder.toString()); // Query the MLA API HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { /* Set default parser as a JSON parser to make casting to class instance easier */ request.setParser(new JsonObjectParser(JSON_FACTORY)); } }); HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(urlBuilder.toString())); HttpResponse response = request.execute(); // Parse the response and create an instance of the MLAMemberObject. MLAMemberObject mlaMembership = response.parseAs(MLAMemberObject.class); List<MLAMemberObjectData> data = mlaMembership.getData(); // The data element, if present, is a list. If not present then the size of the list // is zero and this indicates that the username could not be found. if (data.size() < 1) { log.info("{} User {} is not known to MLA", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Parse out the id, username, password hash, and membership status. String memberId = data.get(0).getId(); String username = data.get(0).getAuthentication().getUsername(); String passwordHash = data.get(0).getAuthentication().getPassword(); String membershipStatus = data.get(0).getAuthentication().getMembership_status(); log.debug("{} MLA returned member Id {}", getLogPrefix(), memberId); log.debug("{} MLA returned username {}", getLogPrefix(), username); log.debug("{} MLA returned password hash {}", getLogPrefix(), passwordHash); log.debug("{} MLA returned membership status {}", getLogPrefix(), membershipStatus); // Non-active members cannot authenticate. if (!new String("active").equals(membershipStatus)) { log.info("{} User {} does not have active status", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } // Compute the bcrypt hash of the password using the salt sent by the MLA API. String pw_hash = BCrypt.hashpw(getUsernamePasswordContext().getPassword(), passwordHash); log.debug("{} Computed hash {}", getLogPrefix(), pw_hash); // Compare the input username with the password hash returned by the MLA API. if (!pw_hash.equals(passwordHash)) { log.info("{} Invalid password", getLogPrefix(), getUsernamePasswordContext().getUsername()); handleError(profileRequestContext, authenticationContext, AuthnEventIds.INVALID_CREDENTIALS, AuthnEventIds.INVALID_CREDENTIALS); return; } // Set the username in the context directly because the user may have typed the member number // into the form rather than the username. The member number will work for authentication, // but we always want to return the username as the principal. getUsernamePasswordContext().setUsername(username); // Build the authentication result and proceed. log.info("{} Login by '{}' succeeded", getLogPrefix(), getUsernamePasswordContext().getUsername()); buildAuthenticationResult(profileRequestContext, authenticationContext); ActionSupport.buildProceedEvent(profileRequestContext); // } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | InterruptedException e) { } catch (IOException | NoSuchAlgorithmException | InvalidKeyException e) { log.warn("{} Login by {} produced exception", getLogPrefix(), getUsernamePasswordContext().getUsername(), e); handleError(profileRequestContext, authenticationContext, e, AuthnEventIds.AUTHN_EXCEPTION); } }
From source file:com.googlesource.gerrit.plugins.github.notification.WebhookServlet.java
/** * Calculates the expected signature of the payload * * @param payload payload to calculate a signature for * @return signature of the payload//from w w w .j av a 2s .c om * @see <a href= * "https://developer.github.com/webhooks/securing/#validating-payloads-from-github"> * Validating payloads from GitHub</a> */ private byte[] getExpectedSignature(byte[] payload) { SecretKeySpec key = new SecretKeySpec(config.webhookSecret.getBytes(), HMAC_SHA1_ALGORITHM); Mac hmac; try { hmac = Mac.getInstance(HMAC_SHA1_ALGORITHM); hmac.init(key); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Hmac SHA1 must be supported", e); } catch (InvalidKeyException e) { throw new IllegalStateException("Hmac SHA1 must be compatible to Hmac SHA1 Secret Key", e); } return hmac.doFinal(payload); }
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 {/*w w w .j a va2 s. co 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:com.thoughtworks.go.server.controller.AgentRegistrationControllerTest.java
private String token(String uuid, String tokenGenerationKey) { try {/* w ww . j av a 2 s .co 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:org.dasein.cloud.aws.AWSCloud.java
static public byte[] HmacSHA256(String data, byte[] key) throws InternalException { final String algorithm = "HmacSHA256"; Mac mac; try {//w w w. ja va 2s .c o m mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key, algorithm)); return mac.doFinal(data.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { throw new InternalException(e); } catch (InvalidKeyException e) { throw new InternalException(e); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } }
From source file:org.apache.nifi.web.security.jwt.JwtServiceTest.java
private String generateHMAC(String hmacSecret, String body) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(hmacSecret.getBytes("UTF-8"), "HmacSHA256"); hmacSHA256.init(secret_key);//from w w w . jav a2 s . co m return Base64.encodeBase64URLSafeString(hmacSHA256.doFinal(body.getBytes("UTF-8"))); }