List of usage examples for org.apache.commons.codec.digest DigestUtils sha256
public static byte[] sha256(String data)
From source file:org.torproject.collector.bridgedescs.SanitizedBridgesWriter.java
/** * Sanitizes an extra-info descriptor and writes it to disk. *///from w w w . ja va 2s. c o m public void sanitizeAndStoreExtraInfoDescriptor(byte[] data) { /* Parse descriptor to generate a sanitized version. */ String scrubbedDesc = null; String published = null; String masterKeyEd25519FromIdentityEd25519 = null; try { BufferedReader br = new BufferedReader(new StringReader(new String(data, "US-ASCII"))); String line = null; StringBuilder scrubbed = null; String hashedBridgeIdentity = null; String masterKeyEd25519 = null; while ((line = br.readLine()) != null) { /* Parse bridge identity from extra-info line and replace it with * its hash in the sanitized descriptor. */ String[] parts = line.split(" "); if (line.startsWith("extra-info ")) { if (parts.length < 3) { logger.debug( "Illegal line in extra-info descriptor: '" + line + "'. Skipping descriptor."); return; } hashedBridgeIdentity = DigestUtils.shaHex(Hex.decodeHex(parts[2].toCharArray())).toLowerCase(); scrubbed = new StringBuilder( "extra-info " + parts[1] + " " + hashedBridgeIdentity.toUpperCase() + "\n"); /* Parse the publication time to determine the file name. */ } else if (line.startsWith("published ")) { scrubbed.append(line + "\n"); published = line.substring("published ".length()); if (published.compareTo(maxExtraInfoDescriptorPublishedTime) > 0) { maxExtraInfoDescriptorPublishedTime = published; } /* Remove everything from transport lines except the transport * name. */ } else if (line.startsWith("transport ")) { if (parts.length < 3) { logger.debug( "Illegal line in extra-info descriptor: '" + line + "'. Skipping descriptor."); return; } scrubbed.append("transport " + parts[1] + "\n"); /* Skip transport-info lines entirely. */ } else if (line.startsWith("transport-info ")) { /* Extract master-key-ed25519 from identity-ed25519. */ } else if (line.equals("identity-ed25519")) { StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null && !line.equals("-----END ED25519 CERT-----")) { if (line.equals("-----BEGIN ED25519 CERT-----")) { continue; } sb.append(line); } masterKeyEd25519FromIdentityEd25519 = this .parseMasterKeyEd25519FromIdentityEd25519(sb.toString()); String sha256MasterKeyEd25519 = Base64 .encodeBase64String(DigestUtils .sha256(Base64.decodeBase64(masterKeyEd25519FromIdentityEd25519 + "="))) .replaceAll("=", ""); scrubbed.append("master-key-ed25519 " + sha256MasterKeyEd25519 + "\n"); if (masterKeyEd25519 != null && !masterKeyEd25519.equals(masterKeyEd25519FromIdentityEd25519)) { logger.warn("Mismatch between identity-ed25519 and " + "master-key-ed25519. Skipping."); return; } /* Verify that identity-ed25519 and master-key-ed25519 match. */ } else if (line.startsWith("master-key-ed25519 ")) { masterKeyEd25519 = line.substring(line.indexOf(" ") + 1); if (masterKeyEd25519FromIdentityEd25519 != null && !masterKeyEd25519FromIdentityEd25519.equals(masterKeyEd25519)) { logger.warn("Mismatch between identity-ed25519 and " + "master-key-ed25519. Skipping."); return; } /* Write the following lines unmodified to the sanitized * descriptor. */ } else if (line.startsWith("write-history ") || line.startsWith("read-history ") || line.startsWith("geoip-start-time ") || line.startsWith("geoip-client-origins ") || line.startsWith("geoip-db-digest ") || line.startsWith("geoip6-db-digest ") || line.startsWith("conn-bi-direct ") || line.startsWith("bridge-") || line.startsWith("dirreq-") || line.startsWith("cell-") || line.startsWith("entry-") || line.startsWith("exit-") || line.startsWith("hidserv-")) { scrubbed.append(line + "\n"); /* When we reach the signature, we're done. Write the sanitized * descriptor to disk below. */ } else if (line.startsWith("router-signature")) { scrubbedDesc = scrubbed.toString(); break; /* Skip the ed25519 signature; we'll include a SHA256 digest of * the SHA256 descriptor digest in router-digest-sha256. */ } else if (line.startsWith("router-sig-ed25519 ")) { continue; /* If we encounter an unrecognized line, stop parsing and print * out a warning. We might have overlooked sensitive information * that we need to remove or replace for the sanitized descriptor * version. */ } else { logger.warn("Unrecognized line '" + line + "'. Skipping."); return; } } br.close(); } catch (IOException e) { logger.warn("Could not parse extra-info " + "descriptor.", e); return; } catch (DecoderException e) { logger.warn("Could not parse extra-info " + "descriptor.", e); return; } /* Determine filename of sanitized extra-info descriptor. */ String descriptorDigest = null; try { String ascii = new String(data, "US-ASCII"); String startToken = "extra-info "; String sigToken = "\nrouter-signature\n"; int start = ascii.indexOf(startToken); int sig = ascii.indexOf(sigToken) + sigToken.length(); if (start >= 0 && sig >= 0 && sig > start) { byte[] forDigest = new byte[sig - start]; System.arraycopy(data, start, forDigest, 0, sig - start); descriptorDigest = DigestUtils.shaHex(DigestUtils.sha(forDigest)); } } catch (UnsupportedEncodingException e) { /* Handle below. */ } if (descriptorDigest == null) { logger.warn("Could not calculate extra-info " + "descriptor digest."); return; } String descriptorDigestSha256Base64 = null; if (masterKeyEd25519FromIdentityEd25519 != null) { try { String ascii = new String(data, "US-ASCII"); String startToken = "extra-info "; String sigToken = "\n-----END SIGNATURE-----\n"; int start = ascii.indexOf(startToken); int sig = ascii.indexOf(sigToken) + sigToken.length(); if (start >= 0 && sig >= 0 && sig > start) { byte[] forDigest = new byte[sig - start]; System.arraycopy(data, start, forDigest, 0, sig - start); descriptorDigestSha256Base64 = Base64 .encodeBase64String(DigestUtils.sha256(DigestUtils.sha256(forDigest))) .replaceAll("=", ""); } } catch (UnsupportedEncodingException e) { /* Handle below. */ } if (descriptorDigestSha256Base64 == null) { logger.warn("Could not calculate extra-info " + "descriptor SHA256 digest."); return; } } String dyear = published.substring(0, 4); String dmonth = published.substring(5, 7); File tarballFile = new File( this.sanitizedBridgesDirectory.getAbsolutePath() + "/" + dyear + "/" + dmonth + "/extra-infos/" + descriptorDigest.charAt(0) + "/" + descriptorDigest.charAt(1) + "/" + descriptorDigest); try { File rsyncCatFile = new File(config.getPath(Key.RecentPath).toFile(), "bridge-descriptors/extra-infos/" + this.rsyncCatString + "-extra-infos.tmp"); File[] outputFiles = new File[] { tarballFile, rsyncCatFile }; boolean[] append = new boolean[] { false, true }; for (int i = 0; i < outputFiles.length; i++) { File outputFile = outputFiles[i]; boolean appendToFile = append[i]; if (outputFile.exists() && !appendToFile) { /* We already stored this descriptor to disk before, so let's * not store it yet another time. */ break; } outputFile.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile, appendToFile)); bw.write(Annotation.BridgeExtraInfo.toString()); bw.write(scrubbedDesc); if (descriptorDigestSha256Base64 != null) { bw.write("router-digest-sha256 " + descriptorDigestSha256Base64 + "\n"); } bw.write("router-digest " + descriptorDigest.toUpperCase() + "\n"); bw.close(); } } catch (Exception e) { logger.warn("Could not write sanitized " + "extra-info descriptor to disk.", e); } }
From source file:org.torproject.collector.relaydescs.ArchiveReader.java
/** Reads all descriptors from the given directory, possibly using a * parse history file, and passes them to the given descriptor * parser. *//* w w w . j a v a 2 s. co m*/ public ArchiveReader(RelayDescriptorParser rdp, File archivesDirectory, File statsDirectory, boolean keepImportHistory) { if (rdp == null || archivesDirectory == null || statsDirectory == null) { throw new IllegalArgumentException(); } rdp.setArchiveReader(this); int parsedFiles = 0; int ignoredFiles = 0; SortedSet<String> archivesImportHistory = new TreeSet<String>(); File archivesImportHistoryFile = new File(statsDirectory, "archives-import-history"); if (keepImportHistory && archivesImportHistoryFile.exists()) { try { BufferedReader br = new BufferedReader(new FileReader(archivesImportHistoryFile)); String line = null; while ((line = br.readLine()) != null) { archivesImportHistory.add(line); } br.close(); } catch (IOException e) { logger.warn("Could not read in archives import " + "history file. Skipping.", e); } } if (archivesDirectory.exists()) { logger.debug("Importing files in directory " + archivesDirectory + "/..."); Stack<File> filesInInputDir = new Stack<File>(); filesInInputDir.add(archivesDirectory); List<File> problems = new ArrayList<File>(); Set<File> filesToRetry = new HashSet<File>(); while (!filesInInputDir.isEmpty()) { File pop = filesInInputDir.pop(); if (pop.isDirectory()) { for (File f : pop.listFiles()) { filesInInputDir.add(f); } } else { if (rdp != null) { try { BufferedInputStream bis = null; if (keepImportHistory && archivesImportHistory.contains(pop.getName())) { ignoredFiles++; continue; } else if (pop.getName().endsWith(".tar.bz2")) { logger.warn( "Cannot parse compressed tarball " + pop.getAbsolutePath() + ". Skipping."); continue; } else if (pop.getName().endsWith(".bz2")) { FileInputStream fis = new FileInputStream(pop); BZip2CompressorInputStream bcis = new BZip2CompressorInputStream(fis); bis = new BufferedInputStream(bcis); } else { FileInputStream fis = new FileInputStream(pop); bis = new BufferedInputStream(fis); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; byte[] data = new byte[1024]; while ((len = bis.read(data, 0, 1024)) >= 0) { baos.write(data, 0, len); } bis.close(); byte[] allData = baos.toByteArray(); boolean stored = rdp.parse(allData); if (!stored) { filesToRetry.add(pop); continue; } if (keepImportHistory) { archivesImportHistory.add(pop.getName()); } parsedFiles++; } catch (IOException e) { problems.add(pop); if (problems.size() > 3) { break; } } } } } for (File pop : filesToRetry) { /* TODO We need to parse microdescriptors ourselves, rather than * RelayDescriptorParser, because only we know the valid-after * time(s) of microdesc consensus(es) containing this * microdescriptor. However, this breaks functional abstraction * pretty badly. */ if (rdp != null) { try { BufferedInputStream bis = null; if (pop.getName().endsWith(".bz2")) { FileInputStream fis = new FileInputStream(pop); BZip2CompressorInputStream bcis = new BZip2CompressorInputStream(fis); bis = new BufferedInputStream(bcis); } else { FileInputStream fis = new FileInputStream(pop); bis = new BufferedInputStream(fis); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; byte[] data = new byte[1024]; while ((len = bis.read(data, 0, 1024)) >= 0) { baos.write(data, 0, len); } bis.close(); byte[] allData = baos.toByteArray(); BufferedReader br = new BufferedReader(new StringReader(new String(allData, "US-ASCII"))); String line; do { line = br.readLine(); } while (line != null && line.startsWith("@")); br.close(); if (line == null) { logger.debug("We were given an empty descriptor for " + "parsing. Ignoring."); continue; } if (!line.equals("onion-key")) { logger.debug("Skipping non-recognized descriptor."); continue; } SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); parseFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String ascii = null; try { ascii = new String(allData, "US-ASCII"); } catch (UnsupportedEncodingException e) { /* No way that US-ASCII is not supported. */ } int start = -1; int end = -1; String startToken = "onion-key\n"; while (end < ascii.length()) { start = ascii.indexOf(startToken, end); if (start < 0) { break; } end = ascii.indexOf(startToken, start + 1); if (end < 0) { end = ascii.length(); if (end <= start) { break; } } byte[] descBytes = new byte[end - start]; System.arraycopy(allData, start, descBytes, 0, end - start); String digest256Base64 = Base64.encodeBase64String(DigestUtils.sha256(descBytes)) .replaceAll("=", ""); String digest256Hex = DigestUtils.sha256Hex(descBytes); if (!this.microdescriptorValidAfterTimes.containsKey(digest256Hex)) { logger.debug("Could not store microdescriptor '" + digest256Hex + "', which was not contained in a " + "microdesc consensus."); continue; } for (String validAfterTime : this.microdescriptorValidAfterTimes.get(digest256Hex)) { try { long validAfter = parseFormat.parse(validAfterTime).getTime(); rdp.storeMicrodescriptor(descBytes, digest256Hex, digest256Base64, validAfter); } catch (ParseException e) { logger.warn("Could not parse " + "valid-after time '" + validAfterTime + "'. Not " + "storing microdescriptor.", e); } } } if (keepImportHistory) { archivesImportHistory.add(pop.getName()); } parsedFiles++; } catch (IOException e) { problems.add(pop); if (problems.size() > 3) { break; } } } } if (problems.isEmpty()) { logger.debug("Finished importing files in directory " + archivesDirectory + "/."); } else { StringBuilder sb = new StringBuilder( "Failed importing files in " + "directory " + archivesDirectory + "/:"); int printed = 0; for (File f : problems) { sb.append("\n " + f.getAbsolutePath()); if (++printed >= 3) { sb.append("\n ... more"); break; } } } } if (keepImportHistory) { try { archivesImportHistoryFile.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter(archivesImportHistoryFile)); for (String line : archivesImportHistory) { bw.write(line + "\n"); } bw.close(); } catch (IOException e) { logger.warn("Could not write archives import " + "history file."); } } logger.info("Finished importing relay descriptors from local " + "directory:\nParsed " + parsedFiles + ", ignored " + ignoredFiles + " files."); }
From source file:org.torproject.collector.relaydescs.RelayDescriptorDownloader.java
/** * Attempts to download one or more descriptors identified by a resource * string from a directory authority and passes the returned * descriptor(s) to the <code>RelayDescriptorParser</code> upon success. * Returns the number of descriptors contained in the reply. Throws an * <code>IOException</code> if something goes wrong while downloading. *//*from ww w . j a v a 2 s . c om*/ private int downloadResourceFromAuthority(String authority, String resource) throws IOException { byte[] allData = null; this.requestsByAuthority.put(authority, this.requestsByAuthority.get(authority) + 1); /* TODO Disable compressed downloads for extra-info descriptors, * because zlib decompression doesn't work correctly. Figure out why * this is and fix it. */ String fullUrl = "http://" + authority + resource + (this.downloadCompressed && !resource.startsWith("/tor/extra/") ? ".z" : ""); URL url = new URL(fullUrl); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setRequestMethod("GET"); huc.connect(); int response = huc.getResponseCode(); if (response == 200) { BufferedInputStream in = this.downloadCompressed && !resource.startsWith("/tor/extra/") ? new BufferedInputStream(new InflaterInputStream(huc.getInputStream())) : new BufferedInputStream(huc.getInputStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int len; byte[] data = new byte[1024]; while ((len = in.read(data, 0, 1024)) >= 0) { baos.write(data, 0, len); } in.close(); allData = baos.toByteArray(); } logger.debug("Downloaded " + fullUrl + " -> " + response + " (" + (allData == null ? 0 : allData.length) + " bytes)"); int receivedDescriptors = 0; if (allData != null) { if (resource.startsWith("/tor/status-vote/current/")) { this.rdp.parse(allData); receivedDescriptors = 1; } else if (resource.startsWith("/tor/server/") || resource.startsWith("/tor/extra/")) { if (resource.equals("/tor/server/all") || resource.equals("/tor/extra/all")) { this.lastDownloadedAllDescriptors.put(authority, this.currentTimestamp); } String ascii = null; try { ascii = new String(allData, "US-ASCII"); } catch (UnsupportedEncodingException e) { /* No way that US-ASCII is not supported. */ } int start = -1; int sig = -1; int end = -1; String startToken = resource.startsWith("/tor/server/") ? "router " : "extra-info "; String sigToken = "\nrouter-signature\n"; String endToken = "\n-----END SIGNATURE-----\n"; while (end < ascii.length()) { start = ascii.indexOf(startToken, end); if (start < 0) { break; } sig = ascii.indexOf(sigToken, start); if (sig < 0) { break; } sig += sigToken.length(); end = ascii.indexOf(endToken, sig); if (end < 0) { break; } end += endToken.length(); byte[] descBytes = new byte[end - start]; System.arraycopy(allData, start, descBytes, 0, end - start); this.rdp.parse(descBytes); receivedDescriptors++; } } else if (resource.startsWith("/tor/micro/")) { /* TODO We need to parse microdescriptors ourselves, rather than * RelayDescriptorParser, because only we know the valid-after * time(s) of microdesc consensus(es) containing this * microdescriptor. However, this breaks functional abstraction * pretty badly. */ SimpleDateFormat parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); parseFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String ascii = null; try { ascii = new String(allData, "US-ASCII"); } catch (UnsupportedEncodingException e) { /* No way that US-ASCII is not supported. */ } int start = -1; int end = -1; String startToken = "onion-key\n"; while (end < ascii.length()) { start = ascii.indexOf(startToken, end); if (start < 0) { break; } end = ascii.indexOf(startToken, start + 1); if (end < 0) { end = ascii.length(); if (end <= start) { break; } } byte[] descBytes = new byte[end - start]; System.arraycopy(allData, start, descBytes, 0, end - start); String digest256Base64 = Base64.encodeBase64String(DigestUtils.sha256(descBytes)) .replaceAll("=", ""); if (!this.microdescriptorKeys.containsKey(digest256Base64)) { continue; } String digest256Hex = DigestUtils.sha256Hex(descBytes); for (String microdescriptorKey : this.microdescriptorKeys.get(digest256Base64)) { String validAfterTime = microdescriptorKey.split(",")[1]; try { long validAfter = parseFormat.parse(validAfterTime).getTime(); this.rdp.storeMicrodescriptor(descBytes, digest256Hex, digest256Base64, validAfter); } catch (ParseException e) { logger.warn("Could not parse " + "valid-after time '" + validAfterTime + "' in " + "microdescriptor key. Not storing microdescriptor.", e); } } receivedDescriptors++; } } } return receivedDescriptors; }
From source file:pl.raszkowski.sporttrackersconnector.garminconnect.GarminConnectCredentials.java
@Override public String toString() { return new ToStringBuilder(this).append("username", username) .append("password", DigestUtils.sha256(password)).toString(); }
From source file:se.curity.examples.oauth.jwt.JwtTokenIssuer.java
public String issueToken(String subject, List<String> audiences, int lifetimeInMinutes, Map<String, Object> attributes) throws Exception { Map<String, Object> claims = new LinkedHashMap<>(); //Store the initial attributes for (String key : attributes.keySet()) { claims.put(key, attributes.get(key)); }//from w w w.j av a 2s. co m JsonWebSignature token = new JsonWebSignature(); if (AlgorithmIdentifiers.NONE.equals(this.algorithm) && privateKey == null) { token.setAlgorithmConstraints(AlgorithmConstraints.ALLOW_ONLY_NONE); } long issuedAt = Instant.now().getEpochSecond(); long expirationTime = lifetimeInMinutes * 60 + issuedAt + skewTolerance; claims.put(ReservedClaimNames.ISSUER, issuer); claims.put(ReservedClaimNames.SUBJECT, subject); claims.put(ReservedClaimNames.AUDIENCE, arrayOrString(audiences)); claims.put(ReservedClaimNames.ISSUED_AT, issuedAt); claims.put(ReservedClaimNames.NOT_BEFORE, issuedAt - skewTolerance); claims.put(ReservedClaimNames.EXPIRATION_TIME, expirationTime); claims.put(ReservedClaimNames.JWT_ID, UUID.randomUUID().toString()); String payload = _gson.toJson(claims); token.setHeader(ReservedClaimNames.ISSUER, issuer); try { if (this.cert != null) { byte[] x5t = DigestUtils.sha(this.cert.getEncoded()); byte[] x5tS256 = DigestUtils.sha256(this.cert.getEncoded()); //Set DER encoded base64urlsafe string as header params String b64x5t = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(x5t); String b64x5tS256 = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(x5tS256); token.setHeader("x5t", b64x5t); token.setHeader("x5t#S256", b64x5tS256); logger.trace("x5t: " + b64x5t); logger.trace("x5t#256: " + b64x5tS256); } else if (this.keyId != null) { token.setKeyIdHeaderValue(this.keyId); } } catch (CertificateEncodingException ce) { throw new Exception("Unknown certificate encoding", ce); } token.setPayload(payload); if (privateKey != null) { token.setKey(privateKey); //Can be null for "none" algorithm } token.setAlgorithmHeaderValue(algorithm); try { String serializedToken = token.getCompactSerialization(); logger.trace("Serialized Token: " + serializedToken); if (logger.isTraceEnabled()) { //With jose4j version 0.3.4 the getPayload will perform a Verify operation //This requires the Public Key to be set as the Key. if (this.cert != null) { token.setKey(cert.getPublicKey()); String headers = token.getHeader(); String body = token.getPayload(); String maskedToken = serializedToken.length() >= 20 ? serializedToken.substring(0, 10) : ""; String message = String.format("Issuing token: %s******\nHeader = %s\nBody = %s", maskedToken, headers, body); logger.trace(message); } logger.trace(serializedToken); } return serializedToken; } catch (JoseException e) { logger.error("Could not issue token", e); throw new Exception("Could not issue a JWT token. See inner exception for details", e); } }
From source file:se.curity.examples.oauth.jwt.JwtWithCertTest.java
/** * Load the private Keymap with the x5t256 thumbprint and the public key * The map only contains a single key/*from w ww .j a v a2 s . c o m*/ * @return * @throws Exception */ private Map<String, RSAPublicKey> prepareKeyMap() throws Exception { Map<String, RSAPublicKey> keys = new HashMap<>(); Certificate cert = getCertificate(); RSAPublicKey key = (RSAPublicKey) cert.getPublicKey(); byte[] x5tS256 = DigestUtils.sha256(cert.getEncoded()); String b64x5tS256 = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(x5tS256); keys.put(b64x5tS256, key); return keys; }
From source file:se.curity.oauth.JwtTokenIssuer.java
private String issueToken(String subject, List<String> audiences, int lifetimeInMinutes, Map<String, Object> attributes) throws Exception { Map<String, Object> claims = new LinkedHashMap<>(); //Store the initial attributes for (String key : attributes.keySet()) { claims.put(key, attributes.get(key)); }/*from w ww. ja v a 2 s. com*/ JsonWebSignature token = new JsonWebSignature(); if (AlgorithmIdentifiers.NONE.equals(this._algorithm) && _privateKey == null) { token.setAlgorithmConstraints(AlgorithmConstraints.ALLOW_ONLY_NONE); } long issuedAt = Instant.now().getEpochSecond(); long expirationTime = lifetimeInMinutes * 60 + issuedAt + _skewTolerance; claims.put(ReservedClaimNames.ISSUER, _issuer); claims.put(ReservedClaimNames.SUBJECT, subject); claims.put(ReservedClaimNames.AUDIENCE, arrayOrString(audiences)); claims.put(ReservedClaimNames.ISSUED_AT, issuedAt); claims.put(ReservedClaimNames.NOT_BEFORE, issuedAt - _skewTolerance); claims.put(ReservedClaimNames.EXPIRATION_TIME, expirationTime); claims.put(ReservedClaimNames.JWT_ID, UUID.randomUUID().toString()); String payload = _genson.serialize(claims); token.setHeader(ReservedClaimNames.ISSUER, _issuer); try { if (this._cert != null) { byte[] x5t = DigestUtils.sha(this._cert.getEncoded()); byte[] x5tS256 = DigestUtils.sha256(this._cert.getEncoded()); //Set DER encoded base64urlsafe string as header params String b64x5t = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(x5t); String b64x5tS256 = org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(x5tS256); token.setHeader("x5t", b64x5t); token.setHeader("x5t#S256", b64x5tS256); _logger.trace("x5t: " + b64x5t); _logger.trace("x5t#256: " + b64x5tS256); } else if (this._keyId != null) { token.setKeyIdHeaderValue(this._keyId); } } catch (CertificateEncodingException ce) { throw new Exception("Unknown certificate encoding", ce); } token.setPayload(payload); if (_privateKey != null) { token.setKey(_privateKey); //Can be null for "none" algorithm } token.setAlgorithmHeaderValue(_algorithm); try { String serializedToken = token.getCompactSerialization(); _logger.trace("Serialized Token: " + serializedToken); if (_logger.isTraceEnabled()) { //With jose4j version 0.3.4 the getPayload will perform a Verify operation //This requires the Public Key to be set as the Key. if (this._cert != null) { token.setKey(_cert.getPublicKey()); String headers = token.getHeader(); String body = token.getPayload(); String maskedToken = serializedToken.length() >= 20 ? serializedToken.substring(0, 10) : ""; String message = String.format("Issuing token: %s******\nHeader = %s\nBody = %s", maskedToken, headers, body); _logger.trace(message); } _logger.trace(serializedToken); } return serializedToken; } catch (JoseException e) { _logger.error("Could not issue token", e); throw new Exception("Could not issue a JWT token. See inner exception for details", e); } }
From source file:storage.SQLTest.java
/** * This function tests the functionality of findPaths function in spade.storage.PostgreSQL.java */// w w w . j av a 2 s .co m @Test void findPaths() { System.out.println(Hex.encodeHexString(DigestUtils.sha256("abcdefghijklmnopqrstuvwxyz"))); System.out.println(Hex.encodeHexString(DigestUtils.sha256("abcdefghijklmnopqrstuvwxyz")).substring(0, 32)); //Test Case 1: // Creating graph for the expected outcome. // The following sample subgraph contains 3 vertices and 3 edges. Graph expectedOutcomeCase1 = new Graph(); int i = 1; for (AbstractVertex v : graph.vertexSet()) { if (i == 2 || i == 3 || i == 4) expectedOutcomeCase1.putVertex(v); i++; } i = 1; for (AbstractEdge e : graph.edgeSet()) { if (i == 2 || i == 3 || i == 4) expectedOutcomeCase1.putEdge(e); i++; } Graph actualOutcomeCase1 = null; //testSQLObject.findPaths(4, 3, 10); assertTrue(expectedOutcomeCase1.equals(actualOutcomeCase1)); // Test Case 2: // Creating graph for the expected outcome. // The following sample subgraph contains 4 vertices and 4 edges. Graph expectedOutcomeCase2 = new Graph(); i = 1; for (AbstractVertex v : graph.vertexSet()) { if (i != 3) expectedOutcomeCase2.putVertex(v); i++; } i = 1; for (AbstractEdge e : graph.edgeSet()) { if (i != 2 && i != 4) expectedOutcomeCase2.putEdge(e); i++; } Graph actualOutcomeCase2 = null; //testSQLObject.findPaths(4, 5, 10); assertTrue(expectedOutcomeCase2.equals(actualOutcomeCase2)); }