java.util.Base64 Java Examples

The following examples show how to use java.util.Base64. 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: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a random number using two UUIDs and HMAC-SHA1
 *
 * @return Random Number generated.
 * @throws IdentityException Exception due to Invalid Algorithm or Invalid Key
 */
public static String getRandomNumber() throws IdentityException {
    try {
        String secretKey = UUIDGenerator.generateUUID();
        String baseString = UUIDGenerator.generateUUID();

        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(key);
        byte[] rawHmac = mac.doFinal(baseString.getBytes());
        String random = Base64.getEncoder().encodeToString(rawHmac);
        // Registry doesn't have support for these character.
        random = random.replace("/", "_");
        random = random.replace("=", "a");
        random = random.replace("+", "f");
        return random;
    } catch (Exception e) {
        log.error("Error when generating a random number.", e);
        throw IdentityException.error("Error when generating a random number.", e);
    }
}
 
Example #2
Source File: WebhookBuilderDelegateImpl.java    From Javacord with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Webhook> create() {
    if (name == null) {
        throw new IllegalStateException("Name is no optional parameter!");
    }
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    body.put("name", name);
    if (avatar != null) {
        return avatar.asByteArray(channel.getApi()).thenAccept(bytes -> {
            String base64Avatar = "data:image/" + avatar.getFileType() + ";base64,"
                    + Base64.getEncoder().encodeToString(bytes);
            body.put("avatar", base64Avatar);
        }).thenCompose(aVoid ->
                new RestRequest<Webhook>(channel.getApi(), RestMethod.POST, RestEndpoint.CHANNEL_WEBHOOK)
                        .setUrlParameters(channel.getIdAsString())
                        .setBody(body)
                        .setAuditLogReason(reason)
                        .execute(result -> new WebhookImpl(channel.getApi(), result.getJsonBody())));
    }
    return new RestRequest<Webhook>(channel.getApi(), RestMethod.POST, RestEndpoint.CHANNEL_WEBHOOK)
            .setUrlParameters(channel.getIdAsString())
            .setBody(body)
            .setAuditLogReason(reason)
            .execute(result -> new WebhookImpl(channel.getApi(), result.getJsonBody()));
}
 
Example #3
Source File: Base64GetEncoderTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static void testWrapEncode2(final Base64.Encoder encoder)
        throws IOException {
    System.err.println("\nEncoder.wrap test II ");
    final byte[] secondTestBuffer =
            "api/java_util/Base64/index.html#GetEncoderMimeCustom[noLineSeparatorInEncodedString]"
            .getBytes(US_ASCII);
    String base64EncodedString;
    ByteArrayOutputStream secondEncodingStream = new ByteArrayOutputStream();
    OutputStream base64EncodingStream = encoder.wrap(secondEncodingStream);
    base64EncodingStream.write(secondTestBuffer);
    base64EncodingStream.close();

    final byte[] encodedByteArray = secondEncodingStream.toByteArray();

    System.err.print("result = " + new String(encodedByteArray, US_ASCII)
            + "  after wrap Base64 encoding of string");

    base64EncodedString = new String(encodedByteArray, US_ASCII);

    if (base64EncodedString.contains("$$$")) {
        throw new RuntimeException(
                "Base64 encoding contains line separator after wrap 2 invoked  ... \n");
    }
}
 
Example #4
Source File: Base64GetEncoderTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private static void testWrapEncode1(final Base64.Encoder encoder)
        throws IOException {
    System.err.println("\nEncoder.wrap test I ");

    final byte[] bytesIn = "fo".getBytes(US_ASCII);
    String base64EncodedString;
    ByteArrayOutputStream encodingStream = new ByteArrayOutputStream();
    OutputStream encoding = encoder.wrap(encodingStream);
    encoding.write(bytesIn);
    encoding.close();

    final byte[] encodedBytes = encodingStream.toByteArray();

    System.err.print("result = " + new String(encodedBytes, US_ASCII)
            + "  after the Base64 encoding \n");

    base64EncodedString = new String(encodedBytes, US_ASCII);

    if (base64EncodedString.contains("$$$")) {
        throw new RuntimeException(
                "Base64 encoding contains line separator after wrap I test ... \n");
    }
}
 
