List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:org.instagram4j.DefaultInstagramClient.java
private void setEnforceHeader(HttpRequestBase method) { if (!isSignedHeaderEnabled()) return;// w w w. j a va2 s . c o m if (clientSecret == null) throw new IllegalStateException("Client secret it required to use signed header"); if (clientIps == null || clientIps.length() == 0) throw new IllegalStateException("Client IP(s) required to use signed header"); try { SecretKeySpec signingKey = new SecretKeySpec(getClientSecret().getBytes(), HMAC_SHA256_ALGO); Mac mac = Mac.getInstance(HMAC_SHA256_ALGO); mac.init(signingKey); // Compute the hmac on IP address. byte[] rawHmac = mac.doFinal(clientIps.getBytes()); String digest = Hex.encodeHexString(rawHmac); method.setHeader("X-Insta-Forwarded-For", String.format("%s|%s", clientIps, digest)); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Unexpected error creating signed header using HMAC-SHA256", e); } catch (InvalidKeyException e) { throw new IllegalStateException("Unexpected error creating signed header using HMAC-SHA256", e); } }
From source file:com.cloud.servlet.ConsoleProxyServlet.java
private boolean verifyRequest(Map<String, Object[]> requestParameters) { try {//from ww w . j a v a 2s . co m String apiKey = null; String secretKey = null; String signature = null; String unsignedRequest = null; // - build a request string with sorted params, make sure it's all lowercase // - sign the request, verify the signature is the same List<String> parameterNames = new ArrayList<String>(); for (Object paramNameObj : requestParameters.keySet()) { parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later } Collections.sort(parameterNames); for (String paramName : parameterNames) { // parameters come as name/value pairs in the form String/String[] String paramValue = ((String[]) requestParameters.get(paramName))[0]; if ("signature".equalsIgnoreCase(paramName)) { signature = paramValue; } else { if ("apikey".equalsIgnoreCase(paramName)) { apiKey = paramValue; } if (unsignedRequest == null) { unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } else { unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } } } // if api/secret key are passed to the parameters if ((signature == null) || (apiKey == null)) { if (s_logger.isDebugEnabled()) { s_logger.debug( "expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); } return false; // no signature, bad request } Transaction txn = Transaction.open(Transaction.CLOUD_DB); txn.close(); User user = null; // verify there is a user with this api key Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey); if (userAcctPair == null) { s_logger.debug("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey); return false; } user = userAcctPair.first(); Account account = userAcctPair.second(); if (!user.getState().equals(Account.State.enabled) || !account.getState().equals(Account.State.enabled)) { s_logger.debug("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState()); return false; } // verify secret key exists secretKey = user.getSecretKey(); if (secretKey == null) { s_logger.debug( "User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername()); return false; } unsignedRequest = unsignedRequest.toLowerCase(); Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(unsignedRequest.getBytes()); byte[] encryptedBytes = mac.doFinal(); String computedSignature = Base64.encodeBase64URLSafeString(encryptedBytes); boolean equalSig = signature.equals(computedSignature); if (!equalSig) { s_logger.debug("User signature: " + signature + " is not equaled to computed signature: " + computedSignature); } if (equalSig) { requestParameters.put("userid", new Object[] { String.valueOf(user.getId()) }); requestParameters.put("account", new Object[] { account.getAccountName() }); requestParameters.put("accountobj", new Object[] { account }); } return equalSig; } catch (Exception ex) { s_logger.error("unable to verifty request signature", ex); } return false; }
From source file:net.sf.xfd.provider.PublicProvider.java
public static @Nullable Uri publicUri(Context context, CharSequence path, String mode) { // XXX suspect coversion final String pathString = path.toString(); final int modeInt = ParcelFileDescriptor.parseMode(mode); final Key key = getSalt(context); if (key == null) { return null; }//from w w w. j a va2 s .c o m final Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, 1); final long l = c.getTimeInMillis(); final byte[] encoded; try { final Mac hash = Mac.getInstance("HmacSHA1"); hash.init(key); final byte[] modeBits = new byte[] { (byte) (modeInt >> 24), (byte) (modeInt >> 16), (byte) (modeInt >> 8), (byte) modeInt, }; hash.update(modeBits); final byte[] expiryDate = new byte[] { (byte) (l >> 56), (byte) (l >> 48), (byte) (l >> 40), (byte) (l >> 32), (byte) (l >> 24), (byte) (l >> 16), (byte) (l >> 8), (byte) l, }; hash.update(expiryDate); encoded = hash.doFinal(pathString.getBytes()); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new AssertionError("Error while creating a hash: " + e.getMessage(), e); } final String packageName = context.getPackageName(); final Uri.Builder b = new Uri.Builder().scheme(SCHEME_CONTENT).authority(packageName + AUTHORITY_SUFFIX); if (!"r".equals(mode)) { b.appendQueryParameter(URI_ARG_MODE, mode); } return b.path(pathString).appendQueryParameter(URI_ARG_EXPIRY, String.valueOf(l)) .appendQueryParameter(URI_ARG_COOKIE, encodeToString(encoded, URL_SAFE | NO_WRAP | NO_PADDING)) .build(); }
From source file:org.dasein.cloud.atmos.AtmosMethod.java
private @Nonnull String sign(@Nonnull ProviderContext ctx, @Nonnull String stringToSign) throws InternalException { try {/* w ww . ja v a 2s. com*/ Mac mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(Base64.decodeBase64(new String(ctx.getAccessPrivate(), "utf-8")), "HmacSHA1")); return new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes("UTF-8"))), "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:edu.ku.brc.util.WebStoreAttachmentMgr.java
private String generateToken(String attachLocation) { if (StringUtils.isEmpty(attachment_key)) return ""; SecretKeySpec keySpec = new SecretKeySpec(attachment_key.getBytes(), "HmacMD5"); Mac mac;/*from w w w. j a v a 2s . c o m*/ try { mac = Mac.getInstance("HmacMD5"); mac.init(keySpec); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } String timestamp = "" + (getSystemTime() + serverTimeDelta); byte[] raw = mac.doFinal((timestamp + attachLocation).getBytes()); return new String(Hex.encodeHex(raw)) + ":" + timestamp; }
From source file:me.vertretungsplan.parser.WebUntisParser.java
private int authCodeInternal(long time) throws NoSuchAlgorithmException, InvalidKeyException { long t = time / 30000; byte[] key = new Base32().decode(sharedSecret.toUpperCase().getBytes()); byte[] data = new byte[8]; long value = t; int i = 8;/* w ww.j a v a 2 s . c o m*/ while (true) { int i2 = i - 1; if (i <= 0) { break; } data[i2] = (byte) ((int) value); value >>>= 8; i = i2; } SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signKey); byte[] hash = mac.doFinal(data); int offset = hash[19] & 15; long truncatedHash = 0; for (int i2 = 0; i2 < 4; i2 += 1) { truncatedHash = (truncatedHash << 8) | ((long) (hash[offset + i2] & 255)); } return (int) ((truncatedHash & 2147483647L) % 1000000); }
From source file:com.mastfrog.acteur.twitter.TwitterSign.java
String generateSignature(String data, AuthorizationResponse token) throws NoSuchAlgorithmException, InvalidKeyException { byte[] byteHMAC = null; Mac mac = Mac.getInstance(ALGORITHM); SecretKeySpec spec;/* w w w .jav a2 s . c o m*/ if (token == null) { String signature = HttpParameter.encode(twitter_consumer_secret) + "&"; spec = new SecretKeySpec(signature.getBytes(), ALGORITHM); } else { String signature = HttpParameter.encode(twitter_consumer_secret) + "&" + HttpParameter.encode(token.accessTokenSecret); spec = new SecretKeySpec(signature.getBytes(), ALGORITHM); } mac.init(spec); byteHMAC = mac.doFinal(data.getBytes()); String sig = BASE64Encoder.encode(byteHMAC); return sig; }
From source file:org.dasein.cloud.aws.AWSCloud.java
private String sign(byte[] key, String authString, String algorithm) throws InternalException { try {/* ww w. j av a2 s . c om*/ 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:com.edduarte.protbox.core.registry.PReg.java
public byte[] encrypt(byte[] decryptedData, boolean appendChecksum) throws ProtboxException { try {/* ww w . j av a 2 s . com*/ CIPHER.init(Cipher.ENCRYPT_MODE, pair.getPairKey()); byte[] integrityControlValue = null; int checksumLength = 0; if (appendChecksum) { Mac mac = Mac.getInstance("HmacSHA512"); mac.init(pair.getIntegrityKey()); integrityControlValue = mac.doFinal(decryptedData); checksumLength = 64; } byte[] encryptedData = CIPHER.doFinal(decryptedData); boolean isCBC = pair.getPairAlgorithm().contains("CBC"); byte[] iv = CIPHER.getIV(); int ivLength = isCBC ? 16 : 0; byte[] result = new byte[checksumLength + ivLength + encryptedData.length]; if (appendChecksum) { System.arraycopy(integrityControlValue, 0, result, 0, checksumLength); } if (isCBC) { System.arraycopy(iv, 0, result, checksumLength, ivLength); } System.arraycopy(encryptedData, 0, result, checksumLength + ivLength, encryptedData.length); return result; } catch (GeneralSecurityException ex) { throw new ProtboxException(ex); } }
From source file:com.cloud.api.ApiServer.java
public boolean verifyRequest(Map<String, Object[]> requestParameters, Long userId) throws ServerApiException { try {/*from w w w .ja va 2s .c o m*/ String apiKey = null; String secretKey = null; String signature = null; String unsignedRequest = null; String[] command = (String[]) requestParameters.get("command"); if (command == null) { s_logger.info("missing command, ignoring request..."); return false; } String commandName = command[0]; // if userId not null, that mean that user is logged in if (userId != null) { Long accountId = ApiDBUtils.findUserById(userId).getAccountId(); Account userAccount = _accountMgr.getAccount(accountId); short accountType = userAccount.getType(); if (!isCommandAvailable(accountType, commandName)) { s_logger.warn("The given command:" + commandName + " does not exist"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); } return true; } else { // check against every available command to see if the command exists or not if (!isCommandAvailable(commandName) && !commandName.equals("login") && !commandName.equals("logout")) { s_logger.warn("The given command:" + commandName + " does not exist"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); } } // - build a request string with sorted params, make sure it's all lowercase // - sign the request, verify the signature is the same List<String> parameterNames = new ArrayList<String>(); for (Object paramNameObj : requestParameters.keySet()) { parameterNames.add((String) paramNameObj); // put the name in a list that we'll sort later } Collections.sort(parameterNames); String signatureVersion = null; String expires = null; for (String paramName : parameterNames) { // parameters come as name/value pairs in the form String/String[] String paramValue = ((String[]) requestParameters.get(paramName))[0]; if ("signature".equalsIgnoreCase(paramName)) { signature = paramValue; } else { if ("apikey".equalsIgnoreCase(paramName)) { apiKey = paramValue; } else if ("signatureversion".equalsIgnoreCase(paramName)) { signatureVersion = paramValue; } else if ("expires".equalsIgnoreCase(paramName)) { expires = paramValue; } if (unsignedRequest == null) { unsignedRequest = paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } else { unsignedRequest = unsignedRequest + "&" + paramName + "=" + URLEncoder.encode(paramValue, "UTF-8").replaceAll("\\+", "%20"); } } } // if api/secret key are passed to the parameters if ((signature == null) || (apiKey == null)) { if (s_logger.isDebugEnabled()) { s_logger.info( "expired session, missing signature, or missing apiKey -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); } return false; // no signature, bad request } Date expiresTS = null; if ("3".equals(signatureVersion)) { // New signature authentication. Check for expire parameter and its validity if (expires == null) { s_logger.info("missing Expires parameter -- ignoring request...sig: " + signature + ", apiKey: " + apiKey); return false; } synchronized (_dateFormat) { try { expiresTS = _dateFormat.parse(expires); } catch (ParseException pe) { s_logger.info("Incorrect date format for Expires parameter", pe); return false; } } Date now = new Date(System.currentTimeMillis()); if (expiresTS.before(now)) { s_logger.info("Request expired -- ignoring ...sig: " + signature + ", apiKey: " + apiKey); return false; } } Transaction txn = Transaction.open(Transaction.CLOUD_DB); txn.close(); User user = null; // verify there is a user with this api key Pair<User, Account> userAcctPair = _accountMgr.findUserByApiKey(apiKey); if (userAcctPair == null) { s_logger.info("apiKey does not map to a valid user -- ignoring request, apiKey: " + apiKey); return false; } user = userAcctPair.first(); Account account = userAcctPair.second(); if (user.getState() != Account.State.enabled || !account.getState().equals(Account.State.enabled)) { s_logger.info("disabled or locked user accessing the api, userid = " + user.getId() + "; name = " + user.getUsername() + "; state: " + user.getState() + "; accountState: " + account.getState()); return false; } UserContext.updateContext(user.getId(), account, null); if (!isCommandAvailable(account.getType(), commandName)) { s_logger.warn("The given command:" + commandName + " does not exist"); throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist"); } // verify secret key exists secretKey = user.getSecretKey(); if (secretKey == null) { s_logger.info( "User does not have a secret key associated with the account -- ignoring request, username: " + user.getUsername()); return false; } unsignedRequest = unsignedRequest.toLowerCase(); Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(unsignedRequest.getBytes()); byte[] encryptedBytes = mac.doFinal(); String computedSignature = Base64.encodeBase64String(encryptedBytes); boolean equalSig = signature.equals(computedSignature); if (!equalSig) { s_logger.info("User signature: " + signature + " is not equaled to computed signature: " + computedSignature); } return equalSig; } catch (Exception ex) { if (ex instanceof ServerApiException && ((ServerApiException) ex).getErrorCode() == BaseCmd.UNSUPPORTED_ACTION_ERROR) { throw (ServerApiException) ex; } s_logger.error("unable to verifty request signature", ex); } return false; }