Java Code Examples for java.util.AbstractMap.SimpleEntry#getValue()
The following examples show how to use
java.util.AbstractMap.SimpleEntry#getValue() .
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: CachingJwtAuthenticator.java From dropwizard-auth-jwt with Apache License 2.0 | 6 votes |
@Override public Optional<P> authenticate(JwtContext context) throws AuthenticationException { final Timer.Context timer = gets.time(); try { final SimpleEntry<JwtContext, Optional<P>> cacheEntry = cache.getIfPresent(context.getJwt()); if (cacheEntry != null) { return cacheEntry.getValue(); } cacheMisses.mark(); final Optional<P> principal = authenticator.authenticate(context); if (principal.isPresent()) { cache.put(context.getJwt(), new SimpleEntry<>(context, principal)); } return principal; } finally { timer.stop(); } }
Example 2
Source File: ChainBuildingMessageHandler.java From protect with MIT License | 6 votes |
/** * Handles message received over point-to-point links */ @Override public void handleMessage(final Message message) { // TODO: Implement stuff here // System.out.println("OPT BFT --- Received unique authenticated message: " /*+ // message*/); // Count votes for messages in a given position if (message instanceof Message) { final Message publicMessage = (Message) message; final Payload payload = publicMessage.getPayload(); if (payload.getOpcode() == Payload.OpCode.BFT_CERTIFICATION) { final SimpleEntry<Long, SignedMessage> data = (SimpleEntry<Long, SignedMessage>) payload.getData(); final long messagePosition = data.getKey(); final SignedMessage bftMessage = data.getValue(); recordVote(messagePosition, bftMessage, message.getSenderIndex()); } } }
Example 3
Source File: PartialHandler.java From protect with MIT License | 6 votes |
@SuppressWarnings("unchecked") private static String computeEncryptedPartials(final ApvssShareholder shareholder, final String secretName, final Integer requesterId) throws NotFoundException { // This server final int serverIndex = shareholder.getIndex(); // Epoch information final long epoch = shareholder.getEpoch(); // Return encrypted partials final SimpleEntry<BigInteger, BigInteger> encryptedPartials = shareholder.computeEncryptedPartial(requesterId); final BigInteger encryptedShare1Part = encryptedPartials.getKey(); final BigInteger encryptedShare2Part = encryptedPartials.getValue(); // Return the result in json final JSONObject obj = new JSONObject(); obj.put("responder", new Integer(serverIndex)); obj.put("requester", new Integer(requesterId)); obj.put("epoch", new Long(epoch)); obj.put("share1_part", encryptedShare1Part.toString()); obj.put("share2_part", encryptedShare2Part.toString()); return obj.toJSONString() + "\n"; }
Example 4
Source File: NettyTransportClient.java From Sentinel with Apache License 2.0 | 5 votes |
@Override public ClusterResponse sendRequest(ClusterRequest request) throws Exception { if (!isReady()) { throw new SentinelClusterException(ClusterErrorMessages.CLIENT_NOT_READY); } if (!validRequest(request)) { throw new SentinelClusterException(ClusterErrorMessages.BAD_REQUEST); } int xid = getCurrentId(); try { request.setId(xid); channel.writeAndFlush(request); ChannelPromise promise = channel.newPromise(); TokenClientPromiseHolder.putPromise(xid, promise); if (!promise.await(ClusterClientConfigManager.getRequestTimeout())) { throw new SentinelClusterException(ClusterErrorMessages.REQUEST_TIME_OUT); } SimpleEntry<ChannelPromise, ClusterResponse> entry = TokenClientPromiseHolder.getEntry(xid); if (entry == null || entry.getValue() == null) { // Should not go through here. throw new SentinelClusterException(ClusterErrorMessages.UNEXPECTED_STATUS); } return entry.getValue(); } finally { TokenClientPromiseHolder.remove(xid); } }
Example 5
Source File: ClassTransformer.java From AdvancedRocketry with MIT License | 5 votes |
private String getName(String key) { SimpleEntry<String, String> entry = entryMap.get(key); if(entry == null) return ""; else if(obf) return entry.getValue(); else return entry.getKey(); }
Example 6
Source File: VariableReplacementAnalysis.java From RefactoringMiner with MIT License | 5 votes |
private void findParametersWrappedInLocalVariables() { for(StatementObject statement : nonMappedLeavesT2) { for(VariableDeclaration declaration : statement.getVariableDeclarations()) { AbstractExpression initializer = declaration.getInitializer(); if(initializer != null) { for(String key : initializer.getCreationMap().keySet()) { List<ObjectCreation> creations = initializer.getCreationMap().get(key); for(ObjectCreation creation : creations) { for(String argument : creation.arguments) { SimpleEntry<VariableDeclaration, UMLOperation> v2 = getVariableDeclaration2(new Replacement("", argument, ReplacementType.VARIABLE_NAME)); SimpleEntry<VariableDeclaration, UMLOperation> v1 = getVariableDeclaration1(new Replacement(declaration.getVariableName(), "", ReplacementType.VARIABLE_NAME)); if(v2 != null && v1 != null) { Set<AbstractCodeMapping> references = VariableReferenceExtractor.findReferences(v1.getKey(), v2.getKey(), mappings); RenameVariableRefactoring ref = new RenameVariableRefactoring(v1.getKey(), v2.getKey(), v1.getValue(), v2.getValue(), references); if(!existsConflictingExtractVariableRefactoring(ref) && !existsConflictingMergeVariableRefactoring(ref) && !existsConflictingSplitVariableRefactoring(ref)) { variableRenames.add(ref); if(!v1.getKey().getType().equals(v2.getKey().getType()) || !v1.getKey().getType().equalsQualified(v2.getKey().getType())) { ChangeVariableTypeRefactoring refactoring = new ChangeVariableTypeRefactoring(v1.getKey(), v2.getKey(), v1.getValue(), v2.getValue(), references); refactoring.addRelatedRefactoring(ref); refactorings.add(refactoring); } } } } } } } } } }
Example 7
Source File: StringTemplate.java From freecol with GNU General Public License v2.0 | 5 votes |
/** * Add a replacement. * * @param replacement The {@code StringTemplate} replacement to add. */ private void addReplacement(StringTemplate replacement) { if (this.kv == null) this.kv = new ArrayList<>(); for (SimpleEntry<String,StringTemplate> e : this.kv) { if (e.getValue() == null) { e.setValue(replacement); return; } } addPair(null, replacement); }
Example 8
Source File: StringTemplate.java From freecol with GNU General Public License v2.0 | 5 votes |
/** * Try to find the replacement for a given key. * * @param key The key to look for. * @return The value found, otherwise null. */ public StringTemplate getReplacement(String key) { if (this.kv == null) return null; SimpleEntry<String,StringTemplate> val = find(this.kv, matchKeyEquals(key, SimpleEntry::getKey)); return (val == null) ? null : val.getValue(); }
Example 9
Source File: NettyTransportClient.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 5 votes |
@Override public ClusterResponse sendRequest(ClusterRequest request) throws Exception { if (!isReady()) { throw new SentinelClusterException(ClusterErrorMessages.CLIENT_NOT_READY); } if (!validRequest(request)) { throw new SentinelClusterException(ClusterErrorMessages.BAD_REQUEST); } int xid = getCurrentId(); try { request.setId(xid); channel.writeAndFlush(request); ChannelPromise promise = channel.newPromise(); TokenClientPromiseHolder.putPromise(xid, promise); if (!promise.await(ClusterClientConfigManager.getRequestTimeout())) { throw new SentinelClusterException(ClusterErrorMessages.REQUEST_TIME_OUT); } SimpleEntry<ChannelPromise, ClusterResponse> entry = TokenClientPromiseHolder.getEntry(xid); if (entry == null || entry.getValue() == null) { // Should not go through here. throw new SentinelClusterException(ClusterErrorMessages.UNEXPECTED_STATUS); } return entry.getValue(); } finally { TokenClientPromiseHolder.remove(xid); } }
Example 10
Source File: EciesEncryptionClient.java From protect with MIT License | 5 votes |
public void encryptFile() throws BadPaddingException, IllegalBlockSizeException, ClassNotFoundException, IOException, ResourceUnavailableException, BelowThresholdException { // Print status System.out.println("-----------------------------------------------------------"); System.out.println("Beginning encryption of file: " + this.inputFile); // Get public key and current epoch from the server System.out.print("Accessing public key for secret: " + this.secretName + "... "); final SimpleEntry<List<EcPoint>, Long> shareVerificationKeysAndEpoch = this.getServerVerificationKeys(secretName); System.out.println(" (done)"); final EcPoint publicKey = shareVerificationKeysAndEpoch.getKey().get(0); final long currentEpoch = shareVerificationKeysAndEpoch.getValue(); System.out.println("Public key for secret: " + publicKey); System.out.println("Current epoch for secret: " + currentEpoch); System.out.println(); // Reading System.out.print("Reading input file: " + this.inputFile + "... "); final byte[] plaintextData = Files.readAllBytes(inputFile.toPath()); System.out.println(" (done)"); System.out.println("Read " + plaintextData.length + " bytes."); System.out.println(); // Perform ECIES encryption System.out.print("Performing ECIES encryption of file content... "); final byte[] ciphertext = EciesEncryption.encrypt(plaintextData, publicKey); System.out.println(" (done)"); System.out.println("Encrypted length " + ciphertext.length + " bytes."); System.out.println(); // Write ciphertext to output file System.out.print("Writing ciphertext to file: " + this.outputFile + "... "); Files.write(this.outputFile.toPath(), ciphertext); System.out.println(" (done)"); System.out.println("Wrote " + ciphertext.length + " bytes."); System.out.println(); System.out.println("Done."); }
Example 11
Source File: ApvssTest.java From protect with MIT License | 5 votes |
private static void printErrors(final List<ApvssShareholder> shareholders) { for (ApvssShareholder shareholder : shareholders) { System.out.println("Errors reported by shareholder with index = " + shareholder.getIndex() + ":"); for (SimpleEntry<Integer, ErrorCondition> alert : shareholder.alertLog.getAlerts()) { int reportedShareholder = alert.getKey(); ErrorCondition error = alert.getValue(); System.out.println(" Shareholder[" + reportedShareholder + "] committed a " + error + " error"); } } }
Example 12
Source File: EciesEncryptionClient.java From protect with MIT License | 5 votes |
public void encryptFile() throws BadPaddingException, IllegalBlockSizeException, ClassNotFoundException, IOException, ResourceUnavailableException, BelowThresholdException { // Print status System.out.println("-----------------------------------------------------------"); System.out.println("Beginning encryption of file: " + this.inputFile); // Get public key and current epoch from the server System.out.print("Accessing public key for secret: " + this.secretName + "... "); final SimpleEntry<EcPoint, Long> publicKeyAndEpoch = this.getServerPublicKey(secretName); System.out.println(" (done)"); final EcPoint publicKey = publicKeyAndEpoch.getKey(); final long currentEpoch = publicKeyAndEpoch.getValue(); System.out.println("Public key for secret: " + publicKey); System.out.println("Current epoch for secret: " + currentEpoch); System.out.println(); // Reading System.out.print("Reading input file: " + this.inputFile + "... "); final byte[] plaintextData = Files.readAllBytes(inputFile.toPath()); System.out.println(" (done)"); System.out.println("Read " + plaintextData.length + " bytes."); System.out.println(); // Perform ECIES encryption System.out.print("Performing ECIES encryption of file content... "); final byte[] ciphertext = EciesEncryption.encrypt(plaintextData, publicKey); System.out.println(" (done)"); System.out.println("Encrypted length " + ciphertext.length + " bytes."); System.out.println(); // Write ciphertext to output file System.out.print("Writing ciphertext to file: " + this.outputFile + "... "); Files.write(this.outputFile.toPath(), ciphertext); System.out.println(" (done)"); System.out.println("Wrote " + ciphertext.length + " bytes."); System.out.println(); System.out.println("Done."); }
Example 13
Source File: EciesEncryptionClient.java From protect with MIT License | 4 votes |
public void decryptFile() throws BadPaddingException, IllegalBlockSizeException, ClassNotFoundException, IOException, ResourceUnavailableException, BelowThresholdException { // Print status System.out.println("-----------------------------------------------------------"); System.out.println("Beginning decryption of file: " + this.inputFile); // Reading ciphertext System.out.print("Reading input file: " + this.inputFile + "... "); final byte[] ciphertextData = Files.readAllBytes(inputFile.toPath()); System.out.println(" (done)"); System.out.println("Read " + ciphertextData.length + " bytes of ciphertext."); System.out.println(); // Extract public value from ciphertext System.out.print("Extracting public value from ciphertext: " + this.inputFile + "... "); final EcPoint publicValue = EciesEncryption.getPublicValue(ciphertextData); System.out.println(" (done)"); System.out.println("Public Value is: " + publicValue); System.out.println(); // Get public key and current epoch from the server System.out.print("Accessing public key for secret: " + this.secretName + "... "); final SimpleEntry<List<EcPoint>, Long> shareVerificationKeysAndEpoch = this.getServerVerificationKeys(secretName); System.out.println(" (done)"); final EcPoint publicKey = shareVerificationKeysAndEpoch.getKey().get(0); final long currentEpoch = shareVerificationKeysAndEpoch.getValue(); System.out.println("Public key for secret: " + publicKey); System.out.println("Current epoch for secret: " + currentEpoch); System.out.println(); // Get public key and current epoch from the server System.out.print("Performing threshold exponentiation on public value using: " + this.secretName + "... "); final EcPoint exponentiationResult = this.exponentiatePoint(publicValue, currentEpoch); System.out.println(" (done)"); System.out.println("Shared secret obtained: " + exponentiationResult); System.out.println(); // Perform ECIES decryption System.out.print("Performing ECIES decryption of file content... "); final byte[] plaintext = EciesEncryption.decrypt(ciphertextData, exponentiationResult); System.out.println(" (done)"); System.out.println("Plaintext length " + plaintext.length + " bytes."); System.out.println(); // Write plaintext to output file System.out.print("Writing plaintext to file: " + this.outputFile + "... "); Files.write(this.outputFile.toPath(), plaintext); System.out.println(" (done)"); System.out.println("Wrote " + plaintext.length + " bytes."); System.out.println(); System.out.println("Done."); }
Example 14
Source File: CertificateAuthorityCli.java From protect with MIT License | 4 votes |
private static final void issueClientCertificates(final File caPath, final File keyPath, final File certPath) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException, InvalidKeySpecException { // Load configuration to get server addresses final File baseDirectory = new File(caPath.getParent()); final File serverDirectory = new File(baseDirectory, "server"); final File configFile = new File(serverDirectory, ServerApplication.AUTH_DIRECTORY); // Load Client Access Controls final AccessEnforcement accessEnforcement = ClientPermissionLoader.loadIniFile(configFile); // Load or generate client CA Certificate final SimpleEntry<X509Certificate, PrivateKey> clientCaEntry = loadOrGenerateCa(caPath, "clients"); final String issuerDnClient = clientCaEntry.getKey().getIssuerDN().getName(); final PrivateKey caKeyClient = clientCaEntry.getValue(); System.out.println(); // For each ECDSA public key in the keyPath, create a certificate for (final String username : accessEnforcement.getKnownUsers()) { final File publicKeyFile = new File(keyPath, "public-" + username); if (!publicKeyFile.exists()) { System.out.println(publicKeyFile.getAbsoluteFile() + " not found, skipping..."); continue; } else { try (final PemReader reader = new PemReader(new FileReader(publicKeyFile.getAbsolutePath()))) { // Load client public key from file final PublicKey publicKey = ((PublicKey) Pem.readObject(reader.readPemObject())); System.out.println("Read: " + publicKeyFile.getAbsolutePath()); // Generate certificate final String subjectDn = "O=Threshold, OU=Security, CN=client-" + username; final X509Certificate certificate = CertificateGeneration.generateCertificate(subjectDn, null, null, publicKey, 730, false, issuerDnClient, caKeyClient); System.out.println(" Issued certificate for: " + subjectDn); // Load entity private key from file final File privateKeyFile = new File(keyPath, "private-" + username); try (final PemReader keyReader = new PemReader(new FileReader(privateKeyFile.getAbsolutePath()))) { final PrivateKey privateKey = ((PrivateKey) Pem.readObject(keyReader.readPemObject())); // Write PKCS12 file for import to browsers final File pfxFile = new File(keyPath, "bundle-private-" + username + ".p12"); CertificateGeneration.createP12File(pfxFile, "password".toCharArray(), certificate, privateKey); System.out.println("Wrote: " + pfxFile.getAbsolutePath()); } // Write certificate file final File certificateFile = new File(certPath, "cert-" + username); Pem.storeCertificateToFile(certificate, certificateFile); System.out.println("Wrote: " + certificateFile.getAbsolutePath()); System.out.println(); } } } }
Example 15
Source File: AnnotatedTextToString.java From xtext-eclipse with Eclipse Public License 2.0 | 4 votes |
@Override public String toString() { String contents = getContents(); regions.sort(Comparator.comparing((region) -> region.start)); List<SimpleEntry<Integer, CommentedRegion>> sorted = new ArrayList<>(); for (int index = 0; index < regions.size(); index++) { sorted.add(new SimpleEntry<>(index, regions.get(index))); } List<SimpleEntry<Integer, String>> locations = new ArrayList<>(); sorted.stream().forEach(s -> { locations.add(new SimpleEntry<>(s.getValue().start, "<" + s.getKey() + "<")); locations.add(new SimpleEntry<>(s.getValue().end, ">" + s.getKey() + ">")); }); locations.sort(Comparator.comparing(SimpleEntry::getKey)); StringBuilder result = new StringBuilder(); int lastOffset = 0; for (int i = 0; i < locations.size(); i++) { SimpleEntry<Integer, String> location = locations.get(i); Integer offset = location.getKey(); String comment = location.getValue(); result.append(contents.substring(lastOffset, offset)); result.append(comment); lastOffset = offset; } result.append(contents.substring(lastOffset, contents.length())); String[] resultsArray = result.toString().replace("\t", " ").split("\r?\n"); int maxLineLength = Arrays.stream(resultsArray).map(r -> r.length()).reduce(Integer::max).get(); if (!result.substring(result.length() - 1, result.length()).equals("\n")) { result.append("\n"); } result.append(Strings.repeat("-", maxLineLength)); if (sorted.isEmpty()) { for (String message : emptyMessages) { result.append("\n"); result.append(message); } } else { for (SimpleEntry<Integer, CommentedRegion> c : sorted) { result.append("\n"); result.append(c.getKey()); result.append(": "); result.append(c.getValue().text); } } return result.toString(); }
Example 16
Source File: EngineMBPythonNetworksBase.java From gateplugin-LearningFramework with GNU Lesser General Public License v2.1 | 4 votes |
@Override protected void loadModel(URL directoryURL, String parms) { File directory = null; if("file".equals(directoryURL.getProtocol())) { directory = Files.fileFromURL(directoryURL); } else { throw new GateRuntimeException("The dataDirectory for WekaWrapper must be a file: URL not "+directoryURL); } ArrayList<String> finalCommand = new ArrayList<>(); // we need the corpus representation here! Normally this is done from loadEngine and after // load model, but we do it here. The load crm method only loads anything if it is still // null, so we will do this only once anyway. loadAndSetCorpusRepresentation(directoryURL); CorpusRepresentationMalletTarget data = (CorpusRepresentationMalletTarget)corpusRepresentation; SimpleEntry<String,Integer> modeAndNrC = findOutMode(data); String mode = modeAndNrC.getKey(); Integer nrClasses = modeAndNrC.getValue(); // Instead of loading a model, this establishes a connection with the // external wrapper process. File commandFile = findWrapperCommand(directory, true); String modelFileName = new File(directory,MODEL_BASENAME).getAbsolutePath(); finalCommand.add(commandFile.getAbsolutePath()); finalCommand.add(modelFileName); finalCommand.add(mode); finalCommand.add(nrClasses.toString()); // if we have a shell command prepend that, and if we have shell parms too, include them if(shellcmd != null) { finalCommand.add(0,shellcmd); if(shellparms != null) { String[] sps = shellparms.trim().split("\\s+"); int i=0; for(String sp : sps) { finalCommand.add(++i,sp); } } } //System.err.println("Running: "+finalCommand); // Create a fake Model jsut to make LF_Apply... happy which checks if this is null model = MODEL_INSTANCE; Map<String,String> env = new HashMap<>(); env.put(ENV_WRAPPER_HOME, wrapperhome); process = Process4JsonStream.create(directory,env,finalCommand); }
Example 17
Source File: EngineMBPythonNetworksBase.java From gateplugin-LearningFramework with GNU Lesser General Public License v2.1 | 4 votes |
@Override public void trainModel(File dataDirectory, String instanceType, String parms) { ArrayList<String> finalCommand = new ArrayList<>(); CorpusRepresentationMalletTarget data = (CorpusRepresentationMalletTarget)corpusRepresentation; SimpleEntry<String,Integer> modeAndNrC = findOutMode(data); String mode = modeAndNrC.getKey(); Integer nrClasses = modeAndNrC.getValue(); // invoke wrapper for training File commandFile = findWrapperCommand(dataDirectory, false); // Export the data // Note: any scaling was already done in the PR before calling this method! // find out if we train classification or regression // TODO: NOTE: not sure if classification/regression matters here as long as // the actual exporter class does the right thing based on the corpus representation! // TODO: we have to choose the correct target type here!!! // NOTE: the last argument here are the parameters for the exporter method. // we use the CSV exporter with parameters: // -t: twofiles, export indep and dep into separate files // -n: noheaders, do not add a header row // Exporter.export(corpusRepresentation, // Exporter.CSV_CL_MR, dataDirectory, instanceType, "-t -n"); corpusExporter.export(); String dataFileName = dataDirectory.getAbsolutePath()+File.separator; String modelFileName = new File(dataDirectory, MODEL_BASENAME).getAbsolutePath(); finalCommand.add(commandFile.getAbsolutePath()); finalCommand.add(dataFileName); finalCommand.add(modelFileName); finalCommand.add(mode); finalCommand.add(nrClasses.toString()); if(!parms.trim().isEmpty()) { String[] tmp = parms.split("\\s+",-1); finalCommand.addAll(Arrays.asList(tmp)); } // if we have a shell command prepend that, and if we have shell parms too, include them if(shellcmd != null) { finalCommand.add(0,shellcmd); if(shellparms != null) { String[] sps = shellparms.trim().split("\\s+"); int i=0; for(String sp : sps) { finalCommand.add(++i,sp); } } } //System.err.println("Running: "); //for(int i=0; i<finalCommand.size();i++) { // System.err.println(i+": >"+finalCommand.get(i)+"<"); //} // Create a fake Model jsut to make LF_Apply... happy which checks if this is null model = MODEL_INSTANCE; Map<String,String> env = new HashMap<>(); env.put(ENV_WRAPPER_HOME,wrapperhome); process = ProcessSimple.create(dataDirectory,env,finalCommand); process.waitFor(); updateInfo(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); info.modelWhenTrained = sdf.format(new Date()); info.algorithmParameters = parms; info.save(dataDirectory); featureInfo.save(dataDirectory); }
Example 18
Source File: Series.java From SPADE with GNU General Public License v3.0 | 4 votes |
public V getBestMatch(T t){ if(t == null){ logger.log(Level.WARNING, "Key to look up cannot be null."); }else{ if(!sorted){ sorted = true; Collections.sort(series, new Comparator<SimpleEntry<T,V>>(){ @Override public int compare(SimpleEntry<T, V> o1, SimpleEntry<T, V> o2){ if(o1 == null && o2 == null){ return 0; }else if(o1 == null && o2 != null){ return -1; }else if(o1 != null && o2 == null){ return 1; }else{ T t1 = o1.getKey(); T t2 = o2.getKey(); if(t1 == null && t2 == null){ return 0; }else if(t1 == null && t2 != null){ return -1; }else if(t1 != null && t2 == null){ return 1; }else{ return t1.compareTo(t2); } } } }); } // Looking up in reverse because we want the last associated value for that key. for(int a = series.size() - 1; a > -1; a--){ SimpleEntry<T, V> entry = series.get(a); T time = entry.getKey(); if(t.compareTo(time) >= 0){ return entry.getValue(); } } } return null; // none matched }
Example 19
Source File: CertificateAuthorityCli.java From protect with MIT License | 4 votes |
private static final void issueServerCertificates(final File caPath, final File keyPath, final File certPath) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException { // Load configuration to get server addresses final File baseDirectory = new File(caPath.getParent()); final File serverDirectory = new File(baseDirectory, "server"); final File configFile = new File(serverDirectory, ServerApplication.CONFIG_FILENAME); final ServerConfiguration configuration = ServerConfigurationLoader.load(configFile); // For each ECDSA public key in the keyPath, create a certificate for (int keyIndex = 1; keyIndex <= configuration.getNumServers(); keyIndex++) { final File publicKeyFile = new File(keyPath, "public-" + keyIndex); if (!publicKeyFile.exists()) { System.out.println(publicKeyFile.getAbsoluteFile() + " not found, skipping..."); continue; } else { // Load CA certificate (or generate a new one) final SimpleEntry<X509Certificate, PrivateKey> entry = loadOrGenerateCa(caPath, "server-" + keyIndex); System.out.println(); final String issuerDn = entry.getKey().getIssuerDN().getName(); final PrivateKey caKey = entry.getValue(); try (final PemReader reader = new PemReader(new FileReader(publicKeyFile.getAbsolutePath()))) { // Load public key from file final PublicKey publicKey = ((PublicKey) Pem.readObject(reader.readPemObject())); System.out.println("Read: " + publicKeyFile.getAbsolutePath()); // Generate certificate final String subjectDn = "O=Threshold, OU=Security, CN=server-" + keyIndex; System.out.println(" Issued certificate for: " + subjectDn); final InetSocketAddress serverAddress = configuration.getServerAddresses().get(keyIndex - 1); final String serverIp = serverAddress.getAddress().toString().split("/")[1]; final String serverHost = serverAddress.getAddress().getCanonicalHostName(); final X509Certificate certificate = CertificateGeneration.generateCertificate(subjectDn, serverIp, serverHost, publicKey, 730, false, issuerDn, caKey); System.out.println(" Alternative names: IP:" + serverIp + ", DNS:" + serverHost); // Write certificate file final File certificateFile = new File(certPath, "cert-" + keyIndex); Pem.storeCertificateToFile(certificate, certificateFile); System.out.println("Wrote: " + certificateFile.getAbsolutePath()); System.out.println(); } } } }
Example 20
Source File: EciesEncryptionClient.java From protect with MIT License | 4 votes |
public void decryptFile() throws BadPaddingException, IllegalBlockSizeException, ClassNotFoundException, IOException, ResourceUnavailableException, BelowThresholdException { // Print status System.out.println("-----------------------------------------------------------"); System.out.println("Beginning decryption of file: " + this.inputFile); // Reading ciphertext System.out.print("Reading input file: " + this.inputFile + "... "); final byte[] ciphertextData = Files.readAllBytes(inputFile.toPath()); System.out.println(" (done)"); System.out.println("Read " + ciphertextData.length + " bytes of ciphertext."); System.out.println(); // Extract public value from ciphertext System.out.print("Extracting public value from ciphertext: " + this.inputFile + "... "); final EcPoint publicValue = EciesEncryption.getPublicValue(ciphertextData); System.out.println(" (done)"); System.out.println("Public Value is: " + publicValue); System.out.println(); // Get public key and current epoch from the server System.out.print("Accessing public key for secret: " + this.secretName + "... "); final SimpleEntry<EcPoint, Long> publicKeyAndEpoch = this.getServerPublicKey(secretName); System.out.println(" (done)"); final EcPoint publicKey = publicKeyAndEpoch.getKey(); final long currentEpoch = publicKeyAndEpoch.getValue(); System.out.println("Public key for secret: " + publicKey); System.out.println("Current epoch for secret: " + currentEpoch); System.out.println(); // Get public key and current epoch from the server System.out.print("Performing threshold exponentiation on public value using: " + this.secretName + "... "); final EcPoint exponentiationResult = this.exponentiatePoint(publicValue, currentEpoch); System.out.println(" (done)"); System.out.println("Shared secret obtained: " + exponentiationResult); System.out.println(); // Perform ECIES decryption System.out.print("Performing ECIES decryption of file content... "); final byte[] plaintext = EciesEncryption.decrypt(ciphertextData, exponentiationResult); System.out.println(" (done)"); System.out.println("Plaintext length " + plaintext.length + " bytes."); System.out.println(); // Write plaintext to output file System.out.print("Writing plaintext to file: " + this.outputFile + "... "); Files.write(this.outputFile.toPath(), plaintext); System.out.println(" (done)"); System.out.println("Wrote " + plaintext.length + " bytes."); System.out.println(); System.out.println("Done."); }