List of usage examples for javax.crypto Mac doFinal
public final byte[] doFinal() throws IllegalStateException
From source file:org.cesecore.audit.impl.queued.entity.HmacLogManagementDataTest.java
@Test public void test01LoadTokenConfigProps() throws Exception { AuditLogCryptoTokenConfigData tokenConfig = hmac.getTokenConfig(); CryptoToken token = CryptoTokenFactory.createCryptoToken(tokenConfig.getClassname(), tokenConfig.getProperties(), tokenConfig.getTokenData(), 1); token.activate(//from w w w.j a v a2s .co m ((String) tokenConfig.getProperties().get(CryptoToken.AUTOACTIVATE_PIN_PROPERTY)).toCharArray()); Key hMacKey = token.getKey(keyAlias); Mac hMac = Mac.getInstance(hmac.getAlgorithm(), token.getEncProviderName()); hMac.init(hMacKey); hMac.update(dataToBeSigned.getBytes()); byte[] signedData = hMac.doFinal(); assertTrue(ArrayUtils.isEquals(signedData, signed)); }
From source file:org.cesecore.audit.impl.queued.entity.HmacLogManagementDataTest.java
@Before public void createHmacConfig() throws Exception { log.trace(">setUp()"); tokenConfigData = new AuditLogCryptoTokenConfigData(); tokenConfigData.setClassname(SoftCryptoToken.class.getName()); Properties props = new Properties(); props.setProperty(CryptoToken.AUTOACTIVATE_PIN_PROPERTY, tokenPin); CryptoToken token = CryptoTokenFactory.createCryptoToken(SoftCryptoToken.class.getName(), props, null, 1); token.activate(tokenPin.toCharArray()); token.generateKey("HmacSHA1", 256, keyAlias); tokenConfigData.setProperties(props); hmac = new HmacLogManagementData(); hmac.setAlgorithm(algorithm);// ww w . j a va 2 s . c o m hmac.setKeyLabel(keyAlias); hmac.setFrequency(0l); hmac.setTokenConfig(tokenConfigData); byte[] tokenData = token.getTokenData(); tokenConfigData.setTokenData(tokenData); Key hMacKey = token.getKey(keyAlias); Mac hMac = Mac.getInstance(hmac.getAlgorithm(), token.getEncProviderName()); hMac.init(hMacKey); hMac.update(dataToBeSigned.getBytes()); signed = hMac.doFinal(); log.trace("<setUp()"); }
From source file:de.betterform.xml.xforms.xpath.saxon.function.Hmac.java
/** * Evaluate in a general context//from w ww . ja v a2 s.c o m */ public Item evaluateItem(XPathContext xpathContext) throws XPathException { final String key = argument[0].evaluateAsString(xpathContext).toString(); final String data = argument[1].evaluateAsString(xpathContext).toString(); final String originalAlgorithmString = argument[2].evaluateAsString(xpathContext).toString(); final String algorithm = "Hmac" + originalAlgorithmString.replaceAll("-", ""); final String encoding = argument != null && argument.length >= 4 ? argument[3].evaluateAsString(xpathContext).toString() : kBASE64; if (!kSUPPORTED_ALG.contains(originalAlgorithmString)) { XPathFunctionContext functionContext = getFunctionContext(xpathContext); XFormsElement xformsElement = functionContext.getXFormsElement(); throw new XPathException(new XFormsComputeException( "Unsupported algorithm '" + originalAlgorithmString + "'", xformsElement.getTarget(), this)); } if (!kSUPPORTED_ENCODINGS.contains(encoding)) { XPathFunctionContext functionContext = getFunctionContext(xpathContext); XFormsElement xformsElement = functionContext.getXFormsElement(); throw new XPathException(new XFormsComputeException("Unsupported encoding '" + encoding + "'", xformsElement.getTarget(), this)); } try { // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104 // In practice, you would save this key. SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"), algorithm); // Create a MAC object using HMAC-MD5 and initialize with kesaxoniay Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); mac.update(data.getBytes("utf-8")); byte[] digest = mac.doFinal(); final BinaryEncoder encoder; if ("base64".equals(encoding)) { encoder = new Base64(digest.length, "".getBytes(), false); } else { encoder = new Hex(); } return new StringValue(new String(encoder.encode(digest), "ASCII")); } catch (NoSuchAlgorithmException e) { throw new XPathException(e); } catch (UnsupportedEncodingException e) { throw new XPathException(e); } catch (EncoderException e) { XPathFunctionContext functionContext = getFunctionContext(xpathContext); XFormsElement xformsElement = functionContext.getXFormsElement(); throw new XPathException( new XFormsComputeException("Encoder exception.", e, xformsElement.getTarget(), this)); } catch (InvalidKeyException e) { throw new XPathException(e); } }
From source file:mitm.application.djigzo.james.PortalInvitationValidator.java
/** * returns the calculated MAC/*from ww w. java 2 s . com*/ */ public String calulateMAC(String key) throws ValidatorException { Check.notNull(key, "key"); if (StringUtils.isEmpty(email)) { throw new ValidatorException("email is not set"); } if (timestamp == null) { throw new ValidatorException("timestamp is not set"); } Mac mac = createMAC(key); mac.update(UNIQUE_ID); mac.update(MiscStringUtils.toUTF8Bytes(email)); mac.update(timestamp.byteValue()); byte[] hmac = mac.doFinal(); return Base32.encode(hmac); }
From source file:com.jivesoftware.sdk.service.filter.JiveAuthorizationValidator.java
@Nonnull private String sign(@Nonnull String str, @Nonnull String clientSecret, @Nonnull String algorithm) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { byte[] secret = Base64.decodeBase64(clientSecret); SecretKeySpec secretKeySpec = new SecretKeySpec(secret, algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKeySpec);/*from w w w.j av a2 s . c om*/ mac.update(str.getBytes("UTF-8")); return Base64.encodeBase64String(mac.doFinal()).replaceAll("\\s+", ""); }
From source file:org.kaaproject.kaa.server.verifiers.twitter.verifier.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(); return signature; }
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.jpeterson.littles3.bo.S3Authenticator.java
/** * Authenticate the request using the prescribed Amazon S3 authentication * mechanisms.//from w w w.jav a 2 s .c o m * * @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.jupyterkernel.kernel.MessageObject.java
private byte[] computeSignature(byte[] header, byte[] parent, byte[] meta, byte[] content) { byte[][] data = { header, parent, meta, content }; try {/*from w w w . ja v a 2 s. c om*/ 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.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 += "="; }/*w w w. j a v a 2 s. c om*/ 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; }