org.apache.commons.codec.digest.DigestUtils Java Examples
The following examples show how to use
org.apache.commons.codec.digest.DigestUtils.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MapperFactory.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public static Mapper getMapper(String... mappingFiles) { Set<String> mappingSet = new TreeSet(); mappingSet.addAll(Arrays.asList(mappingFiles)); MessageDigest complete = DigestUtils.getMd5Digest(); Iterator i$ = mappingSet.iterator(); while(i$.hasNext()) { String mapping = (String)i$.next(); complete.update(mapping.getBytes()); } String key = new String(Base64.encode(complete.digest())); if (!cache.containsKey(key)) { Map<String, Object> options = new HashMap(); options.put("be.ehealth.technicalconnector.mapper.configfiles", mappingFiles); try { cache.put(key, helper.getImplementation(options)); } catch (TechnicalConnectorException var6) { throw new IllegalArgumentException(var6); } } return (Mapper)cache.get(key); }
Example #2
Source File: JsonFilePageModelPipeline.java From webmagic with Apache License 2.0 | 6 votes |
@Override public void process(Object o, Task task) { String path = this.path + PATH_SEPERATOR + task.getUUID() + PATH_SEPERATOR; try { String filename; if (o instanceof HasKey) { filename = path + ((HasKey) o).key() + ".json"; } else { filename = path + DigestUtils.md5Hex(ToStringBuilder.reflectionToString(o)) + ".json"; } PrintWriter printWriter = new PrintWriter(new FileWriter(getFile(filename))); printWriter.write(JSON.toJSONString(o)); printWriter.close(); } catch (IOException e) { logger.warn("write file error", e); } }
Example #3
Source File: MapperFactory.java From freehealth-connector with GNU Affero General Public License v3.0 | 6 votes |
public static Mapper getMapper(String... mappingFiles) { Set<String> mappingSet = new TreeSet(); mappingSet.addAll(Arrays.asList(mappingFiles)); MessageDigest complete = DigestUtils.getMd5Digest(); Iterator i$ = mappingSet.iterator(); while(i$.hasNext()) { String mapping = (String)i$.next(); complete.update(mapping.getBytes()); } String key = new String(Base64.encode(complete.digest())); if (!cache.containsKey(key)) { Map<String, Object> options = new HashMap(); options.put("be.ehealth.technicalconnector.mapper.configfiles", mappingFiles); try { cache.put(key, helper.getImplementation(options)); } catch (TechnicalConnectorException var6) { throw new IllegalArgumentException(var6); } } return (Mapper)cache.get(key); }
Example #4
Source File: DocumentDAOImpl.java From icure-backend with GNU General Public License v2.0 | 6 votes |
@Override protected void beforeSave(Document entity) { super.beforeSave(entity); if (entity.getAttachment() != null) { String newAttachmentId = DigestUtils.sha256Hex(entity.getAttachment()); if (!newAttachmentId.equals(entity.getAttachmentId())) { if (entity.getAttachments().containsKey(entity.getAttachmentId())) { entity.setRev(deleteAttachment(entity.getId(), entity.getRev(), entity.getAttachmentId())); entity.getAttachments().remove(entity.getAttachmentId()); } entity.setAttachmentId(newAttachmentId); entity.setAttachmentDirty(true); } } else { if (entity.getAttachmentId() != null) { entity.setRev(deleteAttachment(entity.getId(), entity.getRev(), entity.getAttachmentId())); entity.setAttachmentId(null); entity.setAttachmentDirty(false); } } }
Example #5
Source File: PackageStoreAPI.java From lucene-solr with Apache License 2.0 | 6 votes |
private void validate(List<String> sigs, ByteBuffer buf) throws SolrException, IOException { Map<String, byte[]> keys = packageStore.getKeys(); if (keys == null || keys.isEmpty()) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "package store does not have any keys"); } CryptoKeys cryptoKeys = null; try { cryptoKeys = new CryptoKeys(keys); } catch (Exception e) { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error parsing public keys in Package store"); } for (String sig : sigs) { if (cryptoKeys.verify(sig, buf) == null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Signature does not match any public key : " + sig +" len: "+buf.limit()+ " content sha512: "+ DigestUtils.sha512Hex(new ByteBufferInputStream(buf))); } } }
Example #6
Source File: SeventeenBroadcastService.java From Alice-LiveMan with GNU Affero General Public License v3.0 | 6 votes |
@Override public String getBroadcastCookies(String username, String password, String captcha) throws Exception { Map<String, String> requestHeader = buildRequestHeader(null); String loginJSON = HttpRequestUtil.downloadUrl(new URI(API_17APP_GATEWAY), null, "data={\"openID\":\"" + username + "\",\"password\":\"" + DigestUtils.md5Hex(password) + "\",\"action\":\"loginAction\"}", requestHeader, StandardCharsets.UTF_8); JSONObject loginObj = JSONObject.parseObject(loginJSON).getJSONObject("data"); if ("success".equals(loginObj.get("result"))) { return loginObj.getString("accessToken"); } else { log.error("17Live登录失败" + loginJSON); String message = loginObj.getString("message"); if ("no_such_user".equals(message)) { throw new RuntimeException("用户名或密码错误"); } else { throw new RuntimeException("未知错误[" + message + "]"); } } }
Example #7
Source File: AgentRegistrationControllerTest.java From gocd with Apache License 2.0 | 6 votes |
@Test public void checkAgentStatusShouldIncludeMd5Checksum_forAgent_forLauncher_whenChecksumsAreCached() throws Exception { when(pluginsZip.md5()).thenReturn("plugins-zip-md5"); when(systemEnvironment.get(AGENT_EXTRA_PROPERTIES)).thenReturn("extra=property"); controller.checkAgentStatus(response); try (InputStream stream = JarDetector.tfsJar(systemEnvironment).getJarURL().openStream()) { assertEquals(DigestUtils.md5Hex(stream), response.getHeader(SystemEnvironment.AGENT_TFS_SDK_MD5_HEADER)); } try (InputStream stream = JarDetector.create(systemEnvironment, "agent-launcher.jar").invoke()) { assertEquals(DigestUtils.md5Hex(stream), response.getHeader(SystemEnvironment.AGENT_LAUNCHER_CONTENT_MD5_HEADER)); } try (InputStream stream = JarDetector.create(systemEnvironment, "agent.jar").invoke()) { assertEquals(DigestUtils.md5Hex(stream), response.getHeader(SystemEnvironment.AGENT_CONTENT_MD5_HEADER)); } assertEquals("plugins-zip-md5", response.getHeader(SystemEnvironment.AGENT_PLUGINS_ZIP_MD5_HEADER)); }
Example #8
Source File: AbstractMarkupDocBuilder.java From markup-document-builder with Apache License 2.0 | 6 votes |
protected String normalizeAnchor(Markup spaceEscape, String anchor) { String normalizedAnchor = defaultString(anchorPrefix) + anchor.trim(); normalizedAnchor = Normalizer.normalize(normalizedAnchor, Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); normalizedAnchor = ANCHOR_IGNORABLE_PATTERN.matcher(normalizedAnchor).replaceAll(spaceEscape.toString()); normalizedAnchor = normalizedAnchor.replaceAll(String.format("([%1$s])([%1$s]+)", ANCHOR_SEPARATION_CHARACTERS), "$1"); normalizedAnchor = StringUtils.strip(normalizedAnchor, ANCHOR_SEPARATION_CHARACTERS); normalizedAnchor = normalizedAnchor.trim().toLowerCase(); String validAnchor = ANCHOR_UNIGNORABLE_PATTERN.matcher(normalizedAnchor).replaceAll(""); if (validAnchor.length() != normalizedAnchor.length()) normalizedAnchor = DigestUtils.md5Hex(normalizedAnchor); else normalizedAnchor = validAnchor; return normalizedAnchor; }
Example #9
Source File: RestController.java From codenjoy with GNU General Public License v3.0 | 6 votes |
private void regeneratePlayerPassword(Player player) { String generated = generator.password(); // это делает фронтенд, но у нас тут чистый пароль String md5 = DigestUtils.md5Hex(generated); // еще раз захешируем String hashed = passwordEncoder.encode(md5); player.setPassword(hashed); // и подсчитаем code(md5(bcrypt(password))) player.setCode(Hash.getCode(player.getId(), hashed)); players.update(player); sms.sendSmsTo(player.getPhone(), generated, SmsService.SmsType.NEW_PASSWORD); ticket.logInfo(String.format("Updated password '%s' for %s", generated, new ServerLocation(player))); }
Example #10
Source File: AssetService.java From mojito with Apache License 2.0 | 6 votes |
/** * Indicates if an asset needs to be updated. * <p> * First compare the asset content with the new content and the options used for the extraction. If the contents are * the same check that the last successful extraction correspond to the * latest version of the asset. If not it means an issue happen before and * that regardless of the content being the same, the asset needs to updated * and reprocessed. * * @param assetContent The asset to be compared * @param newAssetContent The content to be compared * @param optionsMd5 * @return true if the content of the asset is different from the new * content, false otherwise */ private boolean isAssetProcessingNeeded(AssetExtractionByBranch assetExtractionByBranch, String newAssetContent, List<String> newFilterOptions) { boolean assetProcessingNeeded = false; if (assetExtractionByBranch == null) { logger.debug("No active asset extraction, processing needed"); assetProcessingNeeded = true; } else if (assetExtractionByBranch.getDeleted()) { logger.debug("Asset extraction deleted, processing needed"); assetProcessingNeeded = true; } else if (!DigestUtils.md5Hex(newAssetContent).equals(assetExtractionByBranch.getAssetExtraction().getContentMd5())) { logger.debug("Content has changed, processing needed"); assetProcessingNeeded = true; } else if (!filterOptionsMd5Builder.md5(newFilterOptions).equals(assetExtractionByBranch.getAssetExtraction().getFilterOptionsMd5())) { logger.debug("filter options have changed, processing needed"); assetProcessingNeeded = true; } else { logger.debug("Asset processing not needed"); } return assetProcessingNeeded; }
Example #11
Source File: SyncOrganization.java From o2oa with GNU Affero General Public License v3.0 | 6 votes |
private Unit checkUnit(Business business, PullResult result, Unit sup, Department org) throws Exception { Unit unit = business.unit().getWithQiyeweixinIdObject(Objects.toString(org.getId())); if (null != unit) { if ((null == sup) && (StringUtils.isNotEmpty(unit.getSuperior()))) { /* 不是一个顶层组织所以只能删除重建 */ removeUnit(business, result, unit); unit = null; } if ((null != sup) && (!StringUtils.equals(sup.getId(), unit.getSuperior()))) { /* 指定的上级部门和预期不符 */ removeUnit(business, result, unit); unit = null; } } if (null == unit) { unit = this.createUnit(business, result, sup, org); } else { if (!StringUtils.equals(unit.getQiyeweixinHash(), DigestUtils.sha256Hex(XGsonBuilder.toJson(org)))) { logger.print("组织【{}】的hash值变化,更新组织====",org.getName()); unit = this.updateUnit(business, result, unit, org); } } return unit; }
Example #12
Source File: IpaLoader.java From unidbg with Apache License 2.0 | 6 votes |
protected String[] getEnvs(File rootDir) throws IOException { List<String> list = new ArrayList<>(); list.add("PrintExceptionThrow=YES"); // log backtrace of every objc_exception_throw() if (log.isDebugEnabled()) { list.add("OBJC_HELP=YES"); // describe available environment variables // list.add("OBJC_PRINT_OPTIONS=YES"); // list which options are set // list.add("OBJC_PRINT_INITIALIZE_METHODS=YES"); // log calls to class +initialize methods list.add("OBJC_PRINT_CLASS_SETUP=YES"); // log progress of class and category setup list.add("OBJC_PRINT_PROTOCOL_SETUP=YES"); // log progress of protocol setup list.add("OBJC_PRINT_IVAR_SETUP=YES"); // log processing of non-fragile ivars list.add("OBJC_PRINT_VTABLE_SETUP=YES"); // log processing of class vtables } UUID uuid = UUID.nameUUIDFromBytes(DigestUtils.md5(appDir + "_Documents")); String homeDir = "/var/mobile/Containers/Data/Application/" + uuid.toString().toUpperCase(); list.add("CFFIXED_USER_HOME=" + homeDir); FileUtils.forceMkdir(new File(rootDir, homeDir)); return list.toArray(new String[0]); }
Example #13
Source File: ConnectionInformationFileUtils.java From rapidminer-studio with GNU Affero General Public License v3.0 | 6 votes |
/** * Copies the given files to the specified {@code root/dirName} and creates {@code .md5} hash files for each. */ static void copyFilesToZip(Path root, List<Path> filesToCopy, String dirName) throws IOException { if (filesToCopy == null || filesToCopy.isEmpty() || dirName == null) { return; } Path path = root.resolve(dirName); Files.createDirectory(path); MessageDigest md5 = DigestUtils.getMd5Digest(); for (Path fileToCopy : filesToCopy) { Path fileName = fileToCopy.getFileName(); Path nestedFilePath = path.resolve(fileName.toString()); try (InputStream is = Files.newInputStream(fileToCopy); DigestInputStream dis = new DigestInputStream(is, md5); BufferedWriter md5Writer = Files.newBufferedWriter(path.resolve(fileName + ConnectionInformationSerializer.MD5_SUFFIX))) { Files.copy(dis, nestedFilePath); md5Writer.write(Hex.encodeHexString(md5.digest())); } } }
Example #14
Source File: RedisConfig.java From eladmin with Apache License 2.0 | 6 votes |
/** * 自定义缓存key生成策略,默认将使用该策略 */ @Bean @Override public KeyGenerator keyGenerator() { return (target, method, params) -> { Map<String,Object> container = new HashMap<>(3); Class<?> targetClassClass = target.getClass(); // 类地址 container.put("class",targetClassClass.toGenericString()); // 方法名称 container.put("methodName",method.getName()); // 包名称 container.put("package",targetClassClass.getPackage()); // 参数列表 for (int i = 0; i < params.length; i++) { container.put(String.valueOf(i),params[i]); } // 转为JSON字符串 String jsonString = JSON.toJSONString(container); // 做SHA256 Hash计算,得到一个SHA256摘要作为Key return DigestUtils.sha256Hex(jsonString); }; }
Example #15
Source File: BeamSalUhfSpecialTypeAndValueTest.java From beam with Apache License 2.0 | 6 votes |
@Test public void testSHA512() throws Exception { Schema resultType = Schema.builder().addByteArrayField("field").build(); Row resultRow1 = Row.withSchema(resultType).addValues(DigestUtils.sha512("foobar".getBytes(UTF_8))).build(); Row resultRow2 = Row.withSchema(resultType).addValues(DigestUtils.sha512(" ".getBytes(UTF_8))).build(); Row resultRow3 = Row.withSchema(resultType) .addValues(DigestUtils.sha512("abcABCжщфЖЩФ".getBytes(UTF_8))) .build(); String sql = "SELECT SHA512(f_bytes) FROM PCOLLECTION WHERE f_func = 'HashingFn'"; PCollection<Row> result = boundedInputBytes.apply("testUdf", SqlTransform.query(sql)); PAssert.that(result).containsInAnyOrder(resultRow1, resultRow2, resultRow3); pipeline.run().waitUntilFinish(); }
Example #16
Source File: LineRegexReplaceInRegionBolt.java From cognition with Apache License 2.0 | 6 votes |
@Override protected void execute(Tuple tuple, RecordCollector collector) { byte[] bytes = (byte[]) tuple.getValue(0); String record = new String(bytes); String sha1Checksum = DigestUtils.shaHex(bytes); if (StringUtils.isBlank(record)) { // skips blank entries logger.info("received blank record"); return; } LogRecord logRecord = new LogRecord(sha1Checksum); logRecord.addMetadataValue(SHA1_CHECKSUM, sha1Checksum); String recordAfterReplace = replaceAll(record); populateLogRecord(logRecord, recordAfterReplace); collector.emit(logRecord); }
Example #17
Source File: GitHubRiver.java From elasticsearch-river-github with Apache License 2.0 | 6 votes |
private IndexRequest indexOther(JsonElement e, String type, boolean overwrite) { JsonObject obj = e.getAsJsonObject(); // handle objects that don't have IDs (i.e. labels) // set the ID to the MD5 hash of the string representation String id; if (obj.has("id")) { id = obj.get("id").getAsString(); } else { id = DigestUtils.md5Hex(e.toString()); } IndexRequest req = new IndexRequest(index) .type(type) .id(id).create(!overwrite) .source(e.toString()); return req; }
Example #18
Source File: TestDisconnectedSecurityInfo.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testInfoPopulation() { DisconnectedSecurityInfo info = new DisconnectedSecurityInfo(); info.addEntry("user", "ph", ImmutableList.of("r"), ImmutableList.of("g")); String userSha = DigestUtils.sha256Hex("user"); DisconnectedSecurityInfo.Entry entry = info.getEntry("user"); Assert.assertEquals(userSha, entry.getUserNameSha()); Assert.assertEquals("ph", entry.getPasswordHash()); Assert.assertEquals(ImmutableList.of("r"), entry.getRoles()); }
Example #19
Source File: Transaction.java From jblockchain with Apache License 2.0 | 5 votes |
/** * Calculates the hash using relevant fields of this type * @return SHA256-hash as raw bytes */ public byte[] calculateHash() { byte[] hashableData = ArrayUtils.addAll(text.getBytes(), senderHash); hashableData = ArrayUtils.addAll(hashableData, signature); hashableData = ArrayUtils.addAll(hashableData, Longs.toByteArray(timestamp)); return DigestUtils.sha256(hashableData); }
Example #20
Source File: DocUtil.java From smart-doc with Apache License 2.0 | 5 votes |
/** * Use md5 generate id number * * @param value value * @return String */ public static String generateId(String value) { if (StringUtil.isEmpty(value)) { return null; } String valueId = DigestUtils.md5Hex(value); int length = valueId.length(); if (valueId.length() < 32) { return valueId; } else { return valueId.substring(length - 32, length); } }
Example #21
Source File: FileUtil.java From cloud-service with MIT License | 5 votes |
/** * 文件的md5 * * @param inputStream * @return */ public static String fileMd5(InputStream inputStream) { try { return DigestUtils.md5Hex(inputStream); } catch (IOException e) { e.printStackTrace(); } return null; }
Example #22
Source File: LearningResourceStoreService.java From sakai with Educational Community License v2.0 | 5 votes |
/** * Construct an actor using an email address * This should not be used directly. Instead LearningResourceStoreService.getActor() should be used to fill in all account details * @param email the user email address */ public LRS_Actor(String email) { this(); if (email == null) { throw new IllegalArgumentException("LRS_Actor email cannot be null"); } mbox = "mailto:"+email; mbox_sha1sum = DigestUtils.sha1Hex(mbox); }
Example #23
Source File: TezClientUtils.java From tez with Apache License 2.0 | 5 votes |
public static byte[] getLocalSha(Path path, Configuration conf) throws IOException { InputStream is = null; try { is = FileSystem.getLocal(conf).open(path); return DigestUtils.sha256(is); } finally { if (is != null) { is.close(); } } }
Example #24
Source File: AlarmSqlImpl.java From monasca-thresh with Apache License 2.0 | 5 votes |
private MetricDefinitionDimensionsDb insertMetricDefinitionDimension(final Session session, final MetricDefinitionAndTenantId mdtId) { final MetricDefinitionDb metricDefinition = this.insertMetricDefinition(session, mdtId); final BinaryId metricDimensionSetId = this.insertMetricDimensionSet(session, mdtId.metricDefinition.dimensions); final byte[] definitionDimensionsIdSha1Hash = DigestUtils.sha( metricDefinition.getId().toHexString() + metricDimensionSetId.toHexString() ); final MetricDefinitionDimensionsDb metricDefinitionDimensions = new MetricDefinitionDimensionsDb( definitionDimensionsIdSha1Hash, metricDefinition, metricDimensionSetId ); return (MetricDefinitionDimensionsDb) session.merge(metricDefinitionDimensions); }
Example #25
Source File: AssetContentService.java From mojito with Apache License 2.0 | 5 votes |
/** * Creates an {@link AssetContent} for a given {@link Branch}. * * @param asset * @param content * @param extractedContent * @param branch * @return */ public AssetContent createAssetContent(Asset asset, String content, boolean extractedContent, Branch branch) { logger.debug("Create asset content for asset id: {} and branch id: {}", asset.getId(), branch.getId()); AssetContent assetContent = new AssetContent(); assetContent.setAsset(asset); assetContent.setContent(content); assetContent.setContentMd5(DigestUtils.md5Hex(content)); assetContent.setBranch(branch); assetContent.setExtractedContent(extractedContent); assetContent = assetContentRepository.save(assetContent); return assetContent; }
Example #26
Source File: Hasher.java From extra-enforcer-rules with Apache License 2.0 | 5 votes |
private String hashForFileInDirectory( File artifactFile ) throws IOException { File classFile = new File( artifactFile, classFilePath ); InputStream inputStream = new FileInputStream( classFile ); try { return DigestUtils.md5Hex( inputStream ); } finally { closeAll( inputStream ); } }
Example #27
Source File: TestUserSessionSource.java From cuba with Apache License 2.0 | 5 votes |
public User createTestUser() { User user = new User(); user.setId(UUID.fromString(USER_ID)); user.setLogin("test_admin"); user.setName("Test Administrator"); user.setPassword(DigestUtils.md5Hex("test_admin")); return user; }
Example #28
Source File: SakaiReport.java From sakai with Educational Community License v2.0 | 5 votes |
protected boolean validateHash(String sessionid, String query, String hash) { // TODO add in shared secret to make this safer String calculatedHash = DigestUtils.sha256Hex(sessionid + query); log.info("received hash of: " + hash + " calculated hash value as: " + calculatedHash); return hash.equals(calculatedHash); }
Example #29
Source File: EmbeddedKettleTransformationProducer.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 5 votes |
public Object getQueryHash( final ResourceManager resourceManager, final ResourceKey resourceKey ) { final ArrayList<Object> retval = internalGetQueryHash(); retval.add( pluginId ); if ( rawBytes != null ) { retval.add( DigestUtils.sha256Hex( rawBytes ) ); } else { retval.add( Boolean.FALSE ); } return retval; }
Example #30
Source File: Block.java From blockchain with MIT License | 5 votes |
/** * Calculate new hash based on blocks contents * @param block 区块 * @return */ public static String calculateHash(Block block) { String record = block.getIndex() + block.getTimestamp() + block.getNonce() + block.getPrevHash()+block.getMerkleRoot(); MessageDigest digest = DigestUtils.getSha256Digest(); byte[] hash = digest.digest(StringUtils.getBytesUtf8(record)); return Hex.encodeHexString(hash); }