Java Code Examples for java.util.Base64

The following are top voted examples for showing how to use java.util.Base64. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: JavaSDK   File: PortfolioDataFile.java   Source Code and License 8 votes vote down vote up
/**
 * Combines multiple files into a ZIP archive, then base-64 the ZIP archive.
 *
 * @param paths a list of one or more input files, that are to be compressed together
 * @return the compressed output, as a String
 */
private static String zipBase64(List<Path> paths) {
  if (paths.isEmpty()) {
    throw new IllegalArgumentException("PortfolioDataFile requires at least one file");
  }
  try {
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 8)) {
      try (OutputStream baseos = Base64.getEncoder().wrap(baos)) {
        try (ZipOutputStream zos = new ZipOutputStream(baseos)) {
          for (Path path : paths) {
            ZipEntry entry = new ZipEntry(path.getFileName().toString());
            zos.putNextEntry(entry);
            Files.copy(path, zos);
            zos.closeEntry();
          }
        }
      }
      return baos.toString("ISO-8859-1");  // base-64 bytes are ASCII, so this is optimal
    }
  } catch (IOException ex) {
    throw new UncheckedIOException("Failed to zip base-64 content", ex);
  }
}
 
Example 2
Project: scancode   File: Image.java   Source Code and License 6 votes vote down vote up
public Image(long code) throws IOException {
  try {
    this.bufferedImage = ImageIO.read(new File(DEFAULT_LOCATION));
    sideLength = bufferedImage.getWidth() / 16;
  } catch (IOException e) {
    Logger.getGlobal().log(Level.SEVERE, String.valueOf(e));
  }

  for (int i = 0; i < 33; i++) {
    if ((code & ((long) 1 << (32 - i))) != 0L) {
      drawTopLeft(i);
    }
  }

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ImageIO.write(bufferedImage, "png", baos);
  byte[] bufferedImageBytes = baos.toByteArray();

  this.base64 = Base64.getEncoder().encodeToString(bufferedImageBytes);
}
 
Example 3
Project: bouncr   File: ForTestBackendApp.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    Base64.Decoder b64decoder = Base64.getUrlDecoder();
    final Undertow server = Undertow.builder()
            .addHttpListener(8083, "localhost")
            .setHandler(exchange -> {
                exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
                String credential = exchange.getRequestHeaders().getFirst("X-Bouncr-Credential");
                String[] tokens = credential.split("\\.", 3);
                String json = new String(b64decoder.decode(tokens[1]));


                exchange.getResponseSender().send("Server1\n"
                        + "profile=" + json + "\n"
                );
            })
            .build();
    Runtime.getRuntime().addShutdownHook(new Thread(server::stop));
    server.start();
}
 
Example 4
Project: edge-jwt-sample   File: JWTGenerator.java   Source Code and License 6 votes vote down vote up
private PublicKey getDERPublicKeyFromPEM(String key) throws Exception {
	try {
	    // strip of header, footer, newlines, whitespaces
	    String publicKeyPEM = key
	            .replace("-----BEGIN PUBLIC KEY-----", "")
	            .replace("-----END PUBLIC KEY-----", "")
	            .replaceAll("\\s", "");

	    // decode to get the binary DER representation
	    byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM);

	    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	    PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER));
	    return publicKey;
	} catch (Exception e) {
		throw new InvalidConfig("Invalid JWE public key");
	}
}
 
Example 5
Project: openjdk-jdk10   File: ProxyTunnelServer.java   Source Code and License 6 votes vote down vote up
private boolean authenticate(String authInfo) throws IOException {
    boolean matched = false;
    try {
        authInfo.trim();
        int ind = authInfo.indexOf(' ');
        String recvdUserPlusPass = authInfo.substring(ind + 1).trim();
        // extract encoded (username:passwd
        if (userPlusPass.equals(
                        new String( Base64.getMimeDecoder()
                                    .decode(recvdUserPlusPass))))
        {
            matched = true;
        }
    } catch (Exception e) {
          throw new IOException(
            "Proxy received invalid Proxy-Authorization value: "
             + authInfo);
      }
    return matched;
}
 
Example 6
Project: L2J-Global   File: SQLAccountManager.java   Source Code and License 6 votes vote down vote up
private static void addOrUpdateAccount(String account, String password, String level)
{
	try (Connection con = DatabaseFactory.getInstance().getConnection();
		PreparedStatement ps = con.prepareStatement("REPLACE accounts(login, password, accessLevel) VALUES (?, ?, ?)"))
	{
		final MessageDigest md = MessageDigest.getInstance("SHA");
		final byte[] newPassword = md.digest(password.getBytes("UTF-8"));
		ps.setString(1, account);
		ps.setString(2, Base64.getEncoder().encodeToString(newPassword));
		ps.setString(3, level);
		if (ps.executeUpdate() > 0)
		{
			System.out.println("Account " + account + " has been created or updated");
		}
		else
		{
			System.out.println("Account " + account + " does not exist");
		}
	}
	catch (Exception e)
	{
		System.out.println("There was error while adding/updating account:");
		System.out.println(e.getMessage());
	}
}
 
Example 7
Project: Juice   File: DESUtil.java   Source Code and License 6 votes vote down vote up
/**
     * 数据加密,算法(DES)
     *
     * @param data
     *            要进行加密的数据
     * @param desKey DES密钥
     * @return 加密后的数据
     */
    public static String encrypt(String data, byte[] desKey) {
        String encryptedData = null;
        try {
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(desKey);
            // 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            // 加密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key, sr);
            // 加密,并把字节数组编码成字符串
            encryptedData = Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
//            log.error("加密错误,错误信息:", e);
            throw new RuntimeException("加密错误,错误信息:", e);
        }
        return encryptedData;
    }
 
Example 8
Project: thjson   File: THJSONTokenizer.java   Source Code and License 6 votes vote down vote up
private Token readQuotedBytes() throws IOException {
	int c;
	for (;;) {
		c = in.read();
		switch (c) {
			case -1:
				throw new EOFException("Unexpected EOF reading quoted bytes at line " + getLine() + ":" + getCol());
			case '\n':
				throw new EOFException("Unexpected end of line reading quoted bytes at line " + getLine() + ":" + getCol());
			case '`':
				// End the bytes
				return new Token(Base64.getDecoder().decode(getToken(false, false).getBytes(UTF_8)), TokenType.BYTES);
			default:
				// Only allow valid Base64 characters: A-Z,a-z,0-9,\+
				if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=') {
					// Simply append to string so far
					token.append((char) c);
				} else {
					throw new IOException("Expected base64 character but got " + (char) c + " at line " + getLine() + ":" + getCol());
				}
		}
	}
}
 
