List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:com.muk.ext.security.impl.DefaultNonceService.java
private String hash(String salt, String payload) throws NoSuchAlgorithmException, InvalidKeyException { Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secret_key = new SecretKeySpec(salt.getBytes(), "HmacSHA256"); sha256_HMAC.init(secret_key); return Base64.encodeBase64URLSafeString(sha256_HMAC.doFinal(payload.getBytes())); }
From source file:com.eucalyptus.objectstorage.pipeline.WalrusSoapUserAuthenticationHandler.java
protected String checkSignature(final String queryKey, final String subject) throws AuthenticationException { SecretKeySpec signingKey = new SecretKeySpec(queryKey.getBytes(), Hmac.HmacSHA1.toString()); try {/*w w w. ja v a 2s . co m*/ Mac mac = Hmac.HmacSHA1.getInstance(); mac.init(signingKey); byte[] rawHmac = mac.doFinal(subject.getBytes()); return new String(Base64.encode(rawHmac)).replaceAll("=", ""); } catch (Exception e) { LOG.error(e, e); throw new AuthenticationException("Failed to compute signature"); } }
From source file:net.sourceforge.vulcan.web.SignedRequestAuthorizationFilter.java
@Override protected void initFilterBean() throws ServletException { if (StringUtils.isBlank(sharedSecret)) { secretKey = null;/*from ww w . j a v a 2s .c o m*/ return; } try { secretKey = new SecretKeySpec(sharedSecret.getBytes(), algorithm); // Initialize a mac instance to fail fast on NoSuchAlgorithmException or InvalidKeyException. // This way any configuration errors will prevent the application from starting instead of causing // problems later. final Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } catch (InvalidKeyException e) { throw new ServletException(e); } }
From source file:net.alegen.datpass.library.crypto.CryptoManager.java
public String generateHmac(EncryptionOutput encryptionOutput, String password) { final String ctext = encryptionOutput.getCypherText(); final String salt = encryptionOutput.getSalt(); final String iv = encryptionOutput.getIV(); try {//from w ww. ja va 2 s .c o m // create the hmac key and message MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] hmacKey = md.digest(password.getBytes("UTF-8")); byte[] hmacMessage = (iv + ctext + salt).getBytes("UTF-8"); // generate hmac SecretKeySpec keySpec = new SecretKeySpec(hmacKey, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec); byte[] result = mac.doFinal(hmacMessage); // return result result = Base64.encodeBase64(result); return new String(result, "UTF-8"); } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) { log.error("An error occured while generating an HMAC value."); return null; } }
From source file:com.emc.vipr.ribbon.ViPRDataServicesServerList.java
protected String getSignature(String canonicalString, String secret) throws Exception { Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1")); String signature = new String(Base64.encodeBase64(mac.doFinal(canonicalString.getBytes("UTF-8")))); logger.debug("canonicalString:\n" + canonicalString); logger.debug("signature:\n" + signature); return signature; }
From source file:org.dasein.cloud.qingcloud.util.requester.QingCloudRequestBuilder.java
private String doMac(byte[] accessKeySecret, String stringToSign) throws InternalException { String signature;//from w ww. j av a2s. com try { Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); mac.init(new SecretKeySpec(accessKeySecret, SIGNATURE_ALGORITHM)); byte[] signedData = mac.doFinal(stringToSign.getBytes(ENCODING)); signature = new String(Base64.encodeBase64(signedData)); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { logger.error("AliyunRequestBuilderStrategy.sign() failed due to algorithm not supported: " + noSuchAlgorithmException.getMessage()); throw new InternalException(noSuchAlgorithmException); } catch (InvalidKeyException invalidKeyException) { logger.error("AliyunRequestBuilderStrategy.sign() failed due to key invalid: " + invalidKeyException.getMessage()); throw new InternalException(invalidKeyException); } catch (UnsupportedEncodingException unsupportedEncodingException) { logger.error("AliyunMethod.sign() failed due to encoding not supported: " + unsupportedEncodingException.getMessage()); throw new InternalException(unsupportedEncodingException); } return signature; }
From source file:fitmon.DietAPI.java
public ArrayList<ArrayList<Food>> searchFood(String foodName) throws InvalidKeyException, NoSuchAlgorithmException, ParserConfigurationException, SAXException, IOException { xmlParser xParser = new xmlParser(); ArrayList<ArrayList<Food>> listOfFoodList = new ArrayList<ArrayList<Food>>(); ArrayList<String> list; String base = URLEncoder.encode("GET") + "&"; base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&"; String params;/*from www . j av a 2s .c o m*/ //params = "format=json&"; params = "method=foods.search&"; params += "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&"; // ur consumer key params += "oauth_nonce=123&"; params += "oauth_signature_method=HMAC-SHA1&"; Date date = new java.util.Date(); Timestamp ts = new Timestamp(date.getTime()); params += "oauth_timestamp=" + ts.getTime() + "&"; params += "oauth_version=1.0&"; params += "search_expression=" + foodName; String params2 = URLEncoder.encode(params); base += params2; System.out.println(base); String line = ""; String secret = "76172de2330a4e55b90cbd2eb44f8c63&"; Mac sha256_HMAC = Mac.getInstance("HMACSHA1"); SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HMACSHA1"); sha256_HMAC.init(secret_key); String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(base.getBytes())); //$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig); String url = "http://platform.fatsecret.com/rest/server.api?" + params + "&oauth_signature=" + URLEncoder.encode(hash); System.out.println(url); list = xParser.foodSearchParser(url); for (int i = 0; i < list.size(); i++) { listOfFoodList.add(getFood(list.get(i))); } return listOfFoodList; }
From source file:org.apache.nifi.web.security.otp.OtpService.java
/** * Hashes the specified authentication token. The resulting value will be used as the one time use token. * * @param authenticationToken the authentication token * @return the one time use token *///from w ww . j a v a 2 s . co m private String hash(final OtpAuthenticationToken authenticationToken) { try { // input is the user identity and timestamp final String input = authenticationToken.getName() + "-" + System.nanoTime(); // create the secret using secure random final SecureRandom secureRandom = new SecureRandom(); final byte[] randomBytes = new byte[32]; secureRandom.nextBytes(randomBytes); final SecretKeySpec secret = new SecretKeySpec(randomBytes, HMAC_SHA256); // 256 bit // hash the input final Mac hmacSha256 = Mac.getInstance(HMAC_SHA256); hmacSha256.init(secret); final byte[] output = hmacSha256.doFinal(input.getBytes(StandardCharsets.UTF_8)); // return the result as a base 64 string return Base64.encodeBase64URLSafeString(output); } catch (final NoSuchAlgorithmException | InvalidKeyException e) { final String errorMessage = "There was an error generating the OTP"; logger.error(errorMessage, e); throw new IllegalStateException("Unable to generate single use token."); } }
From source file:org.apache.qpid.server.security.auth.sasl.CRAMMD5HexServerTest.java
/** * Since we don't have a CRAM-MD5-HEX implementation client implementation in Java, this method * provides the implementation for first principals. * * @param userId user id/*from ww w. j av a2 s . com*/ * @param clearTextPassword clear text password * @param serverChallenge challenge from server * * @return challenge response */ private byte[] generateClientResponse(final String userId, final String clearTextPassword, final byte[] serverChallenge) throws Exception { byte[] digestedPasswordBytes = MessageDigest.getInstance("MD5").digest(clearTextPassword.getBytes()); char[] hexEncodedDigestedPassword = Hex.encodeHex(digestedPasswordBytes); byte[] hexEncodedDigestedPasswordBytes = new String(hexEncodedDigestedPassword).getBytes(); Mac hmacMd5 = Mac.getInstance("HmacMD5"); hmacMd5.init(new SecretKeySpec(hexEncodedDigestedPasswordBytes, "HmacMD5")); final byte[] messageAuthenticationCode = hmacMd5.doFinal(serverChallenge); // Build client response String responseAsString = userId + " " + new String(Hex.encodeHex(messageAuthenticationCode)); byte[] resp = responseAsString.getBytes(); return resp; }
From source file:com.baidubce.auth.BceV1Signer.java
private String sha256Hex(String signingKey, String stringToSign) { try {//ww w .j a v a 2 s.c o m Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(signingKey.getBytes(UTF8), "HmacSHA256")); return new String(Hex.encodeHex(mac.doFinal(stringToSign.getBytes(UTF8)))); } catch (Exception e) { throw new BceClientException("Fail to generate the signature", e); } }