List of usage examples for org.apache.commons.codec.binary Hex encodeHex
public static char[] encodeHex(byte[] data)
From source file:com.tiempometa.muestradatos.ReaderContext.java
public static String readTid(String epc, Integer tid_length) throws ReaderException { String tid = null;//from w w w.j a va 2 s . c om TagData target = new TagData(epc); if (tid_length == null) { tid_length = 16; } try { tid = String.valueOf( Hex.encodeHex(ReaderContext.readTagMemBytes(target, Gen2.Bank.TID.ordinal(), 0, tid_length))); logger.debug("Got " + tid_length + " byte TID"); } catch (Exception e2) { logger.error("Error reading " + tid_length + " byte TID. Falling back to 12 bit TID."); e2.printStackTrace(); tid = String .valueOf(Hex.encodeHex(ReaderContext.readTagMemBytes(target, Gen2.Bank.TID.ordinal(), 0, 12))); logger.debug("Got 12 byte TID"); } return tid; }
From source file:com.concursive.connect.web.modules.admin.actions.AdminSync.java
public String executeCommandStartSync(ActionContext context) { if (!getUser(context).getAccessAdmin()) { return "PermissionError"; }//from w w w . j a v a2s . com if (!hasMatchingFormToken(context)) { return "TokenError"; } boolean isValid = false; String serverURL = null; String apiClientId = null; String apiCode = null; String startSync = null; String saveConnectionDetails = null; Connection db = null; try { Scheduler scheduler = (Scheduler) context.getServletContext().getAttribute(Constants.SCHEDULER); Vector syncStatus = (Vector) scheduler.getContext().get("CRMSyncStatus"); String syncListings = context.getRequest().getParameter("syncListings"); startSync = context.getRequest().getParameter("startSync"); if ("true".equals(startSync)) { isValid = true; if (syncStatus != null && syncStatus.size() == 0) { // Trigger the sync job triggerJob(context, "syncSystem", syncListings); } else { // Do nothing as a sync is already in progress. } } saveConnectionDetails = context.getRequest().getParameter("saveConnectionDetails"); if ("true".equals(saveConnectionDetails)) { ApplicationPrefs prefs = this.getApplicationPrefs(context); serverURL = context.getRequest().getParameter("serverURL"); apiClientId = context.getRequest().getParameter("apiClientId"); apiCode = context.getRequest().getParameter("apiCode"); String domainAndPort = ""; if (serverURL.indexOf("http://") != -1) { domainAndPort = serverURL.substring(7).split("/")[0]; } else if (serverURL.indexOf("https://") != -1) { domainAndPort = serverURL.substring(8).split("/")[0]; } String domain = domainAndPort; if (domainAndPort.indexOf(":") != -1) { domain = domainAndPort.split(":")[0]; } if (StringUtils.hasText(serverURL) && StringUtils.hasText(domain) && StringUtils.hasText(apiClientId) && StringUtils.hasText(apiCode)) { if (testConnection(serverURL, domain, apiCode, apiClientId)) { isValid = true; prefs.add("CONCURSIVE_CRM.SERVER", serverURL); prefs.add("CONCURSIVE_CRM.ID", domain); prefs.add("CONCURSIVE_CRM.CODE", apiCode); prefs.add("CONCURSIVE_CRM.CLIENT", apiClientId); prefs.save(); triggerJob(context, "syncSystem", syncListings); //Set the connect user performing the first sync to have crm admin role db = this.getConnection(context); User user = getUser(context); user.setConnectCRMAdmin(true); user.update(db); //Add a sync client and send that information over to the Mgmt CRM Server Key key = (Key) context.getServletContext().getAttribute(ApplicationPrefs.TEAM_KEY); SyncClient syncClient = new SyncClient(); syncClient.setType(prefs.get(ApplicationPrefs.PURPOSE)); syncClient.setCode(new String(Hex.encodeHex(key.getEncoded()))); syncClient.setEnabled(true); syncClient.setEnteredBy(user.getId()); syncClient.setModifiedBy(user.getId()); boolean recorded = syncClient.insert(db); if (recorded) { CRMConnection connection = new CRMConnection(); connection.setUrl(serverURL); connection.setId(domain); connection.setCode(apiCode); connection.setClientId(apiClientId); DataRecord record = new DataRecord(); record.setName(MAP); record.setAction(SAVE_CONNECT_SYNC_INFO_SERVICE); record.addField("connectURL", getServerUrl(context)); if (StringUtils.hasText(prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME))) { record.addField("connectDomain", prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME)); } else { record.addField("connectDomain", context.getRequest().getServerName()); } record.addField("connectSyncClientId", syncClient.getId()); record.addField("connectSyncClientCode", syncClient.getCode()); connection.save(record); if (!connection.hasError()) { LOG.debug( "Connect Sync connection information has been successfully transmitted..."); } else { LOG.debug("Connect Sync connection information transmission failed..."); } } } } } } catch (Exception e) { context.getRequest().setAttribute("Error", e); return ("SystemError"); } finally { this.freeConnection(context, db); } if (!isValid && "true".equals(saveConnectionDetails)) { context.getRequest().setAttribute("serverURL", context.getRequest().getParameter("serverURL")); context.getRequest().setAttribute("apiClientId", context.getRequest().getParameter("apiClientId")); context.getRequest().setAttribute("apiCode", context.getRequest().getParameter("apiCode")); context.getRequest().setAttribute("actionError", "Could not connect to the CRM"); return executeCommandDefault(context); } return "StartSyncOK"; }
From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileT.java
protected XAdESTimeStampType createXAdESTimeStamp(DigestAlgorithm algorithm, byte[] digest) throws IOException { LOG.info("Create timestamp for digest " + new String(Hex.encodeHex(digest))); TimeStampResponse resp = tspSource.getTimeStampResponse(algorithm, digest); byte[] timeStampToken = resp.getTimeStampToken().getEncoded(); XAdESTimeStampType xadesTimeStamp = xadesObjectFactory.createXAdESTimeStampType(); CanonicalizationMethodType c14nMethod = getXmldsigObjectFactory().createCanonicalizationMethodType(); c14nMethod.setAlgorithm(CanonicalizationMethod.EXCLUSIVE); xadesTimeStamp.setCanonicalizationMethod(c14nMethod); xadesTimeStamp.setId("time-stamp-" + UUID.randomUUID().toString()); EncapsulatedPKIDataType encapsulatedTimeStamp = xadesObjectFactory.createEncapsulatedPKIDataType(); encapsulatedTimeStamp.setValue(timeStampToken); encapsulatedTimeStamp.setId("time-stamp-token-" + UUID.randomUUID().toString()); List<Serializable> timeStampContent = xadesTimeStamp.getEncapsulatedTimeStampOrXMLTimeStamp(); timeStampContent.add(encapsulatedTimeStamp); return xadesTimeStamp; }
From source file:net.solarnetwork.node.backup.s3.S3BackupService.java
private String calculateContentDigest(BackupResource rsrc, MessageDigest digest, byte[] buf, ObjectMetadata objectMetadata) throws IOException { // S3 client buffers to RAM unless content length set; so since we have to calculate the // SHA256 digest of the content anyway, also calculate the content length at the same time long contentLength = 0; digest.reset();/* w w w.j av a 2 s. c o m*/ int len = 0; try (InputStream rsrcIn = rsrc.getInputStream()) { while ((len = rsrcIn.read(buf)) >= 0) { digest.update(buf, 0, len); contentLength += len; } } objectMetadata.setContentLength(contentLength); return new String(Hex.encodeHex(digest.digest())); }
From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypter.java
protected void writeKeyfile(TarArchiveOutputStream tarArchiveOutputStream, ParametersWithIV cipherParameters) throws IOException, InvalidCipherTextException { final KeyParameter keyParameter = (KeyParameter) cipherParameters.getParameters(); final byte[] keyBytes = keyParameter.getKey(); final char[] keyHexChars = Hex.encodeHex(keyBytes); final byte[] ivBytes = cipherParameters.getIV(); final char[] ivHexChars = Hex.encodeHex(ivBytes); //Create keyfile contents final String keyfileString = new StringBuilder(keyHexChars.length + 1 + ivHexChars.length) .append(keyHexChars).append(KEYFILE_LINE_SEPERATOR).append(ivHexChars).toString(); encryptAndWrite(tarArchiveOutputStream, keyfileString, KEYFILE_ENC_NAME); }
From source file:de.innovationgate.wgpublisher.webtml.form.TMLFormProcessContext.java
/** * Add an uploaded file to the process context * @param in The data of the file/*w w w.j av a2 s .co m*/ * @param fileName The name of the file * @throws IOException * @throws NoSuchAlgorithmException */ public void addFile(InputStream in, String fileName) throws IOException, NoSuchAlgorithmException { MD5HashingInputStream hashIn = new MD5HashingInputStream(in); TemporaryFile tempFile = new TemporaryFile(fileName, hashIn, TMLContext.getThreadMainContext().getwgacore().getWgaTempDir()); DiskPCFile pcFile = new DiskPCFile(tempFile.getFile(), fileName, new String(Hex.encodeHex(hashIn.getHashBytes()))); tempFile.deleteOnEviction(pcFile); _files.put(fileName.toLowerCase(), pcFile); }
From source file:com.scm.reader.livescanner.search.SearchRequestBuilder.java
private String sign(String verb, byte[] content, String contentType, String date, String requestPath) throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] thedigest = md.digest(content); String md5sum = new String(Hex.encodeHex(thedigest)); String message = verb + "\n" + md5sum + "\n" + contentType + "\n" + date + "\n" + requestPath; String signature = signHmacSha1(mApiSecret, message); return signature; }
From source file:fi.okm.mpass.shibboleth.authn.impl.ValidateWilmaResponse.java
/** {@inheritDoc} */ @Override/*from w w w . j a va 2 s .c o m*/ protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { final HttpServletRequest servletRequest = getHttpServletRequest(); final WilmaAuthenticationContext wilmaContext = authenticationContext .getSubcontext(WilmaAuthenticationContext.class, false); final String nonce = wilmaContext.getNonce(); if (!getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_NONCE).equals(nonce)) { log.warn("{}: Invalid nonce in the incoming Wilma response!", getLogPrefix()); log.debug("{} vs {}", nonce, getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_NONCE)); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } final String checksum = getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_CHECKSUM); final String query = servletRequest.getQueryString().substring(0, servletRequest.getQueryString() .indexOf("&" + WilmaAuthenticationContext.PARAM_NAME_CHECKSUM + "=")); final String url = servletRequest.getRequestURL().append("?").append(query).toString(); try { final Mac mac = Mac.getInstance(algorithm); mac.init(macKey); byte[] digest = mac.doFinal(url.getBytes("UTF-8")); if (!Arrays.equals(DatatypeConverter.parseHexBinary(checksum), digest)) { log.warn("{}: The checksum validation failed for user {}", getLogPrefix(), getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_USER_ID)); log.trace("{} (params) vs {}", checksum, new String(Hex.encodeHex(digest))); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException | UnsupportedEncodingException | IllegalArgumentException e) { log.error("{}: Could not verify the checksum {}", getLogPrefix(), checksum, e); handleError(profileRequestContext, authenticationContext, AuthnEventIds.NO_CREDENTIALS, AuthnEventIds.NO_CREDENTIALS); return; } log.trace("{}: Building authentication result for user {}", getLogPrefix(), getQueryParam(servletRequest, WilmaAuthenticationContext.PARAM_NAME_USER_ID)); buildAuthenticationResult(profileRequestContext, authenticationContext); }
From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetLoader.java
private String getDigest(File aFile, String aDigest) throws IOException { MessageDigest digest;//from w w w . j av a 2 s .c o m try { digest = MessageDigest.getInstance(aDigest); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } try (InputStream is = new FileInputStream(aFile)) { DigestInputStream digestFilter = new DigestInputStream(is, digest); IOUtils.copy(digestFilter, new NullOutputStream()); return new String(Hex.encodeHex(digestFilter.getMessageDigest().digest())); } }
From source file:com.baidubce.auth.BceV1Signer.java
private String sha256Hex(String signingKey, String stringToSign) { try {//from ww w . j ava 2 s .c o m Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(signingKey.getBytes(UTF8), "HmacSHA256")); return new String(Hex.encodeHex(mac.doFinal(stringToSign.getBytes(UTF8)))); } catch (Exception e) { throw new BceClientException("Fail to generate the signature", e); } }