List of usage examples for javax.crypto Mac update
public final void update(ByteBuffer input)
From source file:com.skplanet.syruppay.token.tav.TransactionAuthenticationValue.java
public boolean isValidBy(final String key, final String checksum) throws NoSuchAlgorithmException, IOException, InvalidKeyException { final Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key.getBytes("UTF-8"), mac.getAlgorithm())); mac.update((cardToken + mctTransAuthId + ocTransAuthId + new ObjectMapper().writeValueAsString(paymentAuthenticationDetail)).getBytes("UTF-8")); return Base64.encodeBase64URLSafeString(mac.doFinal()).equals(checksum); }
From source file:com.jpeterson.littles3.bo.S3Authenticator.java
/** * Authenticate the request using the prescribed Amazon S3 authentication * mechanisms.//from w ww . j ava 2s. c om * * @param req * The original HTTP request. * @param s3Request * The S3 specific information for authenticating the request. * @return The authenticated <code>CanonicalUser</code> making the request. * @throws RequestTimeTooSkewedException * Thrown if the request timestamp is outside of the allotted * timeframe. */ public CanonicalUser authenticate(HttpServletRequest req, S3ObjectRequest s3Request) throws AuthenticatorException { // check to see if anonymous request String authorization = req.getHeader(HEADER_AUTHORIZATION); if (authorization == null) { return new CanonicalUser(CanonicalUser.ID_ANONYMOUS); } // attempting to be authenticated request if (false) { // check timestamp of request Date timestamp = s3Request.getTimestamp(); if (timestamp == null) { throw new RequestTimeTooSkewedException("No timestamp provided"); } GregorianCalendar calendar = new GregorianCalendar(); Date now = calendar.getTime(); calendar.add(Calendar.MINUTE, 15); Date maximumDate = calendar.getTime(); calendar.add(Calendar.MINUTE, -30); Date minimumDate = calendar.getTime(); if (timestamp.before(minimumDate)) { throw new RequestTimeTooSkewedException( "Timestamp [" + timestamp + "] too old. System time: " + now); } if (timestamp.after(maximumDate)) { throw new RequestTimeTooSkewedException( "Timestamp [" + timestamp + "] too new. System time: " + now); } } // authenticate request String[] fields = authorization.split(" "); if (fields.length != 2) { throw new InvalidSecurityException("Unsupported authorization format"); } if (!fields[0].equals(AUTHORIZATION_TYPE)) { throw new InvalidSecurityException("Unsupported authorization type: " + fields[0]); } String[] keys = fields[1].split(":"); if (keys.length != 2) { throw new InvalidSecurityException("Invalid AWSAccesskeyId:Signature"); } String accessKeyId = keys[0]; String signature = keys[1]; String secretAccessKey = userDirectory.getAwsSecretAccessKey(accessKeyId); String calculatedSignature; try { SecretKey key = new SecretKeySpec(secretAccessKey.getBytes(), "HmacSHA1"); Mac m = Mac.getInstance("HmacSHA1"); m.init(key); m.update(s3Request.getStringToSign().getBytes()); byte[] mac = m.doFinal(); calculatedSignature = new String(Base64.encodeBase64(mac)); } catch (NoSuchAlgorithmException e) { throw new InvalidSecurityException(e); } catch (InvalidKeyException e) { throw new InvalidSecurityException(e); } System.out.println("-----------------"); System.out.println("signature: " + signature); System.out.println("calculatedSignature: " + calculatedSignature); System.out.println("-----------------"); if (calculatedSignature.equals(signature)) { // authenticated! return userDirectory.getCanonicalUser(secretAccessKey); } else { throw new SignatureDoesNotMatchException("Provided signature doesn't match calculated value"); } }
From source file:org.janusgraph.graphdb.tinkerpop.gremlin.server.auth.HMACAuthenticator.java
private String generateToken(final String username, final String salt, final String time) { try {/*w w w. j a va 2 s. com*/ final CharBuffer secretAndSalt = CharBuffer.allocate(secret.length + salt.length() + 1); secretAndSalt.put(secret); secretAndSalt.put(":"); secretAndSalt.put(salt); final String tokenPrefix = username + ":" + time.toString() + ":"; final SecretKeySpec keySpec = new SecretKeySpec(toBytes(secretAndSalt.array()), hmacAlgo); final Mac hmac = Mac.getInstance(hmacAlgo); hmac.init(keySpec); hmac.update(username.getBytes()); hmac.update(time.toString().getBytes()); final Base64.Encoder encoder = Base64.getUrlEncoder(); final byte[] hmacbytes = encoder.encode(hmac.doFinal()); final byte[] tokenbytes = tokenPrefix.getBytes(); final byte[] token = ByteBuffer.wrap(new byte[tokenbytes.length + hmacbytes.length]).put(tokenbytes) .put(hmacbytes).array(); return new String(encoder.encode(token)); } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:id.pazpo.agent.utils.OAuthHeaderBuilder.java
private String generateSignature(String signatureBase, String accessTokenSecret) throws InvalidKeyException, NoSuchAlgorithmException { Mac mac = Mac.getInstance(ENCRYPTION_ALGO); mac.init(new SecretKeySpec((CONSUMER_SECRET + "&" + accessTokenSecret).getBytes(), ENCRYPTION_ALGO)); mac.update(signatureBase.getBytes()); byte[] res = mac.doFinal(); String signature = new String(Base64.encodeBase64(res)).trim(); Log.d("headers", signature); return signature; }
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 w w .j a v a2 s . co 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.jupyterkernel.kernel.MessageObject.java
private byte[] computeSignature(byte[] header, byte[] parent, byte[] meta, byte[] content) { byte[][] data = { header, parent, meta, content }; try {//ww w .jav a2 s . c o m SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); for (int i = 0; i < 4; i++) { mac.update(data[i]); } return mac.doFinal(); } catch (InvalidKeyException | NoSuchAlgorithmException e) { System.out.println(e.getMessage()); } return null; }
From source file:com.mnxfst.stream.listener.webtrends.WebtrendsTokenRequest.java
private String getHMAC256(final String input, final String secret) { String temp = null;//from w w w .ja v a2 s .c o m final SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); try { final Mac mac = Mac.getInstance("HmacSHA256"); mac.init(keySpec); // update method adds the given byte to the Mac's input data. mac.update(input.getBytes()); final byte[] m = mac.doFinal(); // The base64-encoder in Commons Codec temp = base64Encode(m); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } return temp; }
From source file:org.apache.nifi.processors.standard.util.crypto.scrypt.Scrypt.java
/** * Implementation of PBKDF2 (RFC2898).//from w ww . ja va 2s . c om * * @param mac the pre-initialized {@link Mac} instance to use * @param s the salt * @param c the iteration count * @param dk the byte array that derived key will be placed in * @param dkLen the intended length, in octets, of the derived key * @throws GeneralSecurityException if the key length is too long */ private static void pbkdf2(Mac mac, byte[] s, int c, byte[] dk, int dkLen) throws GeneralSecurityException { int hLen = mac.getMacLength(); if (dkLen > (Math.pow(2, 32) - 1) * hLen) { throw new GeneralSecurityException("Requested key length too long"); } byte[] U = new byte[hLen]; byte[] T = new byte[hLen]; byte[] block1 = new byte[s.length + 4]; int l = (int) Math.ceil((double) dkLen / hLen); int r = dkLen - (l - 1) * hLen; arraycopy(s, 0, block1, 0, s.length); for (int i = 1; i <= l; i++) { block1[s.length + 0] = (byte) (i >> 24 & 0xff); block1[s.length + 1] = (byte) (i >> 16 & 0xff); block1[s.length + 2] = (byte) (i >> 8 & 0xff); block1[s.length + 3] = (byte) (i >> 0 & 0xff); mac.update(block1); mac.doFinal(U, 0); arraycopy(U, 0, T, 0, hLen); for (int j = 1; j < c; j++) { mac.update(U); mac.doFinal(U, 0); for (int k = 0; k < hLen; k++) { T[k] ^= U[k]; } } arraycopy(T, 0, dk, (i - 1) * hLen, (i == l ? r : hLen)); } }
From source file:mitm.common.util.StandardHttpURLBuilder.java
@Override public String addHMAC(String name, Mac mac) throws URLBuilderException { Check.notNull(mac, "mac"); if (parameters.size() == 0) { throw new URLBuilderException("There are no values."); }//from w w w. j av a 2 s.co m for (Parameter parameter : parameters) { mac.update(MiscStringUtils.toAsciiBytes(parameter.getName())); mac.update(MiscStringUtils.toAsciiBytes(parameter.getValue())); } byte[] hmac = mac.doFinal(); String base32 = Base32.encode(hmac); parameters.add(new Parameter(name, base32)); return base32; }