Example 9
Project: microprofile-jwt-auth   File: RolesAllowedTest.java   Source Code and License 6 votes vote down vote up
@RunAsClient
@Test(groups = TCKConstants.TEST_GROUP_JAXRS,
    description = "Attempting access with BASIC auth header should fail with HTTP_UNAUTHORIZED")
public void callEchoBASIC() throws Exception {
    Reporter.log("callEchoBASIC, expect HTTP_UNAUTHORIZED");
    byte[] tokenb = Base64.getEncoder().encode("[email protected]:password".getBytes());
    String token = new String(tokenb);
    System.out.printf("basic: %s\n", token);

    String uri = baseURL.toExternalForm() + "/endp/echo";
    WebTarget echoEndpointTarget = ClientBuilder.newClient()
        .target(uri)
        .queryParam("input", "hello")
        ;
    Response response = echoEndpointTarget.request(TEXT_PLAIN).header(HttpHeaders.AUTHORIZATION, "BASIC "+token).get();
    Assert.assertEquals(response.getStatus(), HttpURLConnection.HTTP_UNAUTHORIZED);
    String reply = response.readEntity(String.class);
    System.out.println(reply);
}
 
Example 10
Project: aws-photosharing-example   File: Security.java   Source Code and License 6 votes vote down vote up
public static String getPasswordHash(String p_password, byte[] p_seed) {
		
   	byte[] pwd = p_password.getBytes();
   	byte[] result = new byte[pwd.length+p_seed.length];    	
   	
   	for (int i = 0; i<result.length;i++) {
   		if (i%2 == 0 && i/2<pwd.length) {    			
   			result[i] = pwd[i/2];
   		}
   		if ((i+1)%2 == 0 && (i+1)/2<p_seed.length) {    			
   			result[i] = p_seed[(i+1)/2];
   		}    		
   	}    	    
   	MessageDigest md = null;
   	try { md = MessageDigest.getInstance("SHA-256");} 
   	catch (NoSuchAlgorithmException e) {
           _logger.error(e.getMessage(), e);
       }
	
   	return Base64.getEncoder().encodeToString(md.digest(result));
}
 
Example 11
Project: edge-jwt-sample   File: JWTValidatorTest.java   Source Code and License 6 votes vote down vote up
private static String getPEMPublicKeyFromDER(PublicKey publicKey) {
	String begin = "-----BEGIN PUBLIC KEY-----";
	String end = "-----END PUBLIC KEY-----";
	X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
	String key = Base64.getEncoder().encodeToString(x509EncodedKeySpec.getEncoded());
	return begin + "\n" + key + "\n" + end;
}
 
Example 12
Project: wowza-letsencrypt-converter   File: PemCertKey.java   Source Code and License 6 votes vote down vote up
/**
 * Internal method used during parsing : sets the private key in this entry
 *
 * @param key the chunk containing certificate
 * @throws CertificateException if key already exists
 */
private void setPrivateKey(List<String> key) throws CertificateException, NoSuchAlgorithmException {
    if (privateKey != null) throw new CertificateException("More than one private key in PEM input");

    String b64key = key.subList(1, key.size()-1).stream().collect(Collectors.joining());
    byte[] binKey = Base64.getDecoder().decode(b64key);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(binKey);

    KeyFactory kf = KeyFactory.getInstance("RSA");
    try {
        privateKey = kf.generatePrivate(keySpec);
    }
    catch (InvalidKeySpecException e) {
        throw new CertificateException(e);
    }
}
 
Example 13
Project: minijax   File: AuthUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the username and password from a Basic Authentication header.
 *
 * @param auth The Basic Authentication header.
 * @return Either INVALID or a 2-item array.
 */
private static String[] getUsernamePassword(final String auth) {
    if (auth == null || !auth.startsWith(BASIC_PREFIX)) {
        // No Authorization header present
        // or not Basic authentication
        return INVALID;
    }

    final byte[] decodedBytes;
    try {
        decodedBytes = Base64.getDecoder().decode(auth.substring(BASIC_PREFIX.length()));
    } catch (final IllegalArgumentException ex) {
        return INVALID;
    }

    final String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
    final int colonIndex = decoded.indexOf(':');
    if (colonIndex == -1) {
        // No colon means this is a malformed header.
        return INVALID;
    }

    return decoded.split(":", 2);
}
 
Example 14
Project: OperatieBRP   File: PersoonCacheConsumer.java   Source Code and License 6 votes vote down vote up
private SelectieVerwerkTaakBericht maakSelectieTaak(List<PersoonCache> caches, List<SelectieAutorisatieBericht> autorisatieChunk) {
    SelectieVerwerkTaakBericht selectieTaak = new SelectieVerwerkTaakBericht();
    final List<SelectiePersoonBericht> selectiePersonen = new ArrayList<>();
    for (PersoonCache persoonCache : caches) {
        final SelectiePersoonBericht selectiePersoonBericht = new SelectiePersoonBericht();
        if (persoonCache.getAfnemerindicatieGegevens().length > 0) {
            final String afnemerindicatieData =
                    new String(Base64.getEncoder().encode(persoonCache.getAfnemerindicatieGegevens()), StandardCharsets.UTF_8);
            selectiePersoonBericht.setAfnemerindicatieGegevens(afnemerindicatieData);
        }
        if (persoonCache.getPersoonHistorieVolledigGegevens().length > 0) {
            final String persoonData = new String(Base64.getEncoder().encode(persoonCache.getPersoonHistorieVolledigGegevens()), StandardCharsets.UTF_8);
            selectiePersoonBericht.setPersoonHistorieVolledigGegevens(persoonData);
        }
        selectiePersonen.add(selectiePersoonBericht);
    }
    selectieTaak.setPersonen(selectiePersonen);
    selectieTaak.setSelectieAutorisaties(autorisatieChunk);
    selectieTaak.setSelectieRunId(selectie.getSelectierun().getId());
    selectieTaak.setSelectieStartDatum(DatumUtil.vanDatumNaarInteger(selectie.getSelectierun().getTijdstipStart()));
    return selectieTaak;
}
 