Example #5
Source File: ImageLayout.java    From Alice-LiveMan with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void paintLayout(Graphics2D g) throws IOException {
    if (imageBase64 == null) {
        int startPoint = src.indexOf(",");
        if (startPoint > -1) {
            imageBase64 = src.substring(startPoint + 1);
        } else {
            imageBase64 = src;
        }
    }
    byte[] bytes = Base64.getDecoder().decode(imageBase64);
    try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes)) {
        BufferedImage image = ImageIO.read(bis);
        Composite oldComp = g.getComposite();
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
        g.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), x, y, null);
        g.setComposite(oldComp);
    }
}
 
Example #6
Source File: ComponentProxyCustomizerTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSend() throws Exception {
    assertThat(context.getBean("my-bean", MyBean.class)).isNotNull();

    final ProducerTemplate template = camelContext.createProducerTemplate();
    final MockEndpoint mock = camelContext.getEndpoint("mock:result", MockEndpoint.class);
    final String body = "hello";
    final String expected = Base64.getEncoder().encodeToString("HELLO WORLD!".getBytes(StandardCharsets.US_ASCII));

    mock.expectedMessageCount(1);
    mock.expectedBodiesReceived(expected);

    template.sendBody("direct:start", body);

    mock.assertIsSatisfied();
}
 
Example #7
Source File: OTATest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testOTAWrongToken() throws Exception {
    HttpPost post = new HttpPost(httpsAdminServerUrl + "/ota/start?token=" + 123);
    post.setHeader(HttpHeaderNames.AUTHORIZATION.toString(), "Basic " + Base64.getEncoder().encodeToString(auth));

    String fileName = "test.bin";

    InputStream binFile = OTATest.class.getResourceAsStream("/static/ota/" + fileName);
    ContentBody fileBody = new InputStreamBody(binFile, ContentType.APPLICATION_OCTET_STREAM, fileName);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("upfile", fileBody);
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try (CloseableHttpResponse response = httpclient.execute(post)) {
        assertEquals(400, response.getStatusLine().getStatusCode());
        String error = TestUtil.consumeText(response);

        assertNotNull(error);
        assertEquals("Invalid token.", error);
    }
}
 
Example #8
Source File: SolutionSettingsControllerTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Test(timeout = SolutionSettingsControllerTest.TIMEOUT)
@Category({UnitTest.class})
public void setLogoShouldReturnGivenLogo() throws BaseException, ExecutionException, InterruptedException, UnsupportedEncodingException, URISyntaxException {
    // Arrange
    String image = rand.NextString();
    String type = rand.NextString();
    Logo model = new Logo(image, type, null, false);
    setLogoMockSetup(model);
    controller = new SolutionSettingsController(mockStorage, mockActions);
    Http.Response mockResponse = TestUtils.setRequest(SolutionSettingsControllerTest.LOGO_BODY);

    // Act
    byte[] bytes = TestUtils.getBytes(controller.setLogoAsync().toCompletableFuture().get());
    byte[] bytesold = Base64.getDecoder().decode(model.getImage().getBytes());

    // Assert
    assertEquals(ByteString.fromArray(bytes), ByteString.fromArray(bytesold));
    Mockito.verify(mockResponse).setHeader(Logo.IS_DEFAULT_HEADER, Boolean.toString(false));
}
 
Example #9
Source File: JwtUtil.java    From cubeai with Apache License 2.0 6 votes vote down vote up
public static String getUserLogin(HttpServletRequest httpServletRequest) {
    String authorization = httpServletRequest.getHeader("authorization");
    if (null == authorization) {
        // 请求头中没有携带JWT,表示非登录用户
        return null;
    }

    String jwt = authorization.substring(7); // 去除前缀“bearer ”
    String payloadBase64 = jwt.substring(jwt.indexOf(".") + 1, jwt.lastIndexOf(".")); // 取出JWT中第二部分
    Base64.Decoder decoder = Base64.getDecoder();
    String payloadString;
    try {
        payloadString = new String(decoder.decode(payloadBase64), "UTF-8");
    } catch (Exception e) {
        return null;
    }
    JSONObject payloadJson = JSONObject.parseObject(payloadString);

    String userLogin = payloadJson.getString("user_name");
    if (null == userLogin) {
        return "system"; // 如果JWT中没有携带用户名,则应该是微服务见内部调用,此时将用户名强制设为system返回。
    } else {
        return userLogin;
    }
}
 
