List of usage examples for org.apache.commons.codec.binary Hex encodeHexString
public static String encodeHexString(byte[] data)
From source file:VerifyDescriptors.java
private static void verifyConsensuses() throws Exception { File certsDirectory = new File("in/certs"); File consensusDirectory = new File("in/consensuses"); if (!certsDirectory.exists() || !consensusDirectory.exists()) { return;/*from w w w .ja va2 s.co m*/ } Map<String, String> signingKeys = new HashMap<String, String>(); DescriptorReader certsReader = DescriptorSourceFactory.createDescriptorReader(); certsReader.addDirectory(certsDirectory); Iterator<DescriptorFile> descriptorFiles = certsReader.readDescriptors(); int processedCerts = 0, verifiedCerts = 0; while (descriptorFiles.hasNext()) { DescriptorFile descriptorFile = descriptorFiles.next(); if (descriptorFile.getException() != null) { System.err.println("Could not read/parse descriptor file " + descriptorFile.getFileName() + ": " + descriptorFile.getException().getMessage()); continue; } if (descriptorFile.getDescriptors() == null) { continue; } for (Descriptor descriptor : descriptorFile.getDescriptors()) { if (!(descriptor instanceof DirectoryKeyCertificate)) { continue; } DirectoryKeyCertificate cert = (DirectoryKeyCertificate) descriptor; boolean isVerified = true; /* Verify that the contained fingerprint is a hash of the signing * key. */ String dirIdentityKeyHashString = determineKeyHash(cert.getDirIdentityKey()); String fingerprintString = cert.getFingerprint().toLowerCase(); if (!dirIdentityKeyHashString.equals(fingerprintString)) { System.out.println("In " + descriptorFile.getFile() + ", the calculated directory identity key hash " + dirIdentityKeyHashString + " does not match the contained fingerprint " + fingerprintString + "!"); isVerified = false; } /* Verify that the router signature was created using the signing * key. */ if (!verifySignature(cert.getCertificateDigest(), cert.getDirKeyCertification(), cert.getDirIdentityKey())) { System.out.println("In " + descriptorFile.getFile() + ", the decrypted directory key certification does not " + "match the certificate digest!"); isVerified = false; } /* Determine the signing key digest and remember the signing key * to verify consensus signatures. */ String dirSigningKeyString = cert.getDirSigningKey(); PEMReader pemReader2 = new PEMReader(new StringReader(dirSigningKeyString)); RSAPublicKey dirSigningKey = (RSAPublicKey) pemReader2.readObject(); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); new ASN1OutputStream(baos2) .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirSigningKey.getModulus(), dirSigningKey.getPublicExponent()).toASN1Primitive()); byte[] pkcs2 = baos2.toByteArray(); byte[] dirSigningKeyHashBytes = new byte[20]; SHA1Digest sha1_2 = new SHA1Digest(); sha1_2.update(pkcs2, 0, pkcs2.length); sha1_2.doFinal(dirSigningKeyHashBytes, 0); String dirSigningKeyHashString = Hex.encodeHexString(dirSigningKeyHashBytes).toUpperCase(); signingKeys.put(dirSigningKeyHashString, cert.getDirSigningKey()); processedCerts++; if (isVerified) { verifiedCerts++; } } } System.out.println("Verified " + verifiedCerts + "/" + processedCerts + " certs."); DescriptorReader consensusReader = DescriptorSourceFactory.createDescriptorReader(); consensusReader.addDirectory(consensusDirectory); Iterator<DescriptorFile> consensusFiles = consensusReader.readDescriptors(); int processedConsensuses = 0, verifiedConsensuses = 0; while (consensusFiles.hasNext()) { DescriptorFile consensusFile = consensusFiles.next(); if (consensusFile.getException() != null) { System.err.println("Could not read/parse descriptor file " + consensusFile.getFileName() + ": " + consensusFile.getException().getMessage()); continue; } if (consensusFile.getDescriptors() == null) { continue; } for (Descriptor descriptor : consensusFile.getDescriptors()) { if (!(descriptor instanceof RelayNetworkStatusConsensus)) { continue; } RelayNetworkStatusConsensus consensus = (RelayNetworkStatusConsensus) descriptor; boolean isVerified = true; /* Verify all signatures using the corresponding certificates. */ if (consensus.getDirectorySignatures().isEmpty()) { System.out.println(consensusFile.getFile() + " does not contain any signatures."); continue; } for (DirectorySignature signature : consensus.getDirectorySignatures().values()) { String signingKeyDigest = signature.getSigningKeyDigest(); if (!signingKeys.containsKey(signingKeyDigest)) { System.out.println("Cannot find signing key with digest " + signingKeyDigest + "!"); } if (!verifySignature(consensus.getConsensusDigest(), signature.getSignature(), signingKeys.get(signingKeyDigest))) { System.out.println("In " + consensusFile.getFile() + ", the decrypted signature digest does not match the " + "consensus digest!"); isVerified = false; } } processedConsensuses++; if (isVerified) { verifiedConsensuses++; } } } System.out.println("Verified " + verifiedConsensuses + "/" + processedConsensuses + " consensuses."); }
From source file:com.bitbreeds.webrtc.sctp.impl.SendService.java
/** * * @param data the data to send//from w w w . jav a 2 s . c o m * @param ppid protocol id * @param header sctp header * @return payload data */ public byte[] createPayloadMessage(byte[] data, SCTPPayloadProtocolId ppid, SCTPHeader header) { logger.debug("Creating payload"); long myTSN = getNextTSN(); Map<SCTPFixedAttributeType, SCTPFixedAttribute> attr = new HashMap<>(); attr.put(TSN, new SCTPFixedAttribute(TSN, SignalUtil.longToFourBytes(myTSN))); attr.put(STREAM_IDENTIFIER_S, new SCTPFixedAttribute(STREAM_IDENTIFIER_S, SignalUtil.twoBytesFromInt(0))); attr.put(STREAM_SEQUENCE_NUMBER, new SCTPFixedAttribute(STREAM_SEQUENCE_NUMBER, SignalUtil.twoBytesFromInt(0))); attr.put(PROTOCOL_IDENTIFIER, new SCTPFixedAttribute(PROTOCOL_IDENTIFIER, new byte[] { 0, 0, 0, sign(ppid.getId()) })); int fixed = attr.values().stream().map(i -> i.getType().getLgt()).reduce(0, Integer::sum); int lgt = 4 + fixed + data.length; byte[] dataOut = SignalUtil.padToMultipleOfFour(data); SCTPChunk chunk = new SCTPChunk(SCTPMessageType.DATA, SCTPFlags.UNORDERED_UNFRAGMENTED, lgt, attr, new HashMap<>(), dataOut); SCTPMessage msg = new SCTPMessage(header, Collections.singletonList(chunk)); byte[] finalOut = SCTPUtil.addChecksum(msg).toBytes(); logger.debug("Sending payload with TSN: " + myTSN + " and data: " + Hex.encodeHexString(finalOut)); sentBytes.getAndAdd(data.length); /** * Add to resend map * Should remove on correct SACK or too large or too long map. */ addMessageToSend(myTSN, finalOut); return finalOut; }
From source file:com.continusec.client.VerifiableMap.java
/** * For a given key, return the value and inclusion proof for the given treeSize. * @param key the key in the map./*from w ww. j ava 2 s .c o m*/ * @param treeSize the tree size. * @param f the factory that should be used to instantiate the VerifiableEntry. Typically one of {@link RawDataEntryFactory#getInstance()}, {@link JsonEntryFactory#getInstance()}, {@link RedactedJsonEntryFactory#getInstance()}. * @return the value (which may be empty) and inclusion proof. * @throws ContinusecException upon error */ public MapGetEntryResponse get(byte[] key, int treeSize, VerifiableEntryFactory f) throws ContinusecException { try { ResponseData rd = this.client.makeRequest("GET", this.path + "/tree/" + treeSize + "/key/h/" + Hex.encodeHexString(key) + f.getFormat(), null, null); return new MapGetEntryResponse(key, f.createFromBytes(rd.data), parseAuditPath(rd), parseVerifiedTreeSize(rd)); } catch (DecoderException e) { throw new InternalErrorException(); } }
From source file:ch.cyberduck.core.aquaticprime.ReceiptVerifier.java
@Override public boolean verify(final LicenseVerifierCallback callback) { try {/*from w w w . j av a 2 s. c o m*/ // For additional security, you may verify the fingerprint of the root CA and the OIDs of the // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate // is (1 2 840 113635 100 6 11 1). final CMSSignedData s = new CMSSignedData(new FileInputStream(file.getAbsolute())); Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); for (SignerInformation signer : signers.getSigners()) { final Collection<X509CertificateHolder> matches = certs.getMatches(signer.getSID()); for (X509CertificateHolder holder : matches) { if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder() .setProvider(new BouncyCastleProvider()).build(holder))) { return false; } } } // Extract the receipt attributes final CMSProcessable signedContent = s.getSignedContent(); byte[] originalContent = (byte[]) signedContent.getContent(); final ASN1Primitive asn = ASN1Primitive.fromByteArray(originalContent); byte[] opaque = null; String bundleIdentifier = null; String bundleVersion = null; byte[] hash = null; if (asn instanceof ASN1Set) { // 2 Bundle identifier Interpret as an ASN.1 UTF8STRING. // 3 Application version Interpret as an ASN.1 UTF8STRING. // 4 Opaque value Interpret as a series of bytes. // 5 SHA-1 hash Interpret as a 20-byte SHA-1 digest value. final ASN1Set set = (ASN1Set) asn; final Enumeration enumeration = set.getObjects(); while (enumeration.hasMoreElements()) { Object next = enumeration.nextElement(); if (next instanceof DLSequence) { DLSequence sequence = (DLSequence) next; ASN1Encodable type = sequence.getObjectAt(0); if (type instanceof ASN1Integer) { if (((ASN1Integer) type).getValue().intValue() == 2) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleIdentifier = new String(((DEROctetString) value).getOctets(), "UTF-8"); } } else if (((ASN1Integer) type).getValue().intValue() == 3) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleVersion = new String(((DEROctetString) value).getOctets(), "UTF-8"); } } else if (((ASN1Integer) type).getValue().intValue() == 4) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { opaque = ((DEROctetString) value).getOctets(); } } else if (((ASN1Integer) type).getValue().intValue() == 5) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { hash = ((DEROctetString) value).getOctets(); } } } } } } else { log.error(String.format("Expected set of attributes for %s", asn)); return false; } if (!StringUtils.equals(application, StringUtils.trim(bundleIdentifier))) { log.error(String.format("Bundle identifier %s in ASN set does not match", bundleIdentifier)); return false; } if (!StringUtils.equals(version, StringUtils.trim(bundleVersion))) { log.warn(String.format("Bundle version %s in ASN set does not match", bundleVersion)); } final NetworkInterface en0 = NetworkInterface.getByName("en0"); if (null == en0) { // Interface is not found when link is down #fail log.warn("No network interface en0"); return true; } else { final byte[] mac = en0.getHardwareAddress(); if (null == mac) { log.error("Cannot determine MAC address"); // Continue without validation return true; } final String hex = Hex.encodeHexString(mac); if (log.isDebugEnabled()) { log.debug(String.format("Interface en0 %s", hex)); } // Compute the hash of the GUID final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(mac); if (null == opaque) { log.error(String.format("Missing opaque string in ASN.1 set %s", asn)); return false; } digest.update(opaque); if (null == bundleIdentifier) { log.error(String.format("Missing bundle identifier in ASN.1 set %s", asn)); return false; } digest.update(bundleIdentifier.getBytes(Charset.forName("UTF-8"))); final byte[] result = digest.digest(); if (Arrays.equals(result, hash)) { if (log.isInfoEnabled()) { log.info(String.format("Valid receipt for GUID %s", hex)); } guid = hex; return true; } else { log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt", hex)); return false; } } } catch (IOException | GeneralSecurityException | CMSException | SecurityException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (Exception e) { log.error("Unknown receipt validation error", e); return true; } }
From source file:de.elomagic.carafile.client.CaraFileClientTest.java
@Test public void testDownload2() throws Exception { Random random = new Random(); random.nextBytes(data0);// ww w .j av a 2 s .co m random.nextBytes(data1); chunkId0 = Hex.encodeHexString(DigestUtils.sha1(data0)); chunkId1 = Hex.encodeHexString(DigestUtils.sha1(data1)); MessageDigest messageDigest = DigestUtils.getSha1Digest(); messageDigest.update(data0); messageDigest.update(data1); id = Hex.encodeHexString(messageDigest.digest()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); client.setRegistryURI(getURI()).downloadFile(id, baos); Assert.assertArrayEquals(data0, Arrays.copyOf(baos.toByteArray(), DEFAULT_PIECE_SIZE)); Assert.assertArrayEquals(data1, Arrays.copyOfRange(baos.toByteArray(), DEFAULT_PIECE_SIZE, DEFAULT_PIECE_SIZE + 128)); }
From source file:com.streamsets.pipeline.stage.cloudstorage.origin.GoogleCloudStorageSource.java
@Override public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException { maxBatchSize = Math.min(maxBatchSize, gcsOriginConfig.basicConfig.maxBatchSize); long minTimestamp = 0; String blobGeneratedId = ""; String fileOffset = START_FILE_OFFSET; if (!Strings.isNullOrEmpty(lastSourceOffset)) { minTimestamp = getMinTimestampFromOffset(lastSourceOffset); fileOffset = getFileOffsetFromOffset(lastSourceOffset); blobGeneratedId = getBlobIdFromOffset(lastSourceOffset); }// w w w .ja v a 2 s .co m if (minMaxPriorityQueue.isEmpty()) { poolForFiles(minTimestamp, blobGeneratedId, fileOffset); } // Process Blob if (parser == null) { //Get next eligible blob to read, if none throw no more data event do { blob = minMaxPriorityQueue.pollFirst(); //We don't have any spooled files to read from and we don't have anything available from the existing parser //(in case of sdc restart with stored offset, we still want some blob to be available for us to start reading) if (blob == null) { //No more data available if (noMoreDataRecordCount > 0 || noMoreDataErrorCount > 0) { LOG.info("sending no-more-data event. records {} errors {} files {} ", noMoreDataRecordCount, noMoreDataErrorCount, noMoreDataFileCount); CommonEvents.NO_MORE_DATA.create(getContext()).with("record-count", noMoreDataRecordCount) .with("error" + "-count", noMoreDataErrorCount) .with("file-count", noMoreDataFileCount).createAndSend(); noMoreDataRecordCount = 0; noMoreDataErrorCount = 0; noMoreDataFileCount = 0; } return lastSourceOffset; } } while (!isBlobEligible(blob, minTimestamp, blobGeneratedId, fileOffset)); //If we are picking up from where we left off from previous offset //(i.e after sdc restart use the last offset, else use start file offset) fileOffset = (blobGeneratedId.equals(blob.getGeneratedId())) ? fileOffset : START_FILE_OFFSET; blobGeneratedId = blob.getGeneratedId(); if (gcsOriginConfig.dataFormat == DataFormat.WHOLE_FILE) { GCSFileRef.Builder gcsFileRefBuilder = new GCSFileRef.Builder() .bufferSize(gcsOriginConfig.dataParserFormatConfig.wholeFileMaxObjectLen) .createMetrics(true).totalSizeInBytes(blob.getSize()) .rateLimit(FileRefUtil.evaluateAndGetRateLimit(rateLimitElEval, rateLimitElVars, gcsOriginConfig.dataParserFormatConfig.rateLimit)) .blob(blob); if (gcsOriginConfig.dataParserFormatConfig.verifyChecksum) { gcsFileRefBuilder = gcsFileRefBuilder.verifyChecksum(true) .checksum(Hex.encodeHexString(Base64.getDecoder().decode(blob.getMd5()))) .checksumAlgorithm(HashingUtil.HashType.MD5); } Map<String, Object> metadata = new HashMap<>(); metadata.put(BUCKET, blob.getBucket()); metadata.put(FILE, blob.getName()); metadata.put(SIZE, blob.getSize()); Optional.ofNullable(blob.getMetadata()).ifPresent(metadata::putAll); parser = gcsOriginConfig.dataParserFormatConfig.getParserFactory().getParser(blobGeneratedId, metadata, gcsFileRefBuilder.build()); } else { parser = gcsOriginConfig.dataParserFormatConfig.getParserFactory().getParser(blobGeneratedId, Channels.newInputStream(blob.reader()), fileOffset); } minTimestamp = blob.getUpdateTime(); } try { int recordCount = 0; while (recordCount < maxBatchSize) { try { Record record = parser.parse(); if (record != null) { batchMaker.addRecord(record); fileOffset = parser.getOffset(); noMoreDataRecordCount++; recordCount++; } else { fileOffset = END_FILE_OFFSET; IOUtils.closeQuietly(parser); parser = null; noMoreDataFileCount++; break; } } catch (RecoverableDataParserException e) { LOG.error("Error when parsing record from object '{}' at offset '{}'. Reason : {}", blobGeneratedId, fileOffset, e); getContext().toError(e.getUnparsedRecord(), e.getErrorCode(), e.getParams()); } } } catch (IOException | DataParserException e) { LOG.error("Error when parsing records from Object '{}'. Reason : {}, moving to next file", blobGeneratedId, e); getContext().reportError(Errors.GCS_00, blobGeneratedId, fileOffset, e); fileOffset = END_FILE_OFFSET; noMoreDataErrorCount++; try { errorBlobHandler.handleError(blob.getBlobId()); } catch (StorageException se) { LOG.error("Error handling failed for {}. Reason{}", blobGeneratedId, e); getContext().reportError(Errors.GCS_06, blobGeneratedId, se); } } return String.format(OFFSET_FORMAT, minTimestamp, fileOffset, blobGeneratedId); }
From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java
private String md5Hash(String string) { byte[] bytesOfMessage = new byte[0]; try {//w w w .j a v a 2 s . c om bytesOfMessage = string.getBytes("UTF-8"); } catch (UnsupportedEncodingException willNeverHappen) { } MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException willNeverHappen) { } byte[] digest = md.digest(bytesOfMessage); return Hex.encodeHexString(digest); }
From source file:kr.debop4j.core.tools.StringTool.java
/** * ?? 16 .//from ww w . j a va2s . co m * * @param bytes ? * @return ? 16 ? */ public static String getHexString(final byte[] bytes) { return Hex.encodeHexString(bytes); }
From source file:com.google.u2f.server.impl.U2FServerReferenceImpl.java
@Override public U2fSignRequest getSignRequest(String accountName, String appId) throws U2FException { Log.info(">> getSignRequest " + accountName); List<SecurityKeyData> securityKeyDataList = dataStore.getSecurityKeyData(accountName); byte[] challenge = challengeGenerator.generateChallenge(accountName); String challengeBase64 = Base64.encodeBase64URLSafeString(challenge); ImmutableList.Builder<RegisteredKey> registeredKeys = ImmutableList.builder(); Log.info(" challenge: " + Hex.encodeHexString(challenge)); for (SecurityKeyData securityKeyData : securityKeyDataList) { SignSessionData sessionData = new SignSessionData(accountName, appId, challenge, securityKeyData.getPublicKey()); String sessionId = dataStore.storeSessionData(sessionData); byte[] keyHandle = securityKeyData.getKeyHandle(); List<Transports> transports = securityKeyData.getTransports(); Log.info("-- Output --"); Log.info(" sessionId: " + sessionId); Log.info(" keyHandle: " + Hex.encodeHexString(keyHandle)); String keyHandleBase64 = Base64.encodeBase64URLSafeString(keyHandle); Log.info("<< getRegisteredKey " + accountName); registeredKeys.add(new RegisteredKey(U2FConsts.U2F_V2, keyHandleBase64, transports, appId, sessionId)); }/*from w ww. ja v a 2 s .c o m*/ return new U2fSignRequest(challengeBase64, registeredKeys.build()); }
From source file:com.arm.connector.bridge.core.Utils.java
public static String createHash(String data) { try {//from w w w . j ava 2 s .c om if (data == null) { return "none"; } MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(data.getBytes()); String hex = Hex.encodeHexString(digest); return Base64.encodeBase64URLSafeString(hex.getBytes()); } catch (NoSuchAlgorithmException ex) { return "none"; } }