Example 15
Project: quilt   File: PskContextTest.java   Source Code and License 6 votes vote down vote up
@Test
public final void testGenerateFulfillment() {

  PskContext context = PskContext.fromReceiverAddress(TEST_SECRET, TEST_ADDRESS);

  InterledgerPayment payment = InterledgerPayment.builder()
      .destinationAccount(TEST_ADDRESS)
      .destinationAmount(BigInteger.valueOf(100L))
      .data(TEST_MESSAGE)
      .build();

  Fulfillment fulfillment = context.generateFulfillment(payment);

  assertEquals("Incorrect fulfillment.",
          ((PreimageSha256Fulfillment) fulfillment).getPreimage(),
          //TODO Fix crypto-conditions to use Bas64Url without padding
          //Base64.getUrlEncoder().withoutPadding().encodeToString(TEST_PREIMAGE));
          Base64.getUrlEncoder().encodeToString(TEST_PREIMAGE));

}
 
Example 16
Project: libtrails   File: SkinDownloader.java   Source Code and License 6 votes vote down vote up
public String getSkinUrl(GameProfile prof) throws ParseException {
    Collection<Property> ps = prof.getProperties().get("textures");

    if (ps == null || ps.isEmpty()) {
        return null;
    } else {
        Property p = Iterators.getLast(ps.iterator());

        JSONObject obj = (JSONObject) new JSONParser().parse(
                new String(Base64.getDecoder().decode(p.getValue())));

        obj = ((JSONObject) obj.get("textures"));
        obj = ((JSONObject) obj.get("SKIN"));
        return (String) obj.get("url");
    }
}
 
Example 17
Project: jdk8u-jdk   File: NTLMAuthentication.java   Source Code and License 5 votes vote down vote up
private String buildType3Msg (String challenge) throws GeneralSecurityException,
                                                       IOException  {
    /* First decode the type2 message to get the server nonce */
    /* nonce is located at type2[24] for 8 bytes */

    byte[] type2 = Base64.getDecoder().decode(challenge);
    byte[] nonce = new byte[8];
    new java.util.Random().nextBytes(nonce);
    byte[] msg = client.type3(type2, nonce);
    String result = "NTLM " + Base64.getEncoder().encodeToString(msg);
    return result;
}
 
Example 18
Project: ZeroNights-WebVillage-2017   File: DeserController.java   Source Code and License 5 votes vote down vote up
@RequestMapping("/jackson")
@ResponseBody
public String jackson(@RequestParam(value = "sess") String session) throws IOException, ClassNotFoundException {

    String webUserJackson = new String(Base64.getDecoder().decode(session), "utf-8");
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enableDefaultTyping();
    User webUser = (User) objectMapper.readValue(webUserJackson, Object.class);

    return "Hello " + webUser;
}
 
Example 19
Project: openjdk-jdk10   File: X509CertSelectorTest.java   Source Code and License 5 votes vote down vote up
private void testSubjectPublicKey() throws IOException, GeneralSecurityException {
    System.out.println("X.509 Certificate Match on subject public key");
    // bad match
    X509CertSelector selector = new X509CertSelector();
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
            Base64.getMimeDecoder().decode(testKey.getBytes()));
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PublicKey pubKey = keyFactory.generatePublic(keySpec);
    selector.setSubjectPublicKey(pubKey);
    checkMatch(selector, cert, false);

    // good match
    selector.setSubjectPublicKey(cert.getPublicKey());
    checkMatch(selector, cert, true);
}
 
Example 20
Project: JPascalCoin   File: PascalCoinClientImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Operation sendTo(Integer sender, Integer target, Double amount, Double fee, byte[] payload,
		PayLoadEncryptionMethod payloadMethod, String pwd) {
	Operation result = null;
	if (sender==null||target==null||amount==null||fee==null)
		throw new IllegalArgumentException("Missing mandatory params. sender,target, amount and fee are mandatory");
	Map<String,Object> body = getRPCBody();
	Map<String,Object> params = new HashMap<>();
	body.put("method","sendto");
	params.put("sender", sender);
	params.put("target", target);
	params.put("amount", amount);
	params.put("fee", fee);	
	if (payload!=null)
		params.put("payload", Base64.getEncoder().encodeToString(payload));		
	if (payloadMethod!=null)
		params.put("payloadMethod", payloadMethod);	
	if (pwd!=null)
		params.put("pwd", pwd);			
	body.put("params",params);
	Call<OpResult<Operation>> sendToCall= pascalCoinService.sendTo(body);
	try {
		Response<OpResult<Operation>> response = sendToCall.execute();
		if (response.body().isError())
		{
			logger.log(Level.SEVERE, response.body().getErrorMessage());
			throw new RuntimeException(response.body().getErrorMessage());
		}
		result = response.body().getResult();
	} catch (IOException e) {
		logger.log(Level.SEVERE, e.getMessage());
	}
	return result;
}
 
Example 21
Project: amv-access-api-poc   File: CryptoConverter.java   Source Code and License 5 votes vote down vote up
@Override
public String convertToEntityAttribute(String dbVal) {
    if (dbVal == null) {
        return null;
    }

    try {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(Base64.getDecoder().decode(dbVal)));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 22
Project: gp-watson-conversation   File: GP_To_WCS.java   Source Code and License 5 votes vote down vote up
/***
 * Create a new workspace on WCS if target workspace id is not provided Update
 * an existing workspace if target workspace id is provided
 * 
 * @param jsonWCSPayload
 * @return
 * @throws IOException
 */
private void checkWCSWorkspace(JsonObject jsonWCSPayload) throws IOException {

  // Fetch Command Line Params
  String targetWorkspaceId = getTargetworkspaceID();
  String versionDate = getVersionDate();

  // Get WCS Creds
  String wcsCreds = getWCSCreds();
  String authorizationHeader = "Basic " + Base64.getEncoder().encodeToString((wcsCreds).getBytes());

  // Create or Update Watson Conv Workspace
  WCSUtils.putWCSWorkspace(targetWorkspaceId, authorizationHeader, versionDate, jsonWCSPayload);
}
 
Example 23
Project: Much-Assembly-Required   File: TileMap.java   Source Code and License 5 votes vote down vote up
@Override
public JSONObject serialise() {
    JSONObject json = new JSONObject();

    byte[] terrain = new byte[width * width];

    for (int x = 0; x < World.WORLD_SIZE; x++) {
        for (int y = 0; y < World.WORLD_SIZE; y++) {
            terrain[x * width + y] = (byte) tiles[x][y];
        }
    }
    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Deflater compressor = new Deflater(Deflater.BEST_COMPRESSION, true);
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor);

        deflaterOutputStream.write(terrain);

        deflaterOutputStream.close();
        byte[] compressedBytes = stream.toByteArray();

        json.put("z", new String(Base64.getEncoder().encode(compressedBytes)));

    } catch (IOException e) {
        e.printStackTrace();
    }

    return json;
}
 