Example #10
Source File: MicroGatewayCommonUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get the tenant username password mapping from the enabled tenants
 *
 * @return Map<tenantUsername, Password> for all the tenants
 * @throws OnPremiseGatewayException if failed to retrieve the users
 */
public static Map<String, String> getMultiTenantUserMap() throws OnPremiseGatewayException {

    ArrayList multiTenantUsers = ConfigManager.getConfigurationDTO().getMulti_tenant_users();
    if (!multiTenantUsers.isEmpty()) {
        Map<String, String> tenantUserPasswordMap = new HashMap<>();
        for (Object tenantUserCredential : multiTenantUsers) {
            byte[] decodedUser = Base64.getDecoder().decode(tenantUserCredential.toString());
            String decodedUserString = new String(decodedUser);
            String[] userDetails = decodedUserString.split(":");
            tenantUserPasswordMap.put(userDetails[0], userDetails[1]);
        }
        return tenantUserPasswordMap;
    } else {
        throw new OnPremiseGatewayException("Multi Tenant User list is not defined in the on-premise-gateway.toml" +
                " file");
    }
}
 
Example #11
Source File: HwYunMsgSender.java    From WePush with MIT License 6 votes vote down vote up
/**
 * 构造X-WSSE参数值
 *
 * @param appKey
 * @param appSecret
 * @return
 */
static String buildWsseHeader(String appKey, String appSecret) {
    if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
        System.out.println("buildWsseHeader(): appKey or appSecret is null.");
        return null;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    String time = sdf.format(new Date()); //Created
    String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce

    byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
    String hexDigest = Hex.encodeHexString(passwordDigest);

    //如果JDK版本是1.8,请加载原生Base64类,并使用如下代码
    String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest
    //如果JDK版本低于1.8,请加载三方库提供Base64类,并使用如下代码
    //String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes(Charset.forName("utf-8"))); //PasswordDigest
    //若passwordDigestBase64Str中包含换行符,请执行如下代码进行修正
    //passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");

    return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
}
 
Example #12
Source File: EmbeddedAssetCreatorV2.java    From JglTF with MIT License 6 votes vote down vote up
/**
 * Convert the given {@link Buffer} into an embedded buffer, by replacing 
 * its URI with a data URI, if the URI is not already a data URI
 * 
 * @param gltfModel The {@link GltfModelV2}
 * @param index The index of the {@link Buffer}
 * @param buffer The {@link Buffer}
 */
private static void convertBufferToEmbedded(
    GltfModelV2 gltfModel, int index, Buffer buffer)
{
    String uriString = buffer.getUri();
    if (IO.isDataUriString(uriString))
    {
        return;
    }
    BufferModel bufferModel = gltfModel.getBufferModels().get(index);
    ByteBuffer bufferData = bufferModel.getBufferData();
    
    byte data[] = new byte[bufferData.capacity()];
    bufferData.slice().get(data);
    String encodedData = Base64.getEncoder().encodeToString(data);
    String dataUriString = 
        "data:application/gltf-buffer;base64," + encodedData;
    
    buffer.setUri(dataUriString);
}
 
Example #13
Source File: EncryptKitTest.java    From blade with Apache License 2.0 6 votes vote down vote up
@Test
public void encrypt3DES() throws Exception {
    assertTrue(
            Arrays.equals(
                    bytesResDES3,
                    EncryptKit.encrypt3DES(bytesDataDES3, bytesKeyDES3)
            )
    );
    assertEquals(
            res3DES,
            EncryptKit.encrypt3DES2HexString(bytesDataDES3, bytesKeyDES3)
    );
    assertTrue(
            Arrays.equals(
                    Base64.getEncoder().encode(bytesResDES3),
                    EncryptKit.encrypt3DES2Base64(bytesDataDES3, bytesKeyDES3)
            )
    );
}
 
