List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java
/** * @throws NoSuchAlgorithmException/*from www .jav a 2 s.com*/ * @throws InvalidKeyException * @throws UnsupportedEncodingException * @throws IllegalStateException * @throws NullPointerException if <code>tokenFile</code> is * <code>null</code>. */ TokenStore(final File tokenFile, final long sessionTimeout, final boolean fastSeed) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException { if (tokenFile == null) { throw new NullPointerException("tokenfile"); } this.random = SecureRandom.getInstance(SHA1PRNG); this.ttl = sessionTimeout; this.tokenFile = tokenFile; this.tmpTokenFile = new File(tokenFile + ".tmp"); // prime the secret keys from persistence loadTokens(); // warm up the crypto API if (fastSeed) { random.setSeed(getFastEntropy()); } else { log.info("Seeding the secure random number generator can take " + "up to several minutes on some operating systems depending " + "upon environment factors. If this is a problem for you, " + "set the system property 'java.security.egd' to " + "'file:/dev/./urandom' or enable the Fast Seed Generator " + "in the Web Console"); } byte[] b = new byte[20]; random.nextBytes(b); final SecretKey secretKey = new SecretKeySpec(b, HMAC_SHA1); final Mac m = Mac.getInstance(HMAC_SHA1); m.init(secretKey); m.update(UTF_8.getBytes(UTF_8)); m.doFinal(); }
From source file:com.dongwookchung.nutritioncalculator.FatSecretAPI.java
/** * Returns signature generated using signature base as text and consumer secret as key * * @param method//from w w w . j av a2 s .c o m * Http method * @param uri * Request URL - http://platform.fatsecret.com/rest/server.api (Always remains the same) * @param params * An array of parameter values as "key=value" pair * * @return oauth_signature which will be added to request for calling fatsecret api */ public String sign(String method, String uri, String[] params) throws UnsupportedEncodingException { String encodedURI = encode(uri); String encodedParams = encode(paramify(params)); String[] p = { method, encodedURI, encodedParams }; String text = join(p, "&"); String key = APP_SECRET + "&"; SecretKey sk = new SecretKeySpec(key.getBytes(), APP_SIGNATURE_METHOD); String sign = ""; try { Mac m = Mac.getInstance(APP_SIGNATURE_METHOD); m.init(sk); sign = encode(new String(Base64.encode(m.doFinal(text.getBytes()), Base64.DEFAULT)).trim()); } catch (java.security.NoSuchAlgorithmException e) { } catch (java.security.InvalidKeyException e) { } return sign; }
From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java
/** * Signs a request with a secret// www . ja v a 2 s .c om * * @param secret * @param hash_data * @return */ private String signRequest(String secret, String hash_data) { String signature = ""; try { Mac mac = Mac.getInstance(Constants.SIGN_HASH_FUNCTION); SecretKeySpec secret_spec = new SecretKeySpec(Base64.decodeBase64(secret), Constants.SIGN_HASH_FUNCTION); mac.init(secret_spec); signature = Base64.encodeBase64String(mac.doFinal(hash_data.getBytes())); } catch (NoSuchAlgorithmException | InvalidKeyException e) { Logger.getLogger(MtGoxTradeService.class.getName()).log(Level.SEVERE, null, e); } return signature; }
From source file:org.mla.cbox.shibboleth.idp.authn.impl.ValidateUsernamePasswordAgainstMlaRest.java
/** {@inheritDoc} */ @Override/*from w w w. ja v a 2 s. c om*/ 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.axelor.apps.account.service.payment.PayboxService.java
/** * Fonction calculant la signature HMAC des paramtres * @param data/*from ww w .j ava 2s .c o m*/ * La chaine contenant les paramtres * @param hmacKey * La cl HMAC * @param algorithm * L'algorithme utilis (SHA512, ...) * @return * @throws AxelorException */ public String getHmacSignature(String data, String hmacKey, String algorithm) throws AxelorException { try { byte[] bytesKey = DatatypeConverter.parseHexBinary(hmacKey); SecretKeySpec secretKey = new SecretKeySpec(bytesKey, "Hmac" + algorithm); Mac mac = Mac.getInstance("Hmac" + algorithm); mac.init(secretKey); byte[] macData = mac.doFinal(data.getBytes(this.CHARSET)); // final byte[] hex = new Hex().encode( macData ); // return new String( hex, this.CHARSET ); // LOG.debug("Message HMAC 2 : {}",new String( hex, this.CHARSET )); String s = StringTool.getHexString(macData); return s.toUpperCase(); } catch (InvalidKeyException e) { throw new AxelorException(String.format("%s :\n %s", GeneralServiceImpl.EXCEPTION, e), IException.INCONSISTENCY); } catch (NoSuchAlgorithmException e) { throw new AxelorException(String.format("%s :\n %s", GeneralServiceImpl.EXCEPTION, e), IException.INCONSISTENCY); } catch (UnsupportedEncodingException e) { throw new AxelorException(String.format("%s :\n %s", GeneralServiceImpl.EXCEPTION, e), IException.INCONSISTENCY); } }
From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java
private PKIMessage protectPKIMessageWithHMAC(PKIMessage msg, boolean badObjectId, String password, int iterations) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException { // Create the PasswordBased protection of the message PKIHeaderBuilder head = getHeaderBuilder(msg.getHeader()); // SHA1/*from ww w . j a v a 2 s . c o m*/ AlgorithmIdentifier owfAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26")); // 567 iterations int iterationCount = iterations; ASN1Integer iteration = new ASN1Integer(iterationCount); // HMAC/SHA1 AlgorithmIdentifier macAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.113549.2.7")); byte[] salt = "foo123".getBytes(); DEROctetString derSalt = new DEROctetString(salt); // Create the new protected return message String objectId = "1.2.840.113533.7.66.13"; if (badObjectId) { objectId += ".7"; } PBMParameter pp = new PBMParameter(derSalt, owfAlg, iteration, macAlg); AlgorithmIdentifier pAlg = new AlgorithmIdentifier(new ASN1ObjectIdentifier(objectId), pp); head.setProtectionAlg(pAlg); PKIHeader header = head.build(); // Calculate the protection bits byte[] raSecret = password.getBytes(); byte[] basekey = new byte[raSecret.length + salt.length]; System.arraycopy(raSecret, 0, basekey, 0, raSecret.length); for (int i = 0; i < salt.length; i++) { basekey[raSecret.length + i] = salt[i]; } // Construct the base key according to rfc4210, section 5.1.3.1 MessageDigest dig = MessageDigest.getInstance(owfAlg.getAlgorithm().getId(), "BC"); for (int i = 0; i < iterationCount; i++) { basekey = dig.digest(basekey); dig.reset(); } // For HMAC/SHA1 there is another oid, that is not known in BC, but the // result is the same so... String macOid = macAlg.getAlgorithm().getId(); PKIBody body = msg.getBody(); byte[] protectedBytes = getProtectedBytes(header, body); Mac mac = Mac.getInstance(macOid, "BC"); SecretKey key = new SecretKeySpec(basekey, macOid); mac.init(key); mac.reset(); mac.update(protectedBytes, 0, protectedBytes.length); byte[] out = mac.doFinal(); DERBitString bs = new DERBitString(out); return new PKIMessage(header, body, bs); }
From source file:mitm.application.djigzo.james.mailets.PDFReplyURLBuilder.java
private Mac createMAC() throws URLBuilderException { SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory(); try {//w w w. j a v a 2 s. c om Mac mac = securityFactory.createMAC(algorithm); SecretKeySpec keySpec = new SecretKeySpec(MiscStringUtils.toUTF8Bytes(key), "raw"); mac.init(keySpec); return mac; } catch (NoSuchAlgorithmException e) { throw new URLBuilderException(e); } catch (NoSuchProviderException e) { throw new URLBuilderException(e); } catch (InvalidKeyException e) { throw new URLBuilderException(e); } }
From source file:org.egov.collection.integration.pgi.AxisAdaptor.java
private String hashAllFields(final LinkedHashMap<String, String> fields) { final String axisSecureSecret = collectionApplicationProperties.axisSecureSecret(); byte[] decodedKey; byte[] hashValue = null; // Sort list with field names ascending order final List<String> fieldNames = new ArrayList<>(fields.keySet()); Collections.sort(fieldNames); // iterate through field name list and generate message for hashing. Format: fieldname1=fieldvale1?fieldname2=fieldvalue2 final Iterator<String> itr = fieldNames.iterator(); final StringBuilder hashingMessage = new StringBuilder(); int i = 0;/*from w ww. java 2 s. c o m*/ while (itr.hasNext()) { final String fieldName = itr.next(); final String fieldValue = fields.get(fieldName); if (fieldValue != null && fieldValue.length() > 0) { if (i != 0) hashingMessage.append("&"); hashingMessage.append(fieldName).append("=").append(fieldValue); i++; } } try { decodedKey = Hex.decodeHex(axisSecureSecret.toCharArray()); SecretKeySpec keySpec = new SecretKeySpec(decodedKey, "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); byte[] hashingMessageBytes = hashingMessage.toString().getBytes(UTF8); hashValue = mac.doFinal(hashingMessageBytes); } catch (DecoderException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return DatatypeConverter.printHexBinary(hashValue); }
From source file:com.thoughtworks.go.server.controller.AgentRegistrationControllerTest.java
private String token(String uuid, String tokenGenerationKey) { try {//from w ww.jav a2 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.alfresco.encryption.MACUtils.java
protected Mac getMac(String keyAlias) throws Exception { Mac mac = threadMac.get(); if (mac == null) { mac = Mac.getInstance(macAlgorithm); threadMac.set(mac);/*from ww w . java 2 s .co m*/ } Key key = keyProvider.getKey(keyAlias); if (key == null) { throw new AlfrescoRuntimeException("Unexpected null key for key alias " + keyAlias); } mac.init(key); return mac; }