Example 24
Project: maxcube-java   File: Parser.java   Source Code and License 5 votes vote down vote up
/**
 * M:00,01,BASE64
 *
 * First two parts are not known, the base64 encoded string contains the devices and the rooms
 *
 */
void parseMeta(Cube cube, String input) throws IOException {
    String[] metadata = input.split(",");
    String base64 = metadata[metadata.length - 1];
    byte[] data = Base64.getDecoder().decode(base64.getBytes(UTF_8));

    try (ByteArrayInputStream bis = new ByteArrayInputStream(data)) {
        // first numbers are unknown
        bis.read(); bis.read();

        // read rooms
        int roomCount = bis.read();
        for (int i = 0; i < roomCount; i++) {
            cube.getRooms().add(Room.read(bis));
        }

        // read devices and map to rooms
        int deviceCount = bis.read();
        for (int i = 0; i < deviceCount; i++) {
            Device device = Device.readFrom(bis);
            int roomId = bis.read();
            Room room = cube.findRoom(roomId);
            room.getDevices().add(device);
        }

        // another last unknown byte
        bis.read();
    }
}
 
Example 25
Project: ARCLib   File: PptxExporter.java   Source Code and License 5 votes vote down vote up
private byte[] getPNGData(Picture picture, double width, double height) {
    Base64.Decoder decoder = Base64.getDecoder();
    byte[] decoded = decoder.decode(picture.getContent());

    if (picture.getType() == ImageType.SVG) {
        ByteArrayOutputStream pngStream = new ByteArrayOutputStream();
        //svgConverter.convertSvgToPng(new ByteArrayInputStream(decoded), pngStream, (float)width, (float)height);
        svgConverter.convertSvgToEmf(new ByteArrayInputStream(decoded), pngStream);

        return pngStream.toByteArray();
    } else {
        return decoded;
    }
}
 
Example 26
Project: openjdk-jdk10   File: DefineClass.java   Source Code and License 5 votes vote down vote up
private static ArrayList<Permission> getPermissions(MySecureClassLoader scl,
                                                    Policy p, String url,
                                                    String className,
                                                    String classBytes,
                                                    Certificate[] chain)
                                                    throws IOException {
    CodeSource cs = new CodeSource(new URL(url), chain);
    Base64.Decoder bd = Base64.getDecoder();
    byte[] bytes = bd.decode(classBytes);
    Class<?> c = scl.defineMyClass(className, bytes, cs);
    ProtectionDomain pd = c.getProtectionDomain();
    return Collections.list(p.getPermissions(pd).elements());
}
 
Example 27
Project: OpenJSharp   File: Main.java   Source Code and License 5 votes vote down vote up
private synchronized String[] getDigests(ZipEntry ze, ZipFile zf,
                                         MessageDigest[] digests)
    throws IOException {

    int n, i;
    InputStream is = null;
    try {
        is = zf.getInputStream(ze);
        long left = ze.getSize();
        while((left > 0)
            && (n = is.read(buffer, 0, buffer.length)) != -1) {
            for (i=0; i<digests.length; i++) {
                digests[i].update(buffer, 0, n);
            }
            left -= n;
        }
    } finally {
        if (is != null) {
            is.close();
        }
    }

    // complete the digests
    String[] base64Digests = new String[digests.length];
    for (i=0; i<digests.length; i++) {
        base64Digests[i] = Base64.getEncoder().encodeToString(digests[i].digest());
    }
    return base64Digests;
}
 
Example 28
Project: secrets-proxy   File: CreateOrUpdateSecretRequestV2.java   Source Code and License 5 votes vote down vote up
/**
 * @throws IllegalArgumentException if builder data is invalid.
 */
public CreateOrUpdateSecretRequestV2 build() {
    // throws IllegalArgumentException if content not valid base64.
    Base64.getDecoder().decode(content());

    CreateOrUpdateSecretRequestV2 request = autoBuild();
    return request;
}
 
Example 29
Project: secrets-proxy   File: CreateSecretRequestV2.java   Source Code and License 5 votes vote down vote up
/**
 * @throws IllegalArgumentException if builder data is invalid.
 */
public CreateSecretRequestV2 build() {
    // throws IllegalArgumentException if content not valid base64.
    Base64.getDecoder().decode(content());

    CreateSecretRequestV2 request = autoBuild();
    if (request.name().isEmpty()) {
        throw new IllegalStateException("name is empty");
    }
    return request;
}
 
Example 30
Project: JPascalCoin   File: PascalCoinClientTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test changeAccountInfo 
 */
@Test
public void testChangeAccountInfo()
{
	Operation op = client.changeAccountInfo(account2Id, account2Id, null, b58PubKey2, "Testing account", Short.parseShort("0"), 0.0, "Testing".getBytes() , PayLoadEncryptionMethod.AES, "123456");
	System.out.println(String.format("Operation Hash: %s\nOperation Type: %s(%s),Subtype: %s, Timestamp: %d\nAccount %d Account sender %d Balance: %.4f, Account dest: %d, Amount: %.4f, Block: %d, Fee:%.4f\nErrors %s, OpHash %s,\n Payload %s, Maturation %d, OperationBlock %d, V1Ophash %s\n,Valid %s ", op.getOpHash(), op.getType(),op.getTypeDescriptor(),op.getSubType(), op.getTime(), op.getAccount(),op.getSenderAccount(), op.getBalance(), op.getDestAccount(), op.getAmount(), op.getBlock(), op.getFee(), op.getErrors(),op.getOpHash(), Base64.getEncoder().encodeToString(op.getPayLoad()),op.getMaturation(), op.getOperationBlock(), op.getV1Ophash(), op.getValid() ));
	assertTrue(op!=null);
}
 
