List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64
public static byte[] encodeBase64(final byte[] binaryData)
From source file:cz.muni.fi.mushroomhunter.restclient.LocationCreateSwingWorker.java
@Override protected Void doInBackground() throws Exception { LocationDto locationDto = new LocationDto(); locationDto.setName(restClient.getTfLocationName().getText()); locationDto.setDescription(restClient.getTfLocationDescription().getText()); locationDto.setNearCity(restClient.getTfLocationNearCity().getText()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); List<MediaType> mediaTypeList = new ArrayList<>(); mediaTypeList.add(MediaType.ALL);//from ww w . j ava 2 s .c o m headers.setAccept(mediaTypeList); ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); String json = ow.writeValueAsString(locationDto); RestTemplate restTemplate = new RestTemplate(); String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); headers.add("Authorization", "Basic " + base64Creds); HttpEntity request = new HttpEntity(json, headers); Long[] result = restTemplate.postForObject(RestClient.SERVER_URL + "pa165/rest/location", request, Long[].class); RestClient.getLocationIDs().add(result[0]); return null; }
From source file:com.flyingdonut.implementation.helpers.MongoDbConsumerAssociationStore.java
@Override public void save(String opUrl, Association association) { removeExpired();/* w w w . j a v a 2 s . com*/ BasicDBObject dbObject = new BasicDBObject(); dbObject.put(opurlField, opUrl); dbObject.put(handleField, association.getHandle()); dbObject.put(typeField, association.getType()); dbObject.put(mackeyField, association.getMacKey() == null ? null : new String(Base64.encodeBase64(association.getMacKey().getEncoded()))); dbObject.put(expdateField, association.getExpiry()); String collection = getCollectionName(); WriteResult writeResult = getMongoDBConnection().getCollection(collection).insert(dbObject, WriteConcern.SAFE); }
From source file:com.appdynamics.openstack.nova.CreateServerOptions.java
public void setFile(String file, String filePath) { this.file = Base64.encodeBase64(file.getBytes()); this.filePath = filePath; }
From source file:com.konakart.bl.modules.payment.barclaycardsmartpayhosted.BarclaycardSmartPayHostedHMACTools.java
/** * Verify the signature/*from w w w . j av a2 s . c o m*/ * @param secret * @param sig * @param signedData * @return true if the signature is verified */ public static boolean verifyBase64EncodedSignature(String secret, String sig, String signedData) { if (secret == null || sig == null || signedData == null) return false; SecretKey key = getMacKey(secret); try { Mac mac = Mac.getInstance(key.getAlgorithm()); mac.init(getMacKey(secret)); byte[] digest = mac.doFinal(signedData.getBytes("UTF8")); return sig.equals(new String(Base64.encodeBase64(digest), "ASCII")); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } return false; }
From source file:homenet.PortXmlrpc.java
@Override public void send(Packet packet) { _sending = true;//from w ww . j ava 2s.c o m if ((_node == 0) || (_node == packet.getToNode())) { for (PortListener l : _homeNet._portListeners) { l.portSendingStart(_id); } Hashtable<String, String> xmlpacket = new Hashtable<String, String>(); System.out.println(new String(Base64.encodeBase64(packet.getData()))); String packetBase64 = new String(Base64.encodeBase64(packet.getData())); xmlpacket.put("apikey", _client.apikey); xmlpacket.put("timestamp", getDateAsISO8601String(packet.getTimestamp())); xmlpacket.put("packet", packetBase64); //System.out.println("DAte: "+packet.getTimestamp().toString()); Boolean reply = false; try { reply = (Boolean) _client.execute("homenet.packet.submit", xmlpacket); //reply = (String)homeNetXmlrpcClient.execute("HomeNet.ping", "test test3242342"); } catch (Exception e) { //@todo there are probably some specfic exception we need to filter out to kill bad packets System.out.println("XMLRPC Error: " + e); packet.setStatus(STATUS_READY); System.err.println("Possible network error. Will retry in " + retryDelay + " seconds"); Thread timer = new Thread() { public void run() { try { Thread.sleep(retryDelay * 1000); } catch (Exception e) { } _sending = false; } }; timer.start(); for (PortListener l : _homeNet._portListeners) { l.portSendingEnd(_id); } return; } if (reply == true) { System.out.println("Packet Successfuly sent to HomeNet.me"); } else { System.out.println("Fatal Error"); } } else { System.out.println("Packet Skipped"); } // debugPacket(packet); packet.setStatus(STATUS_SENT); _sending = false; for (PortListener l : _homeNet._portListeners) { l.portSendingEnd(_id); } }
From source file:com.ec2box.manage.util.EncryptionUtil.java
/** * return encrypted value of string// w w w.j a v a 2 s . c o m * * @param str unencrypted string * @return encrypted string */ public static String encrypt(String str) { String retVal = null; if (str != null && str.length() > 0) { try { Cipher c = Cipher.getInstance("AES"); c.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES")); byte[] encVal = c.doFinal(str.getBytes()); retVal = new String(Base64.encodeBase64(encVal)); } catch (Exception ex) { log.error(ex.toString(), ex); } } return retVal; }
From source file:net.geertvos.gossip.core.Md5HashProvider.java
@Override public String hashCluster(Collection<GossipClusterMember> members) { List<GossipClusterMember> sortedMembers = new ArrayList<GossipClusterMember>(members); Collections.sort(sortedMembers, comperator); StringBuilder stringBuilder = new StringBuilder(); for (ClusterMember member : sortedMembers) { stringBuilder.append(member.getId() + "|"); }/*w w w . j a v a 2s . c o m*/ byte[] bytes = stringBuilder.toString().getBytes(charset); byte[] digest = digester.digest(bytes); byte[] encoded = Base64.encodeBase64(digest); return new String(encoded, charset); }
From source file:com.microsoft.azure.management.TestVirtualMachineCustomData.java
@Override public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception { final String vmName = "vm" + this.testId; final String publicIpDnsLabel = SdkContext.randomResourceName("abc", 16); // Prepare the custom data ///*from w w w .j a v a 2 s .c o m*/ String cloudInitFilePath = getClass().getClassLoader().getResource("cloud-init").getPath(); cloudInitFilePath = cloudInitFilePath.replaceFirst("^/(.:/)", "$1"); // In Windows remove leading slash byte[] cloudInitAsBytes = Files.readAllBytes(Paths.get(cloudInitFilePath)); byte[] cloudInitEncoded = Base64.encodeBase64(cloudInitAsBytes); String cloudInitEncodedString = new String(cloudInitEncoded); PublicIPAddress pip = pips.define(publicIpDnsLabel).withRegion(Region.US_EAST).withNewResourceGroup() .withLeafDomainLabel(publicIpDnsLabel).create(); VirtualMachine vm = virtualMachines.define(vmName).withRegion(pip.regionName()) .withExistingResourceGroup(pip.resourceGroupName()).withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(pip) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!") .withCustomData(cloudInitEncodedString).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create(); pip.refresh(); Assert.assertTrue(pip.hasAssignedNetworkInterface()); if (!MockIntegrationTestBase.IS_MOCKED) { JSch jsch = new JSch(); Session session = null; ChannelExec channel = null; try { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session = jsch.getSession("testuser", publicIpDnsLabel + "." + "eastus.cloudapp.azure.com", 22); session.setPassword("12NewPA$$w0rd!"); session.setConfig(config); session.connect(); // Try running the package installed via init script // channel = (ChannelExec) session.openChannel("exec"); BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream())); channel.setCommand("pwgen;"); channel.connect(); String msg; while ((msg = in.readLine()) != null) { Assert.assertFalse(msg.startsWith("The program 'pwgen' is currently not installed")); } } catch (Exception e) { Assert.fail("SSH connection failed" + e.getMessage()); } finally { if (channel != null) { channel.disconnect(); } if (session != null) { session.disconnect(); } } } return vm; }
From source file:com.rackspacecloud.blueflood.io.serializers.HistogramSerializationTest.java
@Test public void testSerializationDeserializationVersion1() throws Exception { if (System.getProperty("GENERATE_HIST_SERIALIZATION") != null) { OutputStream os = new FileOutputStream( "src/test/resources/serializations/histogram_version_" + Constants.VERSION_1_HISTOGRAM + ".bin", false);/* w ww. jav a 2 s . c o m*/ os.write(Base64.encodeBase64(HistogramSerializer.get().toByteBuffer(histogramRollup).array())); os.write("\n".getBytes()); os.close(); } Assert.assertTrue(new File("src/test/resources/serializations").exists()); // ensure we can read historical serializations. int version = 0; int maxVersion = Constants.VERSION_1_HISTOGRAM; while (version <= maxVersion) { BufferedReader reader = new BufferedReader( new FileReader("src/test/resources/serializations/histogram_version_" + version + ".bin")); ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes())); HistogramRollup histogramRollupDes = HistogramSerializer.get().fromByteBuffer(bb); Assert.assertTrue(areHistogramsEqual(histogramRollup, histogramRollupDes)); version++; } }
From source file:com.vimukti.accounter.developer.api.PublicKeyGenerator.java
private static void generate() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException, KeyStoreException, CertificateException, IOException, URISyntaxException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed("VimTech".getBytes("UTF-8")); keyGen.initialize(1024, random);/*from w w w . java2s . c om*/ KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); System.out.println(priv); System.out.println(pub); byte[] encoded = pub.getEncoded(); byte[] encodeBase64 = Base64.encodeBase64(encoded); System.out.println("Public Key:" + new String(encodeBase64)); byte[] encodedPrv = priv.getEncoded(); byte[] encodeBase64Prv = Base64.encodeBase64(encodedPrv); System.out.println("Private Key:" + new String(encodeBase64Prv)); byte[] decodeBase64 = Base64.decodeBase64(encodeBase64); X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(decodeBase64); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); System.out.println(keyFactory.generatePublic(pubKeySpec).equals(pub)); }