Example #14
Source File: SecretUtils.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
public static void waitForCertToChange(String originalCert, String secretName) {
    LOGGER.info("Waiting for Secret {} certificate change", secretName);
    TestUtils.waitFor("Cert to be replaced", Constants.GLOBAL_POLL_INTERVAL, Constants.TIMEOUT_FOR_CLUSTER_STABLE, () -> {
        Secret secret = kubeClient().getSecret(secretName);
        if (secret != null && secret.getData() != null && secret.getData().containsKey("ca.crt")) {
            String currentCert = new String(Base64.getDecoder().decode(secret.getData().get("ca.crt")), StandardCharsets.US_ASCII);
            boolean changed = !originalCert.equals(currentCert);
            if (changed) {
                LOGGER.info("Certificate in Secret {} has changed, was {}, is now {}", secretName, originalCert, currentCert);
            }
            return changed;
        } else {
            return false;
        }
    });
}
 
Example #15
Source File: TalkClient.java    From Talk with MIT License 6 votes vote down vote up
private void sendMsg() {
	String curUsr = getUsrName(usrsListView.getSelectionModel().getSelectedItem());
	if(sendMsg.getText() != null && ! Pattern.matches("\\n*", sendMsg.getText())) {
		out.printf("[SENDTO %s]%s\n", curUsr, Base64.getEncoder().encodeToString(sendMsg.getText().getBytes(StandardCharsets.UTF_8)));
		out.flush();
		String Msg = String.format("[%s <%s>] %s\n",
				new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
				usrName, sendMsg.getText()
				);
		if(usrsMsg.get(curUsr) != null)
			usrsMsg.put(curUsr, usrsMsg.get(curUsr) + Msg);
		else
			usrsMsg.put(curUsr, Msg);
		message.appendText(Msg);
		sendMsg.setText("");
	} else {
		sendMsg.setText("");
	}
}
 
Example #16
Source File: SensitiveDataCryptoUtilsTest.java    From chvote-1-0 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * saving a key and retrieving it from a file should give the same object
 */
@Test
public void saveAndRetrieveSecretKey() throws IOException, ClassNotFoundException {
    SecretKey sK = SensitiveDataCryptoUtils.buildSecretKey(SECRETKEY_LENGTH, configuration.getPbkdf2Algorithm());
    String secretKeyFingerPrint = Base64.getEncoder().encodeToString(sK.getEncoded());

    File keyFile = File.createTempFile("keyfile", "key");
    keyFile.deleteOnExit();

    saveInFile(keyFile, sK);

    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(keyFile));
    SecretKey readKey = (SecretKey) ois.readObject();
    ois.close();

    assertTrue(readKey.getEncoded().length * 8 == SECRETKEY_LENGTH);
    assertTrue(Base64.getEncoder().encodeToString(readKey.getEncoded()).equals(secretKeyFingerPrint));
}
 
Example #17
Source File: SolrITInitializer.java    From SearchServices with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
    throws IOException, ServletException
{
    //Parse the basic auth filter
    String auth = ((HttpServletRequest)request).getHeader("Authorization");
    if(auth != null)
    {
        auth = auth.replace("Basic ", "");
        byte[] bytes = Base64.getDecoder().decode(auth);
        String decodedBytes = new String(bytes);
        String[] pair = decodedBytes.split(":");
        String user = pair[0];
        String password = pair[1];
        //Just look for the hard coded user and password.
        if (user.equals("test") && password.equals("pass"))
        {
            filterChain.doFilter(request, response);
        }
        else
        {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    }
    else
    {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN);
    }
}
 
