List of usage examples for javax.crypto Mac init
public final void init(Key key) throws InvalidKeyException
From source file:org.apache.cloudstack.region.RegionsApiUtil.java
/** * 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result * * @param request/*w w w .ja v a 2 s . c o m*/ * @param key * @return */ private static String signRequest(String request, String key) { try { Mac mac = Mac.getInstance("HmacSHA1"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1"); mac.init(keySpec); mac.update(request.getBytes()); byte[] encryptedBytes = mac.doFinal(); return URLEncoder.encode(Base64.encodeBase64String(encryptedBytes), "UTF-8"); } catch (Exception ex) { s_logger.error(ex.getMessage()); return null; } }
From source file:com.cws.esolutions.security.utils.PasswordUtils.java
/** * Base64 decodes a given string// w w w .j a v a 2 s . c o m * * @param variance - The allowed differences in OTP values * @param algorithm - The algorithm to encrypt the data with * @param instance - The security instance to utilize * @param secret - The OTP secret * @param code - The OTP code * @return <code>true</code> if successful, <code>false</code> otherwise * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing */ public static final boolean validateOtpValue(final int variance, final String algorithm, final String instance, final String secret, final int code) throws SecurityException { final String methodName = PasswordUtils.CNAME + "#validateOtpValue(final int variance, final String algorithm, final String instance, final String secret, final int code) throws SecurityException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", variance); DEBUGGER.debug("Value: {}", algorithm); DEBUGGER.debug("Value: {}", instance); DEBUGGER.debug("Value: {}", secret); DEBUGGER.debug("Value: {}", code); } long truncatedHash = 0; byte[] data = new byte[8]; long timeIndex = System.currentTimeMillis() / 1000 / 30; final Base32 codec = new Base32(); final byte[] decoded = codec.decode(secret); SecretKeySpec signKey = new SecretKeySpec(decoded, algorithm); if (DEBUG) { DEBUGGER.debug("long: {}", timeIndex); } try { for (int i = 8; i-- > 0; timeIndex >>>= 8) { data[i] = (byte) timeIndex; } Mac mac = Mac.getInstance(instance); mac.init(signKey); byte[] hash = mac.doFinal(data); int offset = hash[20 - 1] & 0xF; for (int i = 0; i < 4; i++) { truncatedHash <<= 8; truncatedHash |= (hash[offset + i] & 0xFF); } truncatedHash &= 0x7FFFFFFF; truncatedHash %= 1000000; if (DEBUG) { DEBUGGER.debug("truncatedHash: {}", truncatedHash); } return (truncatedHash == code); } catch (InvalidKeyException ikx) { throw new SecurityException(ikx.getMessage(), ikx); } catch (NoSuchAlgorithmException nsx) { throw new SecurityException(nsx.getMessage(), nsx); } }
From source file:br.com.vpsa.oauth2android.token.MacTokenTypeDefinition.java
private static String calculateMAC(String key, String normalizedString, String algorithm) { String macString = ""; try {// w w w . j a va2 s . c om System.out.println("algorithm=" + algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(new SecretKeySpec(key.getBytes(), algorithm)); macString = Base64.encodeToString(mac.doFinal(normalizedString.getBytes()), Base64.DEFAULT); } catch (InvalidKeyException ex) { Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(MacTokenTypeDefinition.class.getName()).log(Level.SEVERE, null, ex); } return macString; }
From source file:net.unicon.cas.chalkwire.servlet.CasChalkWireHttpServlet.java
private static Mac setKey(final String sharedSecret) throws IOException { try {/* w w w .j a v a2 s.c o m*/ final Mac mac = Mac.getInstance("HmacSHA1"); final byte[] keyBytes = sharedSecret.getBytes("UTF8"); final SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1"); mac.init(signingKey); return mac; } catch (Exception e) { throw new IOException(e); } }
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 w w. ja v a 2 s .c om*/ 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.applet.service.impl.UserIdentifierUtil.java
/** * Gives back a non-reversible citizen identifier (NRCID). * //from w ww.j a v a 2 s . com * @param userId * the primary user identifier, i.e. the national registry * number. * @param orgId * the optional organization identifier. * @param appId * the optional application identifier. * @param secret * the application specific secret. Should be at least 128 bit * long. Encoded in hexadecimal format. * @return */ public static String getNonReversibleCitizenIdentifier(String userId, String orgId, String appId, String secret) { if (null == secret) { throw new IllegalArgumentException("secret key is null"); } /* * Avoid XML formatting issues introduced by some web.xml XML editors. */ secret = secret.trim(); if (null != orgId) { orgId = orgId.trim(); } else { LOG.warn("it is advised to use an orgId"); } if (null != appId) { appId = appId.trim(); } else { LOG.warn("it is advised to use an appId"); } /* * Decode the secret key. */ byte[] secretKey; try { secretKey = Hex.decodeHex(secret.toCharArray()); } catch (DecoderException e) { LOG.error("secret is not hexadecimal encoded: " + e.getMessage()); throw new IllegalArgumentException("secret is not hexadecimal encoded"); } if ((128 / 8) > secretKey.length) { /* * 128 bit is seen as secure these days. */ LOG.warn("secret key is too short"); throw new IllegalArgumentException("secret key is too short"); } /* * Construct the HMAC input sequence. */ String input = userId; if (null != appId) { input += appId; } if (null != orgId) { input += orgId; } byte[] inputData = input.getBytes(); SecretKey macKey = new SecretKeySpec(secretKey, HMAC_ALGO); Mac mac; try { mac = Mac.getInstance(macKey.getAlgorithm()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("HMAC algo not available: " + e.getMessage()); } try { mac.init(macKey); } catch (InvalidKeyException e) { LOG.error("invalid secret key: " + e.getMessage(), e); throw new RuntimeException("invalid secret"); } mac.update(inputData); byte[] resultHMac = mac.doFinal(); String resultHex = new String(Hex.encodeHex(resultHMac)).toUpperCase(); return resultHex; }
From source file:SecurityUtils.java
/** * Converts a source string to its HMAC/SHA-1 value. * //from www . jav a 2 s . co m * @param source * The source string to convert. * @param secretKey * The secret key to use for conversion. * @return The HMac value of the source string. */ public static byte[] toHMac(String source, String secretKey) { byte[] result = null; try { // Create the HMAC/SHA1 key final SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1"); // Create the message authentication code (MAC) final Mac mac = Mac.getInstance("HmacSHA1"); mac.init(signingKey); // Compute the HMAC value result = mac.doFinal(source.getBytes()); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("Could not find the SHA-1 algorithm. HMac conversion failed.", nsae); } catch (InvalidKeyException ike) { throw new RuntimeException("Invalid key exception detected. HMac conversion failed.", ike); } return result; }
From source file:com.profesorfalken.payzen.webservices.sdk.handler.soap.HeaderHandler.java
private static byte[] encode256(byte[] keyBytes, byte[] text) throws NoSuchAlgorithmException, InvalidKeyException { Mac hmacSha1; try {//from w w w .j a va2 s. c om hmacSha1 = Mac.getInstance("HmacSHA256"); } catch (NoSuchAlgorithmException nsae) { hmacSha1 = Mac.getInstance("HMAC-SHA-256"); } SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW"); try { hmacSha1.init(macKey); } catch (java.security.InvalidKeyException ex) { logger.error("Error encoding auth hash", ex); } return hmacSha1.doFinal(text); }
From source file:com.ironchain.common.kits.DigestKit.java
/** * HMAC-SHA1???, ,20./* w w w . ja va 2 s .co m*/ * * @param input * * @param key * HMAC-SHA1 */ public static byte[] hmacSha1(byte[] input, byte[] key) { try { SecretKey secretKey = new SecretKeySpec(key, HMACSHA1); Mac mac = Mac.getInstance(HMACSHA1); mac.init(secretKey); return mac.doFinal(input); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }
From source file:com.ai.smart.bottom.helper.MacUtils.java
public static String hmacsha256(String secret, String data) { Mac mac = null; byte[] doFinal = null; try {// w w w . java2 s . co m mac = Mac.getInstance(HMAC_ALGORITHM); //??MD5 byte[] dataBytes = DigestUtils.md5(data); //sourcekeyMD5, SecretKey secretkey = new SecretKeySpec(DigestUtils.md5(secret), HMAC_ALGORITHM); mac.init(secretkey); //HmacSHA256 doFinal = mac.doFinal(dataBytes); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeyException e) { } String checksum = Hex.encodeHexString(doFinal).toLowerCase(); return checksum; }