Example 31
Project: JPascalCoin   File: PascalCoinClientTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test sendTo 
 */
@Test
public void testSendTo()
{
	Operation op = client.sendTo(accountId, account3Id, 1.0000, 0.0, null, null, null);
	System.out.println(String.format("Operation Hash: %s\nOperation Type: %s(%s),Subtype: %s, Timestamp: %d\nAccount %d Account sender %d Balance: %.4f, Account dest: %d, Amount: %.4f, Block: %d, Fee:%.4f\nErrors %s, OpHash %s,\n Payload %s, Maturation %d, OperationBlock %d, V1Ophash %s\n,Valid %s ", op.getOpHash(), op.getType(),op.getTypeDescriptor(),op.getSubType(), op.getTime(), op.getAccount(),op.getSenderAccount(), op.getBalance(), op.getDestAccount(), op.getAmount(), op.getBlock(), op.getFee(), op.getErrors(),op.getOpHash(), Base64.getEncoder().encodeToString(op.getPayLoad()),op.getMaturation(), op.getOperationBlock(), op.getV1Ophash(), op.getValid() ));
	assertTrue(op!=null);
}
 
Example 32
Project: JPascalCoin   File: PascalCoinClientTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test listAccountForSale
 */
@Test
public void testListAccountForSale()
{
	Operation op = client.listAccountForSale(account2Id, account2Id, 1000.0000, accountId, null, null, 151125, 0.0, "Testing listAccountForSale".getBytes() , PayLoadEncryptionMethod.AES, "123456");
	System.out.println(String.format("Operation Hash: %s\nOperation Type: %s(%s),Subtype: %s, Timestamp: %d\nAccount %d Account sender %d Balance: %.4f, Account dest: %d, Amount: %.4f, Block: %d, Fee:%.4f\nErrors %s, OpHash %s,\n Payload %s, Maturation %d, OperationBlock %d, V1Ophash %s\n,Valid %s ", op.getOpHash(), op.getType(),op.getTypeDescriptor(),op.getSubType(), op.getTime(), op.getAccount(),op.getSenderAccount(), op.getBalance(), op.getDestAccount(), op.getAmount(), op.getBlock(), op.getFee(), op.getErrors(),op.getOpHash(), Base64.getEncoder().encodeToString(op.getPayLoad()),op.getMaturation(), op.getOperationBlock(), op.getV1Ophash(), op.getValid() ));
	assertTrue(op!=null);
}
 
Example 33
Project: gemnasium-maven-plugin   File: AuthUtils.java   Source Code and License 5 votes vote down vote up
public static String getEncodedBasicToken(String apiKey) throws MojoExecutionException {
    if (apiKey == null || apiKey.isEmpty()) {
        throw new MojoExecutionException("please provide your Gemnasium apiKey");
    }
    return Base64
        .getEncoder()
        .encodeToString(("X:" + apiKey).getBytes(StandardCharsets.UTF_8));
}
 
Example 34
Project: edge-jwt-sample   File: JWTValidatorTest.java   Source Code and License 5 votes vote down vote up
private PublicKey getDERPublicKeyFromPEM(String key) {
	try {
	    // strip of header, footer, newlines, whitespaces
	    String publicKeyPEM = key
	            .replace("-----BEGIN PUBLIC KEY-----", "")
	            .replace("-----END PUBLIC KEY-----", "")
	            .replaceAll("\\s", "");

	    // decode to get the binary DER representation
	    byte[] publicKeyDER = Base64.getDecoder().decode(publicKeyPEM);

	    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	    PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyDER));
	    return publicKey;
	} catch (Exception e) {
		return null;
	}
}
 
Example 35
Project: xmlrss   File: GLProof.java   Source Code and License 5 votes vote down vote up
public GLProof(GLRSSSignatureOutput.GLRSSSignedPart signedPart) {
    Base64.Encoder encoder = Base64.getEncoder();
    this.randomValue = encoder.encodeToString(signedPart.getRandomValue());
    this.accumulatorValue = encoder.encodeToString(signedPart.getAccumulatorValue());
    this.gsProof = encoder.encodeToString(signedPart.getGsProof());
    for (ByteArray byteArray : signedPart.getWitnesses()) {
        witnesses.add(encoder.encodeToString(byteArray.getArray()));
    }
}
 
Example 36
Project: NutriBuddi   File: UserGoalStepsDelete.java   Source Code and License 5 votes vote down vote up
@When("^she makes a request to usergoal/deleteUserGoal$")
public void sheMakesARequestToUsergoalDeleteUserGoal() throws Throwable {
    String userAuthorization = "Basic " + Base64.getEncoder().encodeToString(("user" + ":" + "default").getBytes());
    response = mockMvc.perform(get("http://localhost:8080/userGoal/deleteUserGoal")
            .header("Authorization", userAuthorization)
            .param("email", "[email protected]")
            .accept(MediaType.APPLICATION_JSON));
}
 
Example 37
Project: pac4j-plus   File: RedirectSAML2ClientTests.java   Source Code and License 5 votes vote down vote up
private String getInflatedAuthnRequest(final String location) throws Exception {
    final List<NameValuePair> pairs = URLEncodedUtils.parse(java.net.URI.create(location), "UTF-8");
    final Inflater inflater = new Inflater(true);
    final byte[] decodedRequest = Base64.getDecoder().decode(pairs.get(0).getValue());
    final ByteArrayInputStream is = new ByteArrayInputStream(decodedRequest);
    final InflaterInputStream inputStream = new InflaterInputStream(is, inflater);
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, HttpConstants.UTF8_ENCODING));
    String line;
    final StringBuilder bldr = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        bldr.append(line);
    }
    return bldr.toString();
}
 
Example 38
Project: scancode   File: Image.java   Source Code and License 5 votes vote down vote up
public Image(String base64) throws IOException {
  this.base64 = base64;

  byte[] bufferedImageByte = Base64.getDecoder().decode(base64);
  ByteArrayInputStream bis = new ByteArrayInputStream(bufferedImageByte);
  this.bufferedImage = ImageIO.read(bis);
}
 
