List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.zegoggles.smssync.auth.XOAuthConsumer.java
private String generateSig(HttpRequest request, HttpParameters requestParameters) throws Exception { String keyString = percentEncode(getConsumerSecret()) + '&' + percentEncode(getTokenSecret()); SecretKey key = new SecretKeySpec(keyString.getBytes(ENCODING), MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(key);/*w w w . j a v a 2 s.co m*/ String sbs = new SignatureBaseString(request, requestParameters).generate(); return base64(mac.doFinal(sbs.getBytes(ENCODING))); }
From source file:com.zimbra.cs.service.account.GetAccountInfo.java
static void addUrls(Element response, Account account) throws ServiceException { Provisioning prov = Provisioning.getInstance(); Server server = prov.getServer(account); String hostname = server.getAttr(Provisioning.A_zimbraServiceHostname); Domain domain = prov.getDomain(account); if (server != null && hostname != null) { String httpSoap = URLUtil.getSoapPublicURL(server, domain, false); String httpsSoap = URLUtil.getSoapPublicURL(server, domain, true); if (httpSoap != null) { response.addAttribute(AccountConstants.E_SOAP_URL /* soapURL */, httpSoap, Element.Disposition.CONTENT); }//from w ww . j av a 2 s . c o m if (httpsSoap != null && !httpsSoap.equalsIgnoreCase(httpSoap)) { /* Note: addAttribute with Element.Disposition.CONTENT REPLACEs any previous attribute with the same name. * i.e. Will NOT end up with both httpSoap and httpsSoap as values for "soapURL" */ response.addAttribute(AccountConstants.E_SOAP_URL /* soapURL */, httpsSoap, Element.Disposition.CONTENT); } String pubUrl = URLUtil.getPublicURLForDomain(server, domain, "", true); if (pubUrl != null) { response.addAttribute(AccountConstants.E_PUBLIC_URL, pubUrl, Element.Disposition.CONTENT); } if (AccessManager.getInstance().isAdequateAdminAccount(account)) { String publicAdminUrl = URLUtil.getPublicAdminConsoleURLForDomain(server, domain); if (publicAdminUrl != null) { response.addAttribute(AccountConstants.E_ADMIN_URL, publicAdminUrl, Element.Disposition.CONTENT); } } String changePasswordUrl = null; if (domain != null) { changePasswordUrl = domain.getAttr(Provisioning.A_zimbraChangePasswordURL); } if (changePasswordUrl != null) { response.addAttribute(AccountConstants.E_CHANGE_PASSWORD_URL, changePasswordUrl, Element.Disposition.CONTENT); } } //add a Community redirect URL if (account.getBooleanAttr(Provisioning.A_zimbraFeatureSocialExternalEnabled, false)) { String clientID = account.getAttr(Provisioning.A_zimbraCommunityAPIClientID); if (clientID == null) { ZimbraLog.account.debug( "Zimbra Community client ID is not properly configured. zimbraCommunityAPIClientID cannot be empty."); } String clientSecret = account.getAttr(Provisioning.A_zimbraCommunityAPIClientSecret); if (clientSecret == null) { ZimbraLog.account.debug( "Zimbra Community client secret is not properly configured. zimbraCommunityAPIClientSecret cannot be empty."); } String nameAttribute = account.getAttr(Provisioning.A_zimbraCommunityUsernameMapping); if (nameAttribute == null) { ZimbraLog.account.debug( "Zimbra Community name mapping is not properly configured. zimbraCommunityUsernameMapping cannot be empty"); } String socialBaseURL = account.getAttr(Provisioning.A_zimbraCommunityBaseURL); if (socialBaseURL == null) { ZimbraLog.account.debug( "Zimbra Community base URL is not properly configured. zimbraCommunityBaseURL cannot be empty"); } else { if (socialBaseURL.endsWith("/")) { //avoid double slashes socialBaseURL = socialBaseURL.substring(0, socialBaseURL.length() - 1); } } String socialTabURL = account.getAttr(Provisioning.A_zimbraCommunityHomeURL); if (socialTabURL == null) { ZimbraLog.account.debug( "Zimbra Community home URL is not properly configured. zimbraCommunityHomeURL cannot be empty"); } else { if (!socialTabURL.startsWith("/")) { //make sure the path is relative socialTabURL = "/".concat(socialTabURL); } } if (clientID != null && clientSecret != null && nameAttribute != null && socialBaseURL != null && socialTabURL != null) { try { Date today = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); Mac mac = Mac.getInstance("HmacSHA256"); SecretKeySpec key = new SecretKeySpec(clientSecret.getBytes("UTF8"), "HmacSHA256"); mac.init(key); byte[] rawHmac = mac.doFinal(String.format("%s%s%s%s", account.getUid(), formatter.format(today), socialBaseURL, socialTabURL).getBytes("UTF8")); String Base64Signature = Base64.encodeBase64String(rawHmac); String szURL = String.format( "%s/api.ashx/v2/oauth/redirect?client_id=%s&username=%s&time_stamp=%s&redirect_uri=%s&signature=%s", socialBaseURL, URLEncoder.encode(clientID, "UTF8"), account.getAttr(nameAttribute), URLEncoder.encode(formatter.format(today), "UTF8"), URLEncoder.encode(socialBaseURL.concat(socialTabURL), "UTF8"), URLEncoder.encode(Base64Signature, "UTF8")); response.addAttribute(AccountConstants.E_COMMUNITY_URL, szURL, Element.Disposition.CONTENT); } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) { throw ServiceException.FAILURE("Failed to generate community URL", e); } } } //add BOSH URL if Chat is enabled if (account.getBooleanAttr(Provisioning.A_zimbraFeatureChatEnabled, false)) { response.addAttribute(AccountConstants.E_BOSH_URL, server.getReverseProxyXmppBoshLocalHttpBindURL()); } }
From source file:be.fedict.eid.idp.protocol.openid.StatelessServerAssociationStore.java
private Association loadFromHandle(String handle) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException, InvalidAlgorithmParameterException { byte[] encodedHandle = Base64.decodeBase64(handle); if (null != this.macSecretKeySpec) { byte[] signature = new byte[32]; System.arraycopy(encodedHandle, 0, signature, 0, 32); byte[] toBeSigned = new byte[encodedHandle.length - 32]; System.arraycopy(encodedHandle, 32, toBeSigned, 0, encodedHandle.length - 32); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(this.macSecretKeySpec); byte[] actualSignature = mac.doFinal(toBeSigned); if (false == Arrays.equals(actualSignature, signature)) { return null; }/*w ww. j av a 2 s . c o m*/ encodedHandle = toBeSigned; } byte[] iv = new byte[16]; System.arraycopy(encodedHandle, 0, iv, 0, iv.length); byte[] encodedData = Arrays.copyOfRange(encodedHandle, 16, encodedHandle.length); Cipher cipher = Cipher.getInstance(CIPHER_ALGO); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, this.secretKeySpec, ivParameterSpec); byte[] associationBytes = cipher.doFinal(encodedData); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(associationBytes); int typeByte = byteArrayInputStream.read(); if (typeByte == 1) { byte[] macKeyBytes = new byte[160 / 8]; byteArrayInputStream.read(macKeyBytes); DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream); long exp = dataInputStream.readLong(); Date expDate = new Date(exp); return Association.createHmacSha1(handle, macKeyBytes, expDate); } else if (typeByte == 2) { byte[] macKeyBytes = new byte[256 / 8]; byteArrayInputStream.read(macKeyBytes); DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream); long exp = dataInputStream.readLong(); Date expDate = new Date(exp); return Association.createHmacSha256(handle, macKeyBytes, expDate); } else { return null; } }
From source file:angel.zhuoxiu.library.pusher.Pusher.java
private String authenticate(String channelName) { if (!isConnected()) { Log.e(LOG_TAG, "pusher not connected, can't create auth string"); return null; }//from w w w . ja v a2 s . co m try { String stringToSign = mSocketId + ":" + channelName; SecretKey key = new SecretKeySpec(mPusherSecret.getBytes(), PUSHER_AUTH_ALGORITHM); Mac mac = Mac.getInstance(PUSHER_AUTH_ALGORITHM); mac.init(key); byte[] signature = mac.doFinal(stringToSign.getBytes()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < signature.length; ++i) { sb.append(Integer.toHexString((signature[i] >> 4) & 0xf)); sb.append(Integer.toHexString(signature[i] & 0xf)); } String authInfo = mPusherKey + ":" + sb.toString(); Log.d(LOG_TAG, "Auth Info " + authInfo); return authInfo; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } return null; }
From source file:client.tools.AccessBundleShell.java
/** * Creates a (content, integrity) key pair. * //from w w w . j av a2 s . c o m * @param version * the version of the key * @return a pair of new random (content, integrity) keys with the user * specified properties. * @throws IOException */ private Pair<Key, Key> createKeys(int version) throws IOException { String input; String cipherString = null; String macString = null; int cipherKeyLength = DEFAULT_CIPHER_KEY_LENGTH; int macKeyLength = DEFAULT_MAC_KEY_LENGTH; boolean done = false; // Cipher key generation while (!done) { System.out.format("Specify the cipher [%s]: ", DEFAULT_CIPHER); input = in.readLine(); cipherString = input; if ((cipherString == null) || "".equals(cipherString.trim())) { cipherString = DEFAULT_CIPHER; } try { Cipher.getInstance(cipherString.trim()); done = true; } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { System.out.println("Algorithm or padding not available."); } } done = false; while (!done) { System.out.format("Specify the length of the cipher key in bits [%d]: ", DEFAULT_CIPHER_KEY_LENGTH); input = in.readLine(); if ((input == null) || "".equals(input.trim())) { cipherKeyLength = DEFAULT_CIPHER_KEY_LENGTH; done = true; } else { try { cipherKeyLength = Integer.valueOf(input); if (cipherKeyLength < 1) { System.out.println("Invalid key length."); } else { done = true; } } catch (NumberFormatException e) { System.out.println("Please enter a positive integer."); } } } // MAC key generation done = false; while (!done) { System.out.format("Specify the MAC algorithm [%s]: ", DEFAULT_MAC); input = in.readLine(); macString = input; if ((macString == null) || "".equals(macString.trim())) { macString = DEFAULT_MAC; } try { Mac.getInstance(macString.trim()); done = true; } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm not available."); } } done = false; while (!done) { System.out.format("Specify the length of the MAC key in bits [%d]: ", DEFAULT_MAC_KEY_LENGTH); input = in.readLine(); if ((input == null) || "".equals(input.trim())) { macKeyLength = DEFAULT_MAC_KEY_LENGTH; done = true; } else { try { macKeyLength = Integer.valueOf(input); if (macKeyLength < 1) { System.out.println("Invalid key length."); } else { done = true; } } catch (NumberFormatException e) { System.out.println("Please enter a positive integer."); } } } return new Pair<Key, Key>(Key.randomKey(cipherKeyLength, version, cipherString), Key.randomKey(macKeyLength, version, macString)); }
From source file:org.apache.abdera.ext.oauth.OAuthScheme.java
private String sign(String method, String baseString, Certificate cert) throws AuthenticationException { if (method.equalsIgnoreCase("HMAC-MD5") || method.equalsIgnoreCase("HMAC-SHA1")) { try {/*from www .jav a 2 s .c o m*/ String[] tokens = method.split("-"); String methodName = tokens[0].substring(0, 1).toUpperCase() + tokens[0].substring(1).toLowerCase() + tokens[1]; KeyGenerator kg = KeyGenerator.getInstance(methodName); Mac mac = Mac.getInstance(kg.getAlgorithm()); mac.init(kg.generateKey()); byte[] result = mac.doFinal(baseString.getBytes()); return new String(Base64.encodeBase64(result)); } catch (Exception e) { throw new AuthenticationException(e.getMessage(), e); } } else if (method.equalsIgnoreCase("md5")) { return new String(Base64.encodeBase64(DigestUtils.md5(baseString))); } else if (method.equalsIgnoreCase("sha1")) { return new String(Base64.encodeBase64(DigestUtils.sha(baseString))); } else if (method.equalsIgnoreCase("RSA-SHA1")) { if (cert == null) { throw new AuthenticationException("a cert is mandatory to use SHA1 with RSA"); } try { Cipher cipher = Cipher.getInstance("SHA1withRSA"); cipher.init(Cipher.ENCRYPT_MODE, cert); byte[] result = cipher.doFinal(baseString.getBytes()); return new String(Base64.encodeBase64(result)); } catch (Exception e) { throw new AuthenticationException(e.getMessage(), e); } } else { throw new AuthenticationException("unsupported algorithm method: " + method); } }
From source file:org.sharextras.webscripts.connector.HttpOAuthConnector.java
private String generateSignature(Map<String, String> authParams, Map<String, String> extraParams, String httpMethod, String url) { Map<String, String> sigParams = new HashMap<String, String>(authParams); if (extraParams != null) sigParams.putAll(extraParams);/*w ww . j ava 2 s. c o m*/ String sigMethod = sigParams.get(OAUTH_SIGNATURE_METHOD); if (sigMethod.equals(SIGNATURE_METHOD_PLAINTEXT)) { if (logger.isDebugEnabled()) logger.debug("Generating PLAINTEXT signature"); String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET); StringBuffer signatureBuffer = new StringBuffer(getConsumerSecret()).append("&"); signatureBuffer.append(tokenSecret != null ? tokenSecret : ""); return signatureBuffer.toString(); } else if (sigMethod.equals(SIGNATURE_METHOD_HMACSHA1)) { if (logger.isDebugEnabled()) logger.debug("Generating HMAC-SHA1 signature"); StringBuffer baseStrBuffer = new StringBuffer(); baseStrBuffer.append(httpMethod).append("&"); baseStrBuffer.append(encodeParameter(url)); baseStrBuffer.append("&"); // Add all request params to the list, combine request and auth params in a single map // as per http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1 // TODO Support multiple parameters with same name // Sort keys by param name // TODO Sort *after* encoding List<String> keys = new ArrayList<String>(sigParams.keySet()); Collections.sort(keys); int i = 0; for (String key : keys) { if (!key.equals(OAUTH_REALM) && !key.equals(OAUTH_SIGNATURE) && !key.equals(OAUTH_TOKEN_SECRET)) { if (i > 0) baseStrBuffer.append(encodeParameter("&")); baseStrBuffer.append( encodeParameter(encodeParameter(key) + "=" + encodeParameter(sigParams.get(key)))); i++; } } // Final base string String baseString = baseStrBuffer.toString(); // Key to use for signing String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET); String key = encodeParameter(getConsumerSecret()) + "&" + encodeParameter(tokenSecret != null ? tokenSecret : ""); if (logger.isDebugEnabled()) logger.debug("Generating signature with key '" + key + "', base string '" + baseString + "'"); try { SecretKey keyStr = new SecretKeySpec(key.getBytes(), "HmacSHA1"); Mac m = Mac.getInstance("HmacSHA1"); m.init(keyStr); m.update(baseString.getBytes()); byte[] mac = m.doFinal(); return new String(Base64.encodeBytes(mac)).trim(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } else { throw new UnsupportedOperationException(); } }
From source file:com.scm.reader.livescanner.search.SearchRequestBuilder.java
private static String signHmacSha1(String key, String message) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException { SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(keySpec);/*from www. ja va2 s .c o m*/ byte[] result = mac.doFinal(message.getBytes()); return new String(Base64.encodeBase64(result)); }
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; }