List of usage examples for javax.crypto Mac getInstance
public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:com.weibo.api.OAuth2.java
private String parseSignedRequest(String signedRequest, String appSecret) { String tokenInfoValue = null; String[] tokens = StringUtils.split(signedRequest, "\\.", 2); // base64Token String base64Token = tokens[0]; // url encode/decode ??base64url ?? // '+''/'??'-''_''=' ???base64?'='? int padding = (4 - base64Token.length() % 4); for (int i = 0; i < padding; i++) { base64Token += "="; }//from w ww . jav a 2 s. c o m base64Token = StringUtils.replace(base64Token, "-", "+"); base64Token = StringUtils.replace(base64Token, "_", "/"); // base64Token1 String token1 = tokens[1]; SecretKey key = new SecretKeySpec(appSecret.getBytes(), ALGORITHM_HMACSHA256); try { Mac mac = Mac.getInstance(ALGORITHM_HMACSHA256); mac.init(key); mac.update(token1.getBytes()); byte[] macResult = mac.doFinal(); String base64Token1 = Base64.encodeBase64String(macResult); // access token if (StringUtils.equals(base64Token, base64Token1)) { tokenInfoValue = new String(Base64.decodeBase64(token1)); log.info(tokenInfoValue); } } catch (NoSuchAlgorithmException e) { log.error(ExceptionUtils.getFullStackTrace(e)); } catch (InvalidKeyException e) { log.error(ExceptionUtils.getFullStackTrace(e)); } return tokenInfoValue; }
From source file:org.apache.xml.security.algorithms.implementations.IntegrityHmac.java
/** * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)} * which is executed on the internal {@link java.security.Signature} object. * * @param secretKey// w ww . j av a 2 s .c o m * @throws XMLSignatureException */ protected void engineInitVerify(Key secretKey) throws XMLSignatureException { if (!(secretKey instanceof SecretKey)) { String supplied = secretKey.getClass().getName(); String needed = SecretKey.class.getName(); Object exArgs[] = { supplied, needed }; throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { this.macAlgorithm.init(secretKey); } catch (InvalidKeyException ex) { // reinstantiate Mac object to work around bug in JDK // see: http://bugs.sun.com/view_bug.do?bug_id=4953555 Mac mac = this.macAlgorithm; try { this.macAlgorithm = Mac.getInstance(macAlgorithm.getAlgorithm()); } catch (Exception e) { // this shouldn't occur, but if it does, restore previous Mac if (log.isDebugEnabled()) { log.debug("Exception when reinstantiating Mac:" + e); } this.macAlgorithm = mac; } throw new XMLSignatureException("empty", ex); } }
From source file:com.flazr.Utils.java
public static byte[] sha256(byte[] message, byte[] key) { Mac mac;//w w w . j a v a 2 s . co m try { mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); } catch (Exception e) { throw new RuntimeException(e); } return mac.doFinal(message); }
From source file:fi.okm.mpass.shibboleth.authn.impl.BaseInitializeWilmaContext.java
/** * Constructs an URL where the user is redirected for authentication. * @param flowExecutionUrl The current flow execution URL, to be included in the redirect URL. * @param authenticationContext The context, also containing {@link WilmaAuthenticationContext}. * @return The redirect URL containing the checksum. *//*from w ww . jav a 2 s . c o m*/ public String getRedirect(final String flowExecutionUrl, final AuthenticationContext authenticationContext) { final HttpServletRequest httpRequest = getHttpServletRequest(); final WilmaAuthenticationContext wilmaContext = authenticationContext .getSubcontext(WilmaAuthenticationContext.class); final StringBuffer redirectToBuffer = new StringBuffer( httpRequest.getScheme() + "://" + httpRequest.getServerName()); if (httpRequest.getServerPort() != 443) { redirectToBuffer.append(":" + httpRequest.getServerPort()); } redirectToBuffer.append(flowExecutionUrl).append(getAsParameter("&", "_eventId_proceed", "1")); redirectToBuffer .append(getAsParameter("&", WilmaAuthenticationContext.PARAM_NAME_NONCE, wilmaContext.getNonce())); final URLCodec urlCodec = new URLCodec(); try { final StringBuffer unsignedUrlBuffer = new StringBuffer(wilmaContext.getRedirectUrl()); unsignedUrlBuffer.append(getAsParameter("?", WilmaAuthenticationContext.PARAM_NAME_REDIRECT_TO, urlCodec.encode(redirectToBuffer.toString()))); if (authenticationContext.isForceAuthn()) { unsignedUrlBuffer .append(getAsParameter("&", WilmaAuthenticationContext.PARAM_NAME_FORCE_AUTH, "true")); } final String redirectUrl = unsignedUrlBuffer.toString() + getAsParameter("&", WilmaAuthenticationContext.PARAM_NAME_CHECKSUM, calculateChecksum(Mac.getInstance(algorithm), unsignedUrlBuffer.toString(), signatureKey)); return redirectUrl; } catch (EncoderException | NoSuchAlgorithmException e) { log.error("{}: Could not encode the following URL {}", getLogPrefix(), redirectToBuffer, e); } return null; }
From source file:net.sf.gazpachoquest.rest.auth.TokenStore.java
private String encode(final long expires, final String userId, final int token, final SecretKey key) throws IllegalStateException, UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {// w ww. j a v a 2 s. c o m String cookiePayload = String.valueOf(token) + String.valueOf(expires) + "@" + userId; Mac m = Mac.getInstance(HMAC_SHA1); m.init(key); m.update(cookiePayload.getBytes(UTF_8)); String cookieValue = byteToHex(m.doFinal()); return cookieValue + "@" + cookiePayload; }
From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java
/** * {@inheritDoc}/*from ww w . ja v a 2 s.c o m*/ */ @Override public final byte[] macSha256(byte[] dataToMac, byte[] key) throws McbpCryptoException { final String algorithm = "HmacSHA256"; SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); try { Mac sha256Hmac = Mac.getInstance(algorithm); sha256Hmac.init(secretKey); return sha256Hmac.doFinal(dataToMac); } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new McbpCryptoException(e.toString()); } }
From source file:com.iorga.iraj.security.SecurityUtils.java
public static String computeDataSignature(final String secretAccessKey, final String data) throws NoSuchAlgorithmException, InvalidKeyException { final SecretKeySpec secretKeySpec = new SecretKeySpec(secretAccessKey.getBytes(UTF8_CHARSET), "HmacSHA1"); final Mac mac = Mac.getInstance("HmacSHA1"); mac.init(secretKeySpec);//from w w w. j a v a 2 s . c o m final String signature = Base64.encodeBase64String(mac.doFinal(data.getBytes(UTF8_CHARSET))); return StringUtils.chomp(signature); }
From source file:jp.co.opentone.bsol.linkbinder.util.ValueFormatter.java
/** * ??SHA256???//from w w w . jav a2s .co m * @param value ?? * @param key * @return ?? */ public static String formatValueToHash(String value, String key) { byte[] result; try { SecretKeySpec sk = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(sk); result = mac.doFinal(value.getBytes("UTF-8")); } catch (Exception e) { throw new RuntimeException(e); } return new String(Hex.encodeHex(result)); }
From source file:com.here.account.auth.SignatureCalculator.java
private String generateSignature(String signatureBaseString, String signatureMethod) { try {/*from w ww . j av a 2 s . c om*/ //get the bytes from the signature base string byte[] bytesToSign = signatureBaseString.getBytes(OAuthConstants.UTF_8_CHARSET); //create the signing key from the clientSecret byte[] keyBytes = (urlEncode(consumerSecret) + "&").getBytes(OAuthConstants.UTF_8_CHARSET); SecretKeySpec signingKey = new SecretKeySpec(keyBytes, signatureMethod); //generate signature based on the requested signature method Mac mac = Mac.getInstance(signatureMethod); mac.init(signingKey); byte[] signedBytes = mac.doFinal(bytesToSign); return Base64.encodeBase64String(signedBytes); } catch (Exception e) { throw new IllegalArgumentException(e); } }
From source file:com.xeiam.xchange.mtgox.v2.service.streaming.SocketMessageFactory.java
private String signedCall(String endPoint, Map<String, String> params, String reqId) throws JsonProcessingException, UnsupportedEncodingException { long nonce = MtGoxUtils.getNonce(); HashMap<String, Object> call = new HashMap<String, Object>(6); call.put("id", reqId); call.put("call", endPoint); call.put("nonce", nonce); call.put("params", params); ObjectMapper mapper = new ObjectMapper(); String callString = mapper.writeValueAsString(call); String signedCall = null;//from w w w . ja v a2 s. c o m try { byte[] bsecret = Base64.decode(this.apiSecret); SecretKeySpec spec = new SecretKeySpec(bsecret, "HmacSHA512"); Mac mac = Mac.getInstance("HmacSHA512"); mac.init(spec); byte[] bsig = mac.doFinal(callString.getBytes()); byte[] keyB = fromHexString(this.apiKey.replaceAll("-", "")); byte[] callB = callString.getBytes(); byte[] c = new byte[bsig.length + keyB.length + callB.length]; System.arraycopy(keyB, 0, c, 0, keyB.length); System.arraycopy(bsig, 0, c, keyB.length, bsig.length); System.arraycopy(callB, 0, c, keyB.length + bsig.length, callB.length); signedCall = Base64.encodeBytes(c); } catch (Exception e) { System.out.println("e!: " + e); } HashMap<String, String> msg = new HashMap<String, String>(4); msg.put("op", "call"); msg.put("call", signedCall); msg.put("id", reqId); msg.put("context", "mtgox.com"); mapper = new ObjectMapper(); return mapper.writeValueAsString(msg); }