Example 39
Project: holon-core   File: TestCredentials.java   Source Code and License 5 votes vote down vote up
@Test
public void testCredentialsEncoder() throws UnsupportedEncodingException {

	TestUtils.expectedException(IllegalStateException.class, new Runnable() {

		@Override
		public void run() {
			Credentials.encoder().build();
		}
	});

	final String secret = "test";
	final byte[] secretBytes = ConversionUtils.toBytes(secret);

	byte[] bytes = Credentials.encoder().secret(secret).build();
	assertTrue(Arrays.equals(secretBytes, bytes));

	String sb = Credentials.encoder().secret(secret).buildAndEncodeBase64();
	assertEquals(Base64.getEncoder().encodeToString(secret.getBytes("UTF-8")), sb);

	bytes = Credentials.encoder().secret(secret).hashMD5().build();
	assertNotNull(bytes);
	bytes = Credentials.encoder().secret(secret).hashSHA1().build();
	assertNotNull(bytes);
	bytes = Credentials.encoder().secret(secret).hashSHA256().build();
	assertNotNull(bytes);
	bytes = Credentials.encoder().secret(secret).hashSHA384().build();
	assertNotNull(bytes);
	bytes = Credentials.encoder().secret(secret).hashSHA512().charset("UTF-8").build();
	assertNotNull(bytes);

	TestUtils.expectedException(RuntimeException.class, new Runnable() {

		@Override
		public void run() {
			Credentials.encoder().secret("test").hashAlgorithm("xxx").build();
		}
	});

}
 
Example 40
Project: jdk8u-jdk   File: TestBase64.java   Source Code and License 5 votes vote down vote up
private static void testNull(Base64.Encoder enc) {
    checkNull(() -> enc.encode(ba_null));
    checkNull(() -> enc.encodeToString(ba_null));
    checkNull(() -> enc.encode(ba_null, new byte[10]));
    checkNull(() -> enc.encode(new byte[10], ba_null));
    checkNull(() -> enc.encode(bb_null));
    checkNull(() -> enc.wrap((OutputStream)null));
}
 
Example 41
Project: beaker-notebook-archive   File: ImageContainer.java   Source Code and License 5 votes vote down vote up
public static MIMEContainer Image(Object data) throws Exception {
  byte[] image;
  if (data instanceof String) {
    image = getBytes(data);
  } else {
    image = (byte[]) data;
  }
  return addMimeType(isJPEG(image) ? MIME.IMAGE_JPEG : MIME.IMAGE_PNG, Base64.getEncoder().encodeToString(image));
}
 
Example 42
Project: hall   File: RSAUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 得到公钥
 *
 * @param key 密钥字符串(经过base64编码)
 * @throws Exception
 */
public static PublicKey getPublicKey(String key) throws Exception {
    byte[] keyBytes;
    keyBytes = Base64.getDecoder().decode(key);
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePublic(keySpec);
}
 
Example 43
Project: samsung-email-password-decrypt   File: DecryptSamsungEmailPassword.java   Source Code and License 5 votes vote down vote up
private static String decrypt(String encodedPassword) throws Exception {
	byte[] encodedBytes = Base64.getDecoder().decode(encodedPassword);

	Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	byte[] keybytes = new byte[]
		{14,-89,-110,62,-52,110,-105,-97,99,61,4,21,-95,-30,8,113};
	SecretKeySpec seckey = new SecretKeySpec(keybytes, "AES");
	IvParameterSpec ivspec = new IvParameterSpec(new byte[16]);
	cipher.init(Cipher.DECRYPT_MODE, seckey, ivspec);
		
	return new String(cipher.doFinal(encodedBytes));
}
 
Example 44
Project: daf-cacher   File: ScreenShotService.java   Source Code and License 5 votes vote down vote up
public byte[] fetch(String id, String size) {
    final String redisKey = REDIS_NS + id + ":" + size;
    final String payload = jedis.get(redisKey);

    if (payload != null && payload.length() > 0) {
        return Base64.getDecoder().decode(payload);
    }
    return new byte[0];
}
 
Example 45
Project: TurteTracker_APIServer   File: TestClient.java   Source Code and License 5 votes vote down vote up
private static void deleteNest(String id) throws Exception {
    URL url = new URI("http", ip, "/api/v1/nest/" + id, null, null).toURL();
    Map<String, String> headers = new HashMap<>();
    String base = Base64.getEncoder().encodeToString("admin:[email protected]".getBytes("UTF-8"));
    headers.put("Authorization", "Basic " + base);
    Response res = new Response();
    System.out.println(readString(doDelete(url, headers, res)));
}
 
Example 46
Project: killbill-easytax-plugin   File: EasyTaxServlet.java   Source Code and License 5 votes vote down vote up
private int checkPermission(Tenant tenant, Set<Permission> required, HttpServletRequest req) {
    if (required.isEmpty()) {
        return 0;
    }
    String authHeader = req.getHeader("Authorization");
    if (authHeader == null) {
        return 401;
    }

    final String[] authHeaderComponents = authHeader.split(" ");
    if (authHeaderComponents.length < 2) {
        return 403;
    }

    try {
        final String credentials = new String(
                Base64.getDecoder().decode(authHeaderComponents[1]), "UTF-8").trim();
        final String[] credentialComponents = credentials.split(":", 2);
        if (credentialComponents.length < 2) {
            return 403;
        }

        securityApi.login(credentialComponents[0], credentialComponents[1]);
        TenantContext context = new EasyTaxTenantContext(tenant.getId(), null);
        Set<Permission> granted = securityApi.getCurrentUserPermissions(context);
        if (granted == null) {
            return 403;
        }
        if (granted.containsAll(required)) {
            return 0;
        }
    } catch (Exception e) {
        // ignore and deny
        log.info("Permission check failed for Authorization header {}: {}", authHeader,
                e.getMessage());
    }
    return 403;
}
 