Example #18
Source File: SignedUrls.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  Calendar cal = Calendar.getInstance();
  cal.setTime(new Date());
  cal.add(Calendar.DATE, 1);
  Date tomorrow = cal.getTime();

  //read the key as a base 64 url-safe encoded string, then convert to byte array
  final String keyPath = "/path/to/key";
  String base64String = new String(Files.readAllBytes(Paths.get(keyPath)));
  byte[] keyBytes = Base64.getUrlDecoder().decode(base64String);

  String result = signUrl("http://example.com/", keyBytes, "YOUR-KEY-NAME", tomorrow);
  System.out.println(result);
}
 
Example #19
Source File: LTI13JwtUtil.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public static String rawJwtBody(String encoded) {
	String[] parts = encoded.split("\\.");
	if (parts.length != 2 && parts.length != 3) {
		return null;
	}
	byte[] bytes = Base64.getUrlDecoder().decode(parts[1]);
	return new String(bytes);
}
 
Example #20
Source File: TestBase64.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static void testDecodeIgnoredAfterPadding() throws Throwable {
    for (byte nonBase64 : new byte[] {'#', '(', '!', '\\', '-', '_', '\n', '\r'}) {
        byte[][] src = new byte[][] {
            "A".getBytes("ascii"),
            "AB".getBytes("ascii"),
            "ABC".getBytes("ascii"),
            "ABCD".getBytes("ascii"),
            "ABCDE".getBytes("ascii")
        };
        Base64.Encoder encM = Base64.getMimeEncoder();
        Base64.Decoder decM = Base64.getMimeDecoder();
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        for (int i = 0; i < src.length; i++) {
            // decode(byte[])
            byte[] encoded = encM.encode(src[i]);
            encoded = Arrays.copyOf(encoded, encoded.length + 1);
            encoded[encoded.length - 1] = nonBase64;
            checkEqual(decM.decode(encoded), src[i], "Non-base64 char is not ignored");
            byte[] decoded = new byte[src[i].length];
            decM.decode(encoded, decoded);
            checkEqual(decoded, src[i], "Non-base64 char is not ignored");

            try {
                dec.decode(encoded);
                throw new RuntimeException("No IAE for non-base64 char");
            } catch (IllegalArgumentException iae) {}
        }
    }
}
 
Example #21
Source File: GnochiQueryTest.java    From hawkular-alerts with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void searchRersources() throws Exception {
    String searchUrl = "http://localhost:8041/v1/search/resource/generic";
    String userPassword = "admin:admin";
    String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userPassword.getBytes()));
    String resourceQuery = "{" +
                                "\"like\":{" +
                                    "\"type\":\"c%\"" +
                                "}" +
                            "}";

    URL url = new URL(searchUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Authorization", basicAuth);
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    OutputStream os = conn.getOutputStream();
    os.write(resourceQuery.getBytes());
    os.flush();
    os.close();

    List resources = JsonUtil.getMapper().readValue(conn.getInputStream(), List.class);
    log.infof("resources %s", resources);

    conn.disconnect();
}
 
Example #22
Source File: RawArgument.java    From NCANode with MIT License 5 votes vote down vote up
@Override
public void validate() throws InvalidArgumentException {
    String r = (String)params.get("raw");

    if (r == null) {
        if (required) {
            throw new InvalidArgumentException("Argument 'raw' is required");
        } else {
            return;
        }
    }

    raw = Base64.getDecoder().decode(r);
}
 
Example #23
Source File: DefaultAVUserCookieSign.java    From java-unified-sdk with Apache License 2.0 5 votes vote down vote up
private String getUserCookieValue(AVUser user) {
  Map<String, String> userInfo = new HashMap<String, String>();
  userInfo.put(UID, user.getObjectId());
  userInfo.put(SESSION_TOKEN, user.getSessionToken());
  String userInfoStr = JSON.toJSONString(userInfo);
  String cookieValue = Base64.getEncoder().encodeToString(userInfoStr.getBytes());
  return cookieValue;
}
 
Example #24
Source File: DefaultCookieSerializer.java    From spring-session with Apache License 2.0 5 votes vote down vote up
/**
 * Decode the value using Base64.
 * @param base64Value the Base64 String to decode
 * @return the Base64 decoded value
 * @since 1.2.2
 */