Example 47
Project: Pet-Supply-Store   File: CreatorRunner.java   Source Code and License 5 votes vote down vote up
@Override
public void run() {
	long imgID = ImageIDFactory.ID.getNextImageID();
	Random rand = new Random(productID);
	
	// All products must be added to the database
	imgDB.setImageMapping(productID, imgID, size);

	// Resolve path and create a new image
	Path imgFile = workingDir.resolve(String.valueOf(imgID));
	
	BufferedImage img = ImageCreator.createImage(shapesPerImage, categoryImage, size, rand);
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	
	try {
		ImageIO.write(img, StoreImage.STORE_IMAGE_FORMAT, stream);
		Files.write(imgFile, Base64.getEncoder().encode(stream.toByteArray()), 
				StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
	} catch (IOException ioException) {
		if (!(ioException instanceof ClosedByInterruptException)) {
			log.warn("An IOException occured while writing image with ID " + String.valueOf(imgID) + " to file "
					+ imgFile.toAbsolutePath() + ".", ioException);
		} else {
			log.warn("An exception was thrown during image creation with ID " + String.valueOf(imgID) + " to file "
					+ imgFile.toAbsolutePath() + ".", ioException);
		}
	}
	
	nrOfImagesGenerated.incrementAndGet();
}
 
Example 48
Project: quilt   File: PreimageSha256FulfillmentTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGettersAndSetters() throws Exception {
  final PreimageSha256Fulfillment actual = new PreimageSha256Fulfillment(
      "Hello World".getBytes());
  assertThat(Base64.getUrlDecoder().decode(actual.getPreimage()),
      is("Hello World".getBytes()));
  assertThat(actual.getType(), is(CryptoConditionType.PREIMAGE_SHA256));
}
 
Example 49
Project: exam   File: ExamRecordController.java   Source Code and License 5 votes vote down vote up
@With(ExamRecordSanitizer.class)
@Restrict({@Group("TEACHER"), @Group("ADMIN")})
public Result exportSelectedExamRecordsAsExcel(Long examId) {
    Collection<Long> childIds = request().attrs().get(Attrs.ID_COLLECTION);
    ByteArrayOutputStream bos;
    try {
        bos = ExcelBuilder.build(examId, childIds);
    } catch (IOException e) {
        return internalServerError("sitnet_error_creating_csv_file");
    }
    response().setHeader("Content-Disposition", "attachment; filename=\"exam_records.xlsx\"");
    return ok(Base64.getEncoder().encodeToString(bos.toByteArray()));
}
 
Example 50
Project: hawkular-java-toolbox   File: HawkularClientBuilder.java   Source Code and License 5 votes vote down vote up
private HawkularHttpClient setupClient() {
    HawkularHttpClient client = httpClientProvider
            .map(provider -> provider.apply(uri))
            .orElseGet(() -> new JdkHawkularHttpClient(uri));
    headers.put(KEY_HEADER_TENANT, tenant);
    basicAuthCredential.ifPresent(cred -> {
        String encoded = Base64.getEncoder().encodeToString((cred.getUsername() + ":" + cred.getPassword()).getBytes());
        headers.put(KEY_HEADER_AUTHORIZATION, "Basic " + encoded);
    });
    bearerToken.ifPresent(token -> headers.put(KEY_HEADER_AUTHORIZATION, "Bearer " + token));
    client.addHeaders(headers);
    client.setFailoverOptions(failoverCacheDuration, failoverCacheMaxSize);
    return client;
}
 
Example 51
Project: oauth-filter-for-java   File: RsaPublicKeyCreator.java   Source Code and License 5 votes vote down vote up
static PublicKey createPublicKey(String modulus, String exponent) throws InvalidKeySpecException, NoSuchAlgorithmException
{
    Base64.Decoder decoder = Base64.getDecoder();
    BigInteger bigModulus = new BigInteger(1, decoder.decode(modulus));
    BigInteger bigExponent = new BigInteger(1, decoder.decode(exponent));
    RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(bigModulus, bigExponent);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    return keyFactory.generatePublic(publicKeySpec);
}
 
Example 52
Project: openjdk-jdk10   File: MSOID.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        // msoid.txt is a NegTokenInit packet sent from Internet Explorer to
        // IIS server on a test machine. No sensitive info included.
        byte[] header = Files.readAllBytes(
                Paths.get(System.getProperty("test.src"), "msoid.txt"));
        byte[] token = Base64.getMimeDecoder().decode(
                Arrays.copyOfRange(header, 10, header.length));

        GSSCredential cred = null;
        GSSContext ctx = GSSManager.getInstance().createContext(cred);

        try {
            ctx.acceptSecContext(token, 0, token.length);
            // Before the fix, GSS_KRB5_MECH_OID_MS is not recognized
            // and acceptor chooses another mech and goes on
            throw new Exception("Should fail");
        } catch (GSSException gsse) {
            // After the fix, GSS_KRB5_MECH_OID_MS is recognized but the token
            // cannot be accepted because we don't have any krb5 credential.
            gsse.printStackTrace();
            if (gsse.getMajor() != GSSException.NO_CRED) {
                throw gsse;
            }
            for (StackTraceElement st: gsse.getStackTrace()) {
                if (st.getClassName().startsWith("sun.security.jgss.krb5.")) {
                    // Good, it is already in krb5 mech's hand.
                    return;
                }
            }
            throw gsse;
        }
    }
 
Example 53
Project: GabrielBot   File: OwnerCommands.java   Source Code and License 5 votes vote down vote up
@Command(
        name = "shutdown",
        description = "Makes me go offline :(",
        usage = "`>>shutdown`\n" +
                "`>>shutdown savemusic`",
        permission = CommandPermission.OWNER,
        category = CommandCategory.OWNER
)
public static void shutdown(@Argument("channel") TextChannel channel, @Argument("args") String[] args) {
    if (args.length > 0 && args[0].equals("savemusic")) {
        GabrielBot.getInstance().registry.commands().remove("play");
        JedisDataManager jdm = GabrielData.guilds();
        int[] i = new int[1];
        GabrielBot.getInstance().getPlayers().forEachValue(p->{
            if(p == null) return true;
            if(p.scheduler.currentTrack() == null) {
                p.leave();
                return true;
            }
            p.player.setPaused(true);
            List<Track> allTracks = new ArrayList<>();
            allTracks.add(p.scheduler.currentTrack());
            allTracks.addAll(p.scheduler.tracks());
            p.leave();
            if(p.textChannel.canTalk()) {
                p.textChannel.sendMessage("I'll be rebooting soon, but your queue has been saved and will be restored after I reboot").queue();
            }
            SerializedPlayer sp = new SerializedPlayer(allTracks.stream().map(SerializedTrack::new).collect(Collectors.toList()), allTracks.get(0).track.getPosition(), p.guildId, p.textChannel.getIdLong(), p.voiceChannel.getIdLong());
            jdm.set("p_" + p.guildId, Base64.getEncoder().encodeToString(KryoUtils.serialize(sp)));
            i[0]++;
            return true;
        });
        jdm.save();
        GabrielBot.LOGGER.info("Serialized tracks for {} guilds", i[0]);
    }
    GabrielData.save();
    channel.sendMessage("*Goes to sleep...*").complete();
    Arrays.stream(GabrielBot.getInstance().getShards()).forEach(s -> s.getJDA().shutdown());
    System.exit(0);
}
 
Example 54
Project: ColorMOTD   File: MotdServerIcon.java   Source Code and License 5 votes vote down vote up
static String imageToDataString(RenderedImage image) {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, "png", bout);
    } catch (IOException e) {
        throw new UncheckedIOException("Not possible", e);
    }

    byte[] data = bout.toByteArray();
    byte[] base64 = Base64.getEncoder().encode(data);
    return "data:image/png;base64," + new String(base64, StandardCharsets.UTF_8);
}
 
Example 55
Project: OrthancAnonymization   File: QueryFillStore.java   Source Code and License 5 votes vote down vote up
public QueryFillStore(){
	int curDb = jprefer.getInt("current database", 0);
	int typeDb = jprefer.getInt("db type" + curDb, 5);
	if(typeDb == 5){
		if(!jprefer.get("db path" + curDb, "none").equals("none")){
			String pathBrut = jprefer.get("db path" + curDb, "none") + "/";
			int index = ordinalIndexOf(pathBrut, "/", 3);
			this.fullAddress = pathBrut.substring(0, index);
		}else{
			String address = jprefer.get("ODBC" + curDb, "localhost");
			String pattern1 = "@";
			String pattern2 = ":";
			Pattern p = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
			Matcher m = p.matcher(address);
			while(m.find()){
				this.ip = "http://" + m.group(1);
			}
		}
		if(jprefer.get("db user" + curDb, null) != null && jprefer.get("db pass" + curDb, null) != null){
			authentication = Base64.getEncoder().encodeToString((jprefer.get("db user" + curDb, null) + ":" + jprefer.get("db pass" + curDb, null)).getBytes());
		}
	}else{
		this.ip = jpreferPerso.get("ip", "http://localhost");
		this.port = jpreferPerso.get("port", "8042");
		if(jpreferPerso.get("username", null) != null && jpreferPerso.get("password", null) != null){
			authentication = Base64.getEncoder().encodeToString((jpreferPerso.get("username", null) + ":" + jpreferPerso.get("password", null)).getBytes());
		}
	}
	this.setUrl("/tools/find");
}
 
Example 56
Project: exam   File: AttachmentController.java   Source Code and License 5 votes vote down vote up
private Result serveAttachment(Attachment attachment) {
    File file = new File(attachment.getFilePath());
    if (!file.exists()) {
        return internalServerError("Requested file does not exist on disk even though referenced from database!");
    }
    response().setHeader("Content-Disposition", "attachment; filename=\"" + attachment.getFileName() + "\"");
    String body = Base64.getEncoder().encodeToString(setData(file).toByteArray());
    return ok(body).as(attachment.getMimeType());
}
 
Example 57
Project: OperatieBRP   File: PersoonFragmentConsumer.java   Source Code and License 5 votes vote down vote up
private boolean append(String encodedFragment) throws SelectieResultaatVerwerkException {
    //voor de berekening van bytes nemen we de header en footer van bericht niet mee
    //controleer of huidige inhoud + toevoeging groter is dan max toegestaan
    final byte[] decodedXmlBytes = Base64.getDecoder().decode(encodedFragment.getBytes(StandardCharsets.UTF_8));
    if (decodedXmlBytes.length > berichtMaxBytes) {
        throw new IllegalArgumentException("");
    }
    boolean pastInBestand = (currentSet.personenInBericht + 1) <= berichtMaxPersonen
            && (currentSet.bytesInBericht + decodedXmlBytes.length) <= berichtMaxBytes;
    if (pastInBestand) {
        currentSet.appendPersoon(decodedXmlBytes);
    }
    return pastInBestand;
}
 
Example 58
Project: cloud-portal   File: AES.java   Source Code and License 5 votes vote down vote up
public static String decrypt(String strToDecrypt, String secret) {
    
	try {
		SecretKeySpec secretKey = getSecretKey(secret);
        Cipher cipher = Cipher.getInstance(ECB_PKCS5PADDING);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
    }
    catch (Exception e) {
    	LOG.error(e.getMessage(), e);
    }
    
    return null;
}
 
Example 59
Project: hands-on-neo4j-devoxx-fr-2017   File: ExerciseExporterTest.java   Source Code and License 5 votes vote down vote up
private static void assertThatDeserializedResult(String expectedBase64, Consumer<List<Map<String, Object>>> asserts) throws IOException {
    byte[] bytes = Base64.getDecoder().decode(expectedBase64);
    try (ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes)) {
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> result = KRYO.readObject(new Input(inputStream), ArrayList.class);
        asserts.accept(result);
    }
}
 
Example 60
Project: uroborosql   File: SecretColumnSqlFilter.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * パラメータが暗号化対象のパラメータ名と一致する場合、パラメータの値を暗号化する
 *
 * @see jp.co.future.uroborosql.filter.AbstractSqlFilter#doParameter(jp.co.future.uroborosql.parameter.Parameter)
 */
@Override
public Parameter doParameter(final Parameter parameter) {
	if (skipFilter || parameter == null) {
		return parameter;
	}

	if (Parameter.class.equals(parameter.getClass())) {
		// 通常のパラメータの場合
		String key = parameter.getParameterName();
		if (getCryptParamKeys().contains(CaseFormat.CAMEL_CASE.convert(key))) {
			Object obj = parameter.getValue();
			if (obj != null && obj instanceof String) {
				String objStr = obj.toString();
				if (StringUtils.isNotEmpty(objStr)) {
					try {
						synchronized (encryptCipher) {
							byte[] crypted = encryptCipher.doFinal(StringUtils.defaultString(objStr).getBytes(
									getCharset()));
							return new Parameter(key, Base64.getUrlEncoder().withoutPadding().encodeToString(crypted));
						}
					} catch (Exception ex) {
						return parameter;
					}
				}
			}
		}
	}

	return parameter;
}