private String base64Decode(String base64Value) {
	try {
		byte[] decodedCookieBytes = Base64.getDecoder().decode(base64Value);
		return new String(decodedCookieBytes);
	}
	catch (Exception ex) {
		logger.debug("Unable to Base64 decode value: " + base64Value);
		return null;
	}
}
 
Example #25
Source File: TestBase64Golden.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    test0(Base64Type.BASIC, Base64.getEncoder(), Base64.getDecoder(),
          "plain.txt", "baseEncode.txt");

    test0(Base64Type.URLSAFE, Base64.getUrlEncoder(), Base64.getUrlDecoder(),
          "plain.txt", "urlEncode.txt");

    test0(Base64Type.MIME, Base64.getMimeEncoder(), Base64.getMimeDecoder(),
          "plain.txt", "mimeEncode.txt");
    test1();
}
 
Example #26
Source File: BasicAuthFilter.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean requireRole(String roleName, HttpServletRequest request, HttpServletResponse response) {
    String authHeader = request.getHeader(AUTHORIZATION_HEADER);
    if (authHeader == null || !authHeader.startsWith(BASIC_PREFIX)) {
        LOGGER.debug("Rejecting request: no basic auth header.");
        throwAuthRequired(response);
        return false;
    }

    String userPassBase64 = authHeader.substring(BASIC_PREFIX.length());
    String userPassDecoded = new String(Base64.getDecoder().decode(userPassBase64), StringHelper.UTF8);
    if (!userPassDecoded.contains(":")) {
        LOGGER.debug("Rejecting request: no username:password in basic auth header.");
        throwAuthRequired(response);
        return false;
    }

    String[] split = userPassDecoded.split(":", 2);
    String userName = split[0];
    String userPass = split[1];
    if (!databaseHandler.userHasRole(userName, userPass, roleName)) {
        LOGGER.debug("Rejecting request: User {} does not have role {}.", userName, roleName);
        throwAuthRequired(response);
        return false;
    }
    LOGGER.debug("Accepting request: User {} has role {}.", userName, roleName);
    return true;
}
 
Example #27
Source File: Base64UrlDecoder.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Override
protected String processInternal(String value) throws IOException {
    EncodeDecodeOptions encDecOpts =
            Control.getSingleton()
                    .getExtensionLoader()
                    .getExtension(ExtensionEncoder.class)
                    .getOptions();
    return new String(Base64.getUrlDecoder().decode(value), encDecOpts.getBase64Charset());
}
 
Example #28
Source File: AgentRegistrationControllerIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
private String token(String uuid, String tokenGenerationKey) {
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(tokenGenerationKey.getBytes(), "HmacSHA256");
        mac.init(secretKey);
        return Base64.getEncoder().encodeToString(mac.doFinal(uuid.getBytes()));
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new RuntimeException(e);
    }
}
 
Example #29
Source File: VarbinaryFunctions.java    From presto with Apache License 2.0 5 votes vote down vote up
@Description("Decode URL safe base64 encoded binary data")
@ScalarFunction("from_base64url")
@SqlType(StandardTypes.VARBINARY)
public static Slice fromBase64UrlVarbinary(@SqlType(StandardTypes.VARBINARY) Slice slice)
{
    try {
        if (slice.hasByteArray()) {
            return Slices.wrappedBuffer(Base64.getUrlDecoder().decode(slice.toByteBuffer()));
        }
        return Slices.wrappedBuffer(Base64.getUrlDecoder().decode(slice.getBytes()));
    }
    catch (IllegalArgumentException e) {
        throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e);
    }
}
 
Example #30
Source File: DeflatingWrapper.java    From milkman with MIT License 5 votes vote down vote up
private static byte[] inflate(String data) throws Exception {
	byte[] compressed = Base64.getDecoder().decode(data);
	ByteArrayInputStream in = new ByteArrayInputStream(compressed);
	InflaterInputStream inf = new InflaterInputStream(in, new Inflater(true));
	byte[] byteArray = IOUtils.toByteArray(inf);
	return byteArray;
}