Java Examples for java.util.Base64

The following java examples will help you to understand the usage of java.util.Base64. These source code samples are taken from different open source projects.

Example 1
Project: edit-2015-master  File: ItemId.java View source code
public static String generate() {
    UUID uuid = UUID.randomUUID();
    ByteBuffer uuidByteBuffer = ByteBuffer.wrap(new byte[UUID_BYTE_LENGTH]);
    uuidByteBuffer.putLong(uuid.getMostSignificantBits());
    uuidByteBuffer.putLong(uuid.getLeastSignificantBits());
    return Base64.getUrlEncoder().encodeToString(uuidByteBuffer.array());
}
Example 2
Project: stash-token-auth-master  File: Encrypter.java View source code
public String encrypt(String value) throws EncryptionException {
    try {
        byte[] utf8 = value.getBytes("UTF8");
        byte[] enc = ecipher.doFinal(utf8);
        return new String(Base64.getEncoder().encode(enc));
    } catch (UnsupportedEncodingExceptionBadPaddingException | IllegalBlockSizeException |  e) {
        throw new EncryptionException("Could not encrypt string", e);
    }
}
Example 3
Project: Zxing-master  File: Java8Base64Decoder.java View source code
@Override
byte[] decode(String s) {
    try {
        Object decoder = Class.forName("java.util.Base64").getMethod("getDecoder").invoke(null);
        return (byte[]) Class.forName("java.util.Base64$Decoder").getMethod("decode", String.class).invoke(decoder, s);
    } catch (IllegalAccessExceptionNoSuchMethodException | ClassNotFoundException |  e) {
        throw new IllegalStateException(e);
    } catch (InvocationTargetException ite) {
        throw new IllegalStateException(ite.getCause());
    }
}
Example 4
Project: itol-master  File: PasswordEncryption.java View source code
private static byte[] stringToBytes(String s) throws UnsupportedEncodingException {
    // Previous version used
    // com.sun.org.apache.xml.internal.security.utils.Base64.
    // This class adds \n after each 76 chars, which disturbs the
    // java.util.Base64.
    StringBuilder sbuf = new StringBuilder(s.length());
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (!Character.isWhitespace(c)) {
            sbuf.append(c);
        }
    }
    return java.util.Base64.getDecoder().decode(sbuf.toString());
}
Example 5
Project: TOYS-master  File: JCATest.java View source code
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException {
    KeyGenerator des = KeyGenerator.getInstance("DES");
    des.init(56);
    SecretKey secretKey = des.generateKey();
    Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
    hmacSHA256.init(secretKey);
    byte[] bytes = hmacSHA256.doFinal("Hello Crypto".getBytes());
    System.out.println(Base64.getEncoder().encodeToString(bytes));
    System.out.println(new String(Base64.getEncoder().encode(bytes)));
    System.out.println(hmacSHA256);
    MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
    System.out.println(sha256);
}
Example 6
Project: XCoLab-master  File: SHA1PasswordEncryptor.java View source code
public String doEncrypt(String algorithm, String plainTextPassword) {
    if (!ALGORITHM_NAME.equals(algorithm)) {
        throw new UnsupportedDigestAlgorithmException("This encryptor does not support the algorithm" + algorithm);
    }
    try {
        MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
        byte[] secretKeyBytes = sha1Digest.digest(plainTextPassword.getBytes(StandardCharsets.UTF_8));
        ByteBuffer byteBuffer = ByteBuffer.allocate(secretKeyBytes.length);
        byteBuffer.put(secretKeyBytes);
        return Base64.getEncoder().encodeToString(byteBuffer.array());
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Password encryption algorithm not found", e);
    }
}
Example 7
Project: browserprint-master  File: SampleIDs.java View source code
/**
	 * Decrypt an integer from a String.
	 * 
	 * @param encrypted
	 * @param context
	 * @return
	 * @throws ServletException
	 */
private static Integer decryptInteger(String encrypted, ServletContext context) throws ServletException {
    String encryptedParts[] = encrypted.split("\\|");
    if (encryptedParts.length != 3) {
        throw new ServletException("Invalid encrypted string.");
    }
    /* Get password. */
    String password = context.getInitParameter("SampleSetIDEncryptionPassword");
    /* Extract the encrypted data, initialisation vector, and salt from the cookie. */
    Decoder decoder = Base64.getDecoder();
    byte ciphertext[] = decoder.decode(encryptedParts[0]);
    byte iv[] = decoder.decode(encryptedParts[1]);
    byte salt[] = decoder.decode(encryptedParts[2]);
    byte plainbytes[];
    try {
        /* Derive the key, given password and salt. */
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
        /* Decrypt the message, given derived key and initialization vector. */
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
        plainbytes = cipher.doFinal(ciphertext);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    return ByteBuffer.wrap(plainbytes).asIntBuffer().get();
}
Example 8
Project: vertx-shell-master  File: HttpTermOptionsConverter.java View source code
public static void fromJson(JsonObject json, HttpTermOptions obj) {
    if (json.getValue("charset") instanceof String) {
        obj.setCharset((String) json.getValue("charset"));
    }
    if (json.getValue("intputrc") instanceof String) {
        obj.setIntputrc((String) json.getValue("intputrc"));
    }
    if (json.getValue("shellHtmlResource") instanceof String) {
        obj.setShellHtmlResource(io.vertx.core.buffer.Buffer.buffer(java.util.Base64.getDecoder().decode((String) json.getValue("shellHtmlResource"))));
    }
    if (json.getValue("sockJSHandlerOptions") instanceof JsonObject) {
        obj.setSockJSHandlerOptions(new io.vertx.ext.web.handler.sockjs.SockJSHandlerOptions((JsonObject) json.getValue("sockJSHandlerOptions")));
    }
    if (json.getValue("sockJSPath") instanceof String) {
        obj.setSockJSPath((String) json.getValue("sockJSPath"));
    }
    if (json.getValue("termJsResource") instanceof String) {
        obj.setTermJsResource(io.vertx.core.buffer.Buffer.buffer(java.util.Base64.getDecoder().decode((String) json.getValue("termJsResource"))));
    }
    if (json.getValue("vertsShellJsResource") instanceof String) {
        obj.setVertsShellJsResource(io.vertx.core.buffer.Buffer.buffer(java.util.Base64.getDecoder().decode((String) json.getValue("vertsShellJsResource"))));
    }
}
Example 9
Project: actor-platform-master  File: Main.java View source code
public static void main(String[] args) throws DigestException, NoSuchAlgorithmException, IOException {
    SecureRandom secureRandom = new SecureRandom();
    if (!new File("keys").exists()) {
        new File("keys").mkdir();
    }
    for (int i = 0; i < 4; i++) {
        File pubFile = new File("keys/actor-key-" + i + ".pub");
        File keyFile = new File("keys/actor-key-" + i + ".key");
        if (pubFile.exists() && keyFile.exists()) {
            System.out.println("Key #" + i + " exists. Skipping...");
            continue;
        }
        Curve25519KeyPair keyPair = Curve25519.keyGen(secureRandom.generateSeed(64));
        FileUtils.writeByteArrayToFile(pubFile, keyPair.getPublicKey());
        FileUtils.writeByteArrayToFile(keyFile, keyPair.getPrivateKey());
    }
    System.out.println("Shared Secret: " + Base64.getEncoder().encodeToString(secureRandom.generateSeed(64)));
}
Example 10
Project: bennu-master  File: CASLoginProvider.java View source code
@Override
public void showLogin(HttpServletRequest request, HttpServletResponse response, String callback) throws IOException, ServletException {
    if (Strings.isNullOrEmpty(callback)) {
        callback = CASClientConfiguration.getConfiguration().casServiceUrl();
    }
    callback = Base64.getUrlEncoder().encodeToString(callback.getBytes(StandardCharsets.UTF_8));
    response.sendRedirect(CASClientConfiguration.getConfiguration().casServerUrl() + "/login?service=" + escaper.escape(CoreConfiguration.getConfiguration().applicationUrl() + "/api/cas-client/login/" + callback));
}
Example 11
Project: blynk-server-master  File: SHA256Util.java View source code
public static String makeHash(String password, String salt) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes("UTF-8"));
        byte byteData[] = md.digest(makeHash(salt.toLowerCase()));
        return Base64.getEncoder().encodeToString(byteData);
    } catch (NoSuchAlgorithmExceptionUnsupportedEncodingException |  e) {
        log.error("Unable to make hash for pass. No hashing.", e);
    }
    return password;
}
Example 12
Project: burp-hash-master  File: HashRecord.java View source code
//TODO: normalize h:e:x, 0xFF
String getNormalizedRecord() {
    if (encodingType.equals(EncodingType.Base64)) {
        return Utilities.byteArrayToHex(Base64.getDecoder().decode(record)).toLowerCase();
    }
    if (encodingType.equals(EncodingType.StringBase64)) {
        return new String(Base64.getDecoder().decode(record)).toLowerCase();
    }
    return record.toLowerCase();
}
Example 13
Project: dcache-master  File: AuthorizedKeyParser.java View source code
/**
     *
     * @param Takes
     *            a line of a key file - keyLine
     * @return It then returns a {@link PublicKey} representation of either the
     *         RSA or DSA key.
     * @throws NoSuchAlgorithmException
     *             if algorithm is not known (known are RSA, DSA)
     * @throws InvalidKeySpecException
     */
public PublicKey decodePublicKey(String keyLine) throws IllegalArgumentException, InvalidKeySpecException, NoSuchAlgorithmException {
    bytes = null;
    pos = 0;
    // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes
    for (String part : keyLine.split(" ")) {
        if (part.startsWith("AAAA")) {
            bytes = Base64.getDecoder().decode(part);
            break;
        }
    }
    if (bytes == null) {
        throw new IllegalArgumentException("no Base64 part to decode");
    }
    String type = decodeType();
    switch(type) {
        case "ssh-rsa":
            {
                BigInteger e = decodeBigInt();
                BigInteger m = decodeBigInt();
                RSAPublicKeySpec spec = new RSAPublicKeySpec(m, e);
                return KeyFactory.getInstance("RSA").generatePublic(spec);
            }
        case "ssh-dss":
            {
                BigInteger p = decodeBigInt();
                BigInteger q = decodeBigInt();
                BigInteger g = decodeBigInt();
                BigInteger y = decodeBigInt();
                DSAPublicKeySpec spec = new DSAPublicKeySpec(y, p, q, g);
                return KeyFactory.getInstance("DSA").generatePublic(spec);
            }
        default:
            throw new IllegalArgumentException("unknown type " + type);
    }
}
Example 14
Project: GamificationEngine-Kinben-master  File: SecurityTools.java View source code
/**
	 * Encodes a password to a encoded password with SHA 512.
	 * @param plainText
	 * 			The original password.
	 * @return An encoded password.
	 */
//Based on http://stackoverflow.com/questions/3103652/hash-string-via-sha-256-in-java
public static String encryptWithSHA512(String plainText) {
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-512");
        md.update(plainText.getBytes("UTF-8"));
        byte[] hashedPW = md.digest();
        String encoded = Base64.getEncoder().encodeToString(hashedPW);
        return encoded;
    } catch (NoSuchAlgorithmExceptionUnsupportedEncodingException |  e) {
        throw new ApiError(Response.Status.FORBIDDEN, "The password cannot be hashed.");
    }
}
Example 15
Project: JAVA-KOANS-master  File: AboutBase64.java View source code
@Koan
public void base64Encoding() {
    try {
        // Encode the plainText
        // This uses the basic Base64 encoding scheme but there are corresponding
        // getMimeEncoder and getUrlEncoder methods available if you require a
        // different format/Base64 Alphabet 
        assertEquals(encodedText, Base64.getEncoder().encodeToString(__.getBytes("utf-8")));
    } catch (UnsupportedEncodingException ex) {
    }
}
Example 16
Project: keycloak-master  File: KeyUtils.java View source code
public static PublicKey publicKeyFromString(String key) {
    try {
        KeyFactory kf = KeyFactory.getInstance("RSA");
        byte[] encoded = Base64.getDecoder().decode(key);
        return kf.generatePublic(new X509EncodedKeySpec(encoded));
    } catch (NoSuchAlgorithmExceptionInvalidKeySpecException |  e) {
        throw new RuntimeException(e);
    }
}
Example 17
Project: koa-master  File: AboutBase64.java View source code
@Koan
public void base64Encoding() {
    try {
        // Encode the plainText
        // This uses the basic Base64 encoding scheme but there are corresponding
        // getMimeEncoder and getUrlEncoder methods available if you require a
        // different format/Base64 Alphabet 
        assertEquals(encodedText, Base64.getEncoder().encodeToString(__.getBytes("utf-8")));
    } catch (UnsupportedEncodingException ex) {
    }
}
Example 18
Project: oerworldmap-master  File: ResourceIndexTest.java View source code
private String getAuthString() {
    Configuration conf = new Configuration(ConfigFactory.parseFile(new File("conf/test.conf")).resolve());
    String email = conf.getString("admin.user");
    String pass = conf.getString("admin.pass");
    String authString = email.concat(":").concat(pass);
    return Base64.getEncoder().encodeToString(authString.getBytes());
}
Example 19
Project: OpenConext-teams-master  File: VootApiSecurityFilter.java View source code
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String requestURI = request.getRequestURI();
    if (requestURI.contains(LoginInterceptor.API_VOOT_URL)) {
        String header = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (header == null || !header.startsWith("Basic ")) {
            throw new BadCredentialsException("No or incorrect Authorization header for " + requestURI);
        }
        byte[] base64Token = header.substring(6).getBytes(Charset.defaultCharset());
        byte[] decoded = Base64.getDecoder().decode(base64Token);
        String token = new String(decoded, Charset.defaultCharset());
        int delim = token.indexOf(":");
        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token for " + requestURI);
        }
        if (!user.equals(token.substring(0, delim)) || !password.equals(token.substring(delim + 1))) {
            throw new BadCredentialsException("Invalid username / password for " + requestURI);
        }
    }
    return true;
}
Example 20
Project: openjdk8-jdk-master  File: UnstructuredName.java View source code
public static void main(String[] args) throws Exception {
    PKCS10 req = new PKCS10(Base64.getMimeDecoder().decode(csrStr));
    // If PKCS9Attribute did not accept the PrintableString ASN.1 tag,
    // this would fail with an IOException
    Object attr = req.getAttributes().getAttribute("1.2.840.113549.1.9.2");
    // Check that the attribute exists
    if (attr == null) {
        throw new Exception("Attribute should not be null.");
    }
    System.out.println("Test passed.");
}
Example 21
Project: sample-skeleton-projects-master  File: MapImageUtils.java View source code
public static final String getImageStream(String latitude, String longitude) throws IOException {
    String urlString = URL + "center=" + latitude + "," + longitude;
    urlString += "&key=" + key;
    urlString += "&zoom=12&size=400x400";
    System.out.println(urlString);
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.close();
    InputStream iSteamReader = connection.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(iSteamReader));
    StringBuilder response = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        response.append(line);
        response.append('\r');
    }
    reader.close();
    return Base64.getEncoder().encodeToString(response.toString().getBytes("utf-8"));
}
Example 22
Project: SocialKademlia-master  File: StringCompressor.java View source code
public static String decompress(final String input) throws IOException {
    byte[] inputBytes = Base64.getDecoder().decode(input);
    try (GZIPInputStream gzipper = new GZIPInputStream(new ByteArrayInputStream(inputBytes));
        BufferedReader bf = new BufferedReader(new InputStreamReader(gzipper))) {
        StringBuilder data = new StringBuilder();
        String line;
        while ((line = bf.readLine()) != null) {
            data.append(line);
        }
        return data.toString();
    }
}
Example 23
Project: vert.x-master  File: VertxHttp2ClientUpgradeCodec.java View source code
@Override
public Collection<CharSequence> setUpgradeHeaders(ChannelHandlerContext ctx, HttpRequest upgradeRequest) {
    Http2Settings nettySettings = new Http2Settings();
    HttpUtils.fromVertxInitialSettings(false, settings, nettySettings);
    Buffer buf = Buffer.buffer();
    for (CharObjectMap.PrimitiveEntry<Long> entry : nettySettings.entries()) {
        buf.appendUnsignedShort(entry.key());
        buf.appendUnsignedInt(entry.value());
    }
    String encodedSettings = new String(java.util.Base64.getUrlEncoder().encode(buf.getBytes()), UTF_8);
    upgradeRequest.headers().set(HTTP_UPGRADE_SETTINGS_HEADER, encodedSettings);
    return UPGRADE_HEADERS;
}
Example 24
Project: armeria-master  File: BasicTokenExtractor.java View source code
@Override
public BasicToken apply(HttpHeaders headers) {
    String authorization = headers.get(HttpHeaderNames.AUTHORIZATION);
    if (Strings.isNullOrEmpty(authorization)) {
        return null;
    }
    Matcher matcher = AUTHORIZATION_HEADER_PATTERN.matcher(authorization);
    if (!matcher.matches()) {
        logger.warn("Invalid authorization header: {}", authorization);
        return null;
    }
    String base64 = matcher.group("encoded");
    byte[] decoded;
    try {
        decoded = BASE64_DECODER.decode(base64);
    } catch (IllegalArgumentException e) {
        logger.warn("Base64 decoding failed: {}", base64);
        return null;
    }
    String credential = new String(decoded, StandardCharsets.UTF_8);
    int sep = credential.indexOf(':');
    if (sep == -1) {
        logger.warn("Invalid credential: {}", credential);
        return null;
    }
    String username = credential.substring(0, sep);
    String password = credential.substring(sep + 1);
    return BasicToken.of(username, password);
}
Example 25
Project: gocd-master  File: GoCipher.java View source code
public String cipher(byte[] key, String plainText) throws InvalidCipherTextException {
    PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESEngine()));
    KeyParameter keyParameter = new KeyParameter(Hex.decode(key));
    cipher.init(true, keyParameter);
    byte[] plainTextBytes = plainText.getBytes();
    byte[] cipherTextBytes = new byte[cipher.getOutputSize(plainTextBytes.length)];
    int outputLength = cipher.processBytes(plainTextBytes, 0, plainTextBytes.length, cipherTextBytes, 0);
    cipher.doFinal(cipherTextBytes, outputLength);
    return java.util.Base64.getEncoder().encodeToString(cipherTextBytes).trim();
}
Example 26
Project: openjdk-master  File: ClientHelloChromeInterOp.java View source code
@Override
protected byte[] createClientHelloMessage() {
    byte[] bytes = Base64.getMimeDecoder().decode(ClientHelloMsg);
    // Dump the hex codes of the ClientHello message so that developers
    // can easily check whether the message is captured correct or not.
    HexDumpEncoder dump = new HexDumpEncoder();
    System.out.println("The ClientHello message used");
    try {
        dump.encodeBuffer(bytes, System.out);
    } catch (Exception e) {
    }
    return bytes;
}
Example 27
Project: rapidpm-microservice-master  File: LogEventIndexTest.java View source code
@Test
public void test001() throws Exception {
    final Gson gson = new Gson();
    final Encoder encoder = Base64.getEncoder();
    final LoggerEvent loggerEvent = new LoggerEvent().level("lev5").message("hello").timestamp(LocalDateTime.now());
    final String logeEventAsJson = gson.toJson(loggerEvent);
    final byte[] encodedI01 = encoder.encode(logeEventAsJson.getBytes());
    final Client client = ClientBuilder.newClient();
    final String generateBasicReqURL = generateBasicReqURL(LoggerEventREST.class);
    System.out.println("generateBasicReqURL = " + generateBasicReqURL);
    final WebTarget webTarget = client.target(generateBasicReqURL + "/" + LoggerEventREST.QUERY).queryParam(LoggerEventREST.QP_QUERY, "hello");
    final String q01 = webTarget.request().get(String.class);
    System.out.println("q01 = " + q01);
    final List<LogEvent> q01List = Arrays.asList(gson.fromJson(q01, LoggerEventREST.LOGGER_EVENT_LIST_TYPE));
    Assert.assertNotNull(q01List);
    Assert.assertTrue(q01List.isEmpty());
    final String i01 = client.target(generateBasicReqURL + "/" + LoggerEventREST.INSERT).queryParam(LoggerEventREST.QP_LOGGER_EVENT, new String(encodedI01)).request().get(String.class);
    System.out.println("i01 = " + i01);
    Assert.assertEquals(LoggerEventREST.OK, i01);
    final String q02 = webTarget.request().get(String.class);
    System.out.println("q02 = " + q02);
    final List<LogEvent> q02List = Arrays.asList(gson.fromJson(q02, LoggerEventREST.LOGGER_EVENT_LIST_TYPE));
    Assert.assertNotNull(q02List);
    Assert.assertFalse(q02List.isEmpty());
    Assert.assertEquals(1, q02List.size());
    client.close();
}
Example 28
Project: aerogear-unifiedpush-server-master  File: CertificateBlobToBase64.java View source code
@Override
public SqlStatement[] generateStatements(Database database) throws CustomChangeException {
    List<SqlStatement> statements = new ArrayList<>();
    Connection conn = ((JdbcConnection) (database.getConnection())).getWrappedConnection();
    try {
        conn.setAutoCommit(false);
        ResultSet resultSet = conn.createStatement().executeQuery("SELECT id, certificate from ios_variant");
        while (resultSet.next()) {
            String id = resultSet.getString("id");
            Blob blob = resultSet.getBlob("certificate");
            InputStream certificate = blob.getBinaryStream();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            int bytesRead = -1;
            byte[] buffer = new byte[1024];
            while ((bytesRead = certificate.read(buffer)) != -1) {
                stream.write(buffer, 0, bytesRead);
            }
            final String certificateData = Base64.getEncoder().encodeToString(stream.toByteArray());
            UpdateStatement updateStatement = new UpdateStatement(null, null, "ios_variant").addNewColumnValue("cert_data", certificateData).setWhereClause("id='" + id + "'");
            statements.add(updateStatement);
        }
        conn.commit();
        if (!statements.isEmpty()) {
            confirmationMessage = "updated certificate data successfully";
        }
        return statements.toArray(new SqlStatement[statements.size()]);
    } catch (Exception e) {
        throw new CustomChangeException("Failed to migrate certificate data");
    }
}
Example 29
Project: any-video-master  File: AesUtils.java View source code
/**
   * 使用AES 算法 加密,默认模� AES/CBC/PKCS5Padding
   */
public static String encrypt(String str, String iv, String pass) {
    try {
        Cipher cipher = Cipher.getInstance(TYPE);
        SecretKey secretKey = new SecretKeySpec(pass.getBytes(), KEY_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv.getBytes()));
        byte[] encrypt = cipher.doFinal(str.getBytes());
        return Base64.getEncoder().encodeToString(encrypt);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }
    return null;
}
Example 30
Project: brave-master  File: ScribeReceiver.java View source code
@Override
public ResultCode Log(final List<LogEntry> messages) {
    for (final LogEntry logEntry : messages) {
        final byte[] decodedSpan = Base64.getDecoder().decode(logEntry.getMessage());
        final Span span = SpanCodec.THRIFT.readSpan(decodedSpan);
        spans.add(span);
    }
    if (delayMs > 0) {
        try {
            Thread.sleep(delayMs);
        } catch (final InterruptedException e) {
            LOGGER.log(Level.SEVERE, "Interrupted.", e);
        }
    }
    return ResultCode.OK;
}
Example 31
Project: Density-master  File: SerializePreferenceStore.java View source code
private static String serialize(Serializable obj) throws IOException {
    ObjectOutput out = null;
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        out = new ObjectOutputStream(bos);
        out.writeObject(obj);
        return Base64.getEncoder().encodeToString(bos.toByteArray());
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ex) {
        }
    }
}
Example 32
Project: elasticsearch-readonlyrest-plugin-master  File: RequestContextMock.java View source code
public static RequestContext mockedRequestContext(String user, String pass) {
    RequestContext mock = mock(RequestContext.class);
    when(mock.getHeaders()).thenReturn(Maps.newHashMap(ImmutableMap.<String, String>builder().put("Authorization", "Basic " + Base64.getEncoder().encodeToString((user + ":" + pass).getBytes())).build()));
    when(mock.getLoggedInUser()).thenReturn(Optional.of(new LoggedUser(user)));
    return mock;
}
Example 33
Project: infinispan-master  File: BasicAuthenticator.java View source code
@Override
public SecurityContext authenticate(ChannelHandlerContext ctx, HttpRequest request, HttpResponse response) throws IOException {
    List<String> headers = request.getHttpHeaders().getRequestHeader(HttpHeaderNames.AUTHORIZATION);
    if (!headers.isEmpty()) {
        String auth = headers.get(0);
        if (auth.length() > 5) {
            String type = auth.substring(0, 5);
            type = type.toLowerCase();
            if ("basic".equals(type)) {
                String cookie = auth.substring(6);
                cookie = new String(Base64.getDecoder().decode(cookie.getBytes()));
                String[] split = cookie.split(":");
                try {
                    Principal user = domain.authenticate(split[0], split[1]);
                    return new NettySecurityContext(user, domain, "BASIC", secure);
                } catch (SecurityException e) {
                    sendUnauthorizedResponse(response);
                    return null;
                }
            } else {
                sendUnauthorizedResponse(response);
                return null;
            }
        }
    }
    sendUnauthorizedResponse(response);
    return null;
}
Example 34
Project: java-docs-samples-master  File: AuthInfoServlet.java View source code
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String encodedInfo = req.getHeader("X-Endpoint-API-UserInfo");
    if (encodedInfo == null || encodedInfo == "") {
        JsonObject anon = new JsonObject();
        anon.addProperty("id", "anonymous");
        new Gson().toJson(anon, resp.getWriter());
        return;
    }
    try {
        byte[] authInfo = Base64.getDecoder().decode(encodedInfo);
        resp.getOutputStream().write(authInfo);
    } catch (IllegalArgumentException iae) {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        JsonObject error = new JsonObject();
        error.addProperty("code", HttpServletResponse.SC_BAD_REQUEST);
        error.addProperty("message", "Could not decode auth info.");
        new Gson().toJson(error, resp.getWriter());
    }
}
Example 35
Project: Java-Gitolite-Manager-master  File: KeyGenerator.java View source code
/**
	 * Encode PublicKey (DSA or RSA encoded) to authorized_keys like string
	 *
	 * @param publicKey
	 *            DSA or RSA encoded
	 * @return authorized_keys like string
	 * @throws IOException
	 *             if an I/O error occurs.
	 */
public static String encodePublicKey(final PublicKey publicKey) throws IOException {
    if (publicKey.getAlgorithm().equals("RSA")) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(byteOs);
        dos.writeInt("ssh-rsa".getBytes().length);
        dos.write("ssh-rsa".getBytes());
        dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length);
        dos.write(rsaPublicKey.getPublicExponent().toByteArray());
        dos.writeInt(rsaPublicKey.getModulus().toByteArray().length);
        dos.write(rsaPublicKey.getModulus().toByteArray());
        return "ssh-rsa " + new String(Base64.getEncoder().encode(byteOs.toByteArray()));
    } else {
        throw new IllegalArgumentException("Unknown public key encoding: " + publicKey.getAlgorithm());
    }
}
Example 36
Project: java8-playground-master  File: Hashes3.java View source code
public static void main(String[] args) {
    LongAdder adder = new LongAdder();
    ForkJoinPool fjp = new ForkJoinPool(3);
    measure(() -> spliteratorStream().parallel().peek( s -> adder.increment()).filter( s -> md5(s).startsWith("0000000")).findAny().ifPresent( b -> System.out.println(Base64.getEncoder().encodeToString(b) + " " + md5(b))));
    System.out.println(adder);
}
Example 37
Project: JScanner-master  File: ScanHandler.java View source code
/**
	 * Gets the archive posted to the "/scan" directory.
	 * 
	 * @return The archive posed to the "/scan" directory
	 */
private Archive getArchive() {
    try {
        byte[] data = Base64.getDecoder().decode(postData.get("base64").get(0));
        String suffix = Magic.getMagicMatch(data).getMimeType().equalsIgnoreCase("application/zip") ? "jar" : "class";
        File file = File.createTempFile(new Random().nextInt() + "", suffix);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(data);
        fos.close();
        return suffix.equalsIgnoreCase("jar") ? new JavaArchive(new JarFile(file)) : new ClassFile(file);
    } catch (MagicParseException e) {
        e.printStackTrace();
    } catch (MagicMatchNotFoundException e) {
        e.printStackTrace();
    } catch (MagicException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 38
Project: jwt4j-master  File: JWTDecoder.java View source code
private void checkSignature(String[] tokenParts) {
    try {
        final Mac mac = Mac.getInstance(algorithm.name);
        mac.init(new SecretKeySpec(secret, algorithm.name));
        final byte[] headerAndPayload = new StringJoiner(".").add(tokenParts[0]).add(tokenParts[1]).toString().getBytes();
        final byte[] signature = mac.doFinal(headerAndPayload);
        if (!MessageDigest.isEqual(signature, Base64.getDecoder().decode(tokenParts[2]))) {
            throw new InvalidSignatureException("Signature has been compromised");
        }
    } catch (NoSuchAlgorithmExceptionInvalidKeyException |  e) {
        throw new AlgorithmException(e);
    }
}
Example 39
Project: kaa-master  File: Utils.java View source code
/**
   * Change encoding of uuids  from <b>latin1 (ISO-8859-1)</b> to <b>base64</b>.
   *
   * @param json the json that should be processed
   * @return the json with changed uuids
   * @throws IOException the io exception
   */
public static JsonNode encodeUuids(JsonNode json) throws IOException {
    if (json.has(UUID_FIELD)) {
        JsonNode jsonNode = json.get(UUID_FIELD);
        if (jsonNode.has(UUID_VALUE)) {
            String value = jsonNode.get(UUID_VALUE).asText();
            String encodedValue = Base64.getEncoder().encodeToString(value.getBytes("ISO-8859-1"));
            ((ObjectNode) jsonNode).put(UUID_VALUE, encodedValue);
        }
    }
    for (JsonNode node : json) {
        if (node.isContainerNode()) {
            encodeUuids(node);
        }
    }
    return json;
}
Example 40
Project: keywhiz-master  File: CookieAuthenticator.java View source code
private Optional<UserCookieData> getUserCookieData(Cookie sessionCookie) {
    byte[] ciphertext = Base64.getDecoder().decode(sessionCookie.getValue());
    UserCookieData cookieData = null;
    try {
        cookieData = mapper.readValue(encryptor.decrypt(ciphertext), UserCookieData.class);
        if (cookieData.getExpiration().isBefore(ZonedDateTime.now())) {
            cookieData = null;
        }
    } catch (AEADBadTagException e) {
        logger.warn("Cookie with bad MAC detected");
    } catch (Exception e) {
    }
    return Optional.ofNullable(cookieData);
}
Example 41
Project: kinesis-vcr-master  File: S3RecorderPipeline.java View source code
@Override
public ITransformerBase<byte[], byte[]> getTransformer(KinesisConnectorConfiguration configuration) {
    return new ITransformer<byte[], byte[]>() {

        @Override
        public byte[] toClass(Record record) throws IOException {
            return record.getData().array();
        }

        @Override
        public byte[] fromClass(byte[] record) throws IOException {
            byte[] encoded = Base64.getEncoder().encode(record);
            byte[] expanded = Arrays.copyOf(encoded, encoded.length + 1);
            expanded[encoded.length] = '\n';
            return expanded;
        }
    };
}
Example 42
Project: levelup-java-examples-master  File: DecodeURLBase64.java View source code
@Test
public void string_base64_decode_java_8() throws UnsupportedEncodingException {
    String encodedURL = "aHR0cDovL2xldmVsdXBsdW5jaC5jb20vZXhhbXBsZXMvP3Bhcm09VGhpcyBwYXJhbWV0ZXI=";
    byte[] decodedURLAsBytes = java.util.Base64.getDecoder().decode(encodedURL);
    String decodedURL = new String(decodedURLAsBytes, "utf-8");
    assertEquals("http://leveluplunch.com/examples/?parm=This parameter", decodedURL);
}
Example 43
Project: mathosphere-master  File: PreprocessedExtractedMathPDDocumentMapper.java View source code
public static ExtractedMathPDDocument readExtractedMathPDDocumentFromText(String text) {
    LOGGER.info("text = " + text);
    ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(text));
    ObjectInput in = null;
    try {
        in = new ObjectInputStream(bis);
        return (ExtractedMathPDDocument) in.readObject();
    } catch (IOExceptionClassNotFoundException |  e) {
        new RuntimeException(e);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ex2) {
        }
    }
    return null;
}
Example 44
Project: Mujina-master  File: AbstractIntegrationTest.java View source code
protected CookieFilter login() throws IOException {
    CookieFilter cookieFilter = new CookieFilter();
    String html = given().filter(cookieFilter).get("/login").getBody().asString();
    Matcher matcher = Pattern.compile("name=\"SAMLRequest\" value=\"(.*?)\"").matcher(html);
    matcher.find();
    String samlRequest = new String(Base64.getDecoder().decode(matcher.group(1)));
    //Now mimic a response message
    String samlResponse = getIdPSAMLResponse(samlRequest);
    given().formParam("SAMLResponse", Base64.getEncoder().encodeToString(samlResponse.getBytes())).filter(cookieFilter).post("/saml/SSO").then().statusCode(SC_MOVED_TEMPORARILY);
    return cookieFilter;
}
Example 45
Project: nifi-master  File: PasswordUtilTest.java View source code
@Test
public void testGeneratePassword() {
    SecureRandom secureRandom = mock(SecureRandom.class);
    PasswordUtil passwordUtil = new PasswordUtil(secureRandom);
    int value = 8675309;
    doAnswer( invocation -> {
        byte[] bytes = (byte[]) invocation.getArguments()[0];
        assertEquals(32, bytes.length);
        Arrays.fill(bytes, (byte) 0);
        byte[] val = ByteBuffer.allocate(Long.BYTES).putLong(value).array();
        System.arraycopy(val, 0, bytes, bytes.length - val.length, val.length);
        return null;
    }).when(secureRandom).nextBytes(any(byte[].class));
    byte[] expectedBytes = new byte[32];
    byte[] numberBytes = BigInteger.valueOf(Integer.valueOf(value).longValue()).toByteArray();
    System.arraycopy(numberBytes, 0, expectedBytes, expectedBytes.length - numberBytes.length, numberBytes.length);
    String expected = Base64.getEncoder().encodeToString(expectedBytes).split("=")[0];
    String actual = passwordUtil.generatePassword();
    assertEquals(expected, actual);
}
Example 46
Project: org.openwms-master  File: SecurityUtils.java View source code
public static HttpHeaders createHeaders(String username, String password) {
    if (username == null || username.isEmpty()) {
        return new HttpHeaders();
    }
    return new HttpHeaders() {

        {
            String auth = username + ":" + password;
            byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("UTF-8")));
            String authHeader = "Basic " + new String(encodedAuth);
            set("Authorization", authHeader);
        }
    };
}
Example 47
Project: pac4j-master  File: CookieClientTests.java View source code
@Test
public void testAuthentication() throws HttpAction, UnsupportedEncodingException {
    final CookieClient client = new CookieClient(USERNAME, new SimpleTestTokenAuthenticator());
    final MockWebContext context = MockWebContext.create();
    final Cookie c = new Cookie(USERNAME, Base64.getEncoder().encodeToString(getClass().getName().getBytes(HttpConstants.UTF8_ENCODING)));
    context.getRequestCookies().add(c);
    final TokenCredentials credentials = client.getCredentials(context);
    final CommonProfile profile = client.getUserProfile(credentials, context);
    assertEquals(c.getValue(), profile.getId());
}
Example 48
Project: package-drone-master  File: Tokens.java View source code
public static String hashIt(final String salt, String data) {
    data = Normalizer.normalize(data, Form.NFC);
    final byte[] strData = data.getBytes(StandardCharsets.UTF_8);
    final byte[] saltData = salt.getBytes(StandardCharsets.UTF_8);
    final byte[] first = new byte[saltData.length + strData.length];
    System.arraycopy(saltData, 0, first, 0, saltData.length);
    System.arraycopy(strData, 0, first, saltData.length, strData.length);
    MessageDigest md;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
    byte[] digest = md.digest(first);
    final byte[] current = new byte[saltData.length + digest.length];
    for (int i = 0; i < 1000; i++) {
        System.arraycopy(saltData, 0, current, 0, saltData.length);
        System.arraycopy(digest, 0, current, saltData.length, digest.length);
        digest = md.digest(current);
    }
    return Base64.getEncoder().encodeToString(digest);
}
Example 49
Project: pippo-master  File: SerializationSessionDataTranscoder.java View source code
@Override
public String encode(SessionData sessionData) {
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) {
        objectOutputStream.writeObject(sessionData);
        byte[] bytes = outputStream.toByteArray();
        return Base64.getEncoder().encodeToString(bytes);
    } catch (IOException e) {
        throw new PippoRuntimeException(e);
    }
}
Example 50
Project: prime-mvc-master  File: TestBuilder.java View source code
public TestBuilder createFile(String contents) throws IOException {
    String tmpdir = System.getProperty("java.io.tmpdir");
    String unique = new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()), "UTF-8").substring(0, 5);
    tempFile = Paths.get(tmpdir + "/" + "_prime_binaryContent_" + unique);
    tempFile.toFile().deleteOnExit();
    Files.write(tempFile, contents.getBytes());
    return this;
}
Example 51
Project: restful-and-beyond-tut2184-master  File: LoginRestFilter.java View source code
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    String auth = requestContext.getHeaderString("Authorization");
    if (auth != null) {
        String input = auth.replaceFirst("Basic", "").trim();
        byte[] credential = Base64.getDecoder().decode(input.getBytes());
        String value = new String(credential, "UTF-8");
        String[] parts = value.split(":");
        userManager.validateCredential(parts[0], parts[1]);
        user.setUsername(parts[0]);
        user.setGroups(userManager.getGroups(parts[0]));
    }
}
Example 52
Project: Rob-Maven-and-Gradle-Plugins-master  File: RobLogBitbucketManager.java View source code
@Override
protected List<? extends Commit> fetchFromApi(int page) {
    if (conf.hasUsernamePassword()) {
        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(Bitbucket.URL).build();
        Bitbucket bitbucket = restAdapter.create(Bitbucket.class);
        String auth = "Basic " + Base64.getEncoder().encodeToString((conf.getUsername() + ":" + conf.getPassword()).getBytes());
        if (page == 0) {
            resp = bitbucket.listCommits(conf.getOwner(), conf.getRepo(), conf.getBranch(), auth);
        } else {
            resp = bitbucket.listCommits(conf.getOwner(), conf.getRepo(), conf.getBranch(), page, auth);
        }
        getLog().info("Driving the car");
    } else {
        RetrofitHttpOAuthConsumer oAuthConsumer = new RetrofitHttpOAuthConsumer(conf.getKey(), conf.getSecret());
        //oAuthConsumer.setTokenWithSecret(token, secret);
        RestAdapter restAdapter = new RestAdapter.Builder().setClient(new SigningOkClient(oAuthConsumer)).setEndpoint(Bitbucket.URL).build();
        Bitbucket bitbucket = restAdapter.create(Bitbucket.class);
        if (page == 0) {
            resp = bitbucket.listCommits(conf.getOwner(), conf.getRepo(), conf.getBranch());
        } else {
            resp = bitbucket.listCommits(conf.getOwner(), conf.getRepo(), conf.getBranch(), page);
        }
        getLog().info("Driving a van");
    }
    getLog().info("Neighborhood with " + resp.getPagelen() + " houses (Pages).");
    return resp.getValues();
}
Example 53
Project: roda-master  File: BasicAuthRequestWrapper.java View source code
/**
   * Returns a {@link Pair} of {@link String}s with the username and password
   * contained in the HTTP header <strong>Authorization</strong> or
   * <code>null</code> if the credentials could not be extracted.
   * 
   * @return a {@link Pair} with username and password.
   */
public Pair<String, String> getCredentials() {
    Pair<String, String> ret = null;
    final String authorization = getHeader("Authorization");
    if (authorization != null && authorization.startsWith("Basic")) {
        String credentials = authorization;
        credentials = credentials.replaceFirst("[B|b]asic ", "");
        credentials = new String(Base64.getDecoder().decode(credentials), Charset.forName(RodaConstants.DEFAULT_ENCODING));
        final String[] values = credentials.split(":", 2);
        if (values[0] != null && values[1] != null) {
            ret = Pair.of(values[0], values[1]);
        }
    }
    return ret;
}
Example 54
Project: sandboxes-master  File: HelloWorldTest.java View source code
private ConfluenceClient client() {
    final String basic = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder().header("Authorization", basic).header("Accept", "application/json").method(original.method(), original.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.addInterceptor(loggingInterceptor);
    Retrofit confluence = new Retrofit.Builder().client(client.build()).baseUrl(baseUrl).addConverterFactory(JacksonConverterFactory.create()).build();
    return confluence.create(ConfluenceClient.class);
}
Example 55
Project: teavm-master  File: ResourcesInterceptor.java View source code
@Override
public void begin(RenderingManager manager, BuildTarget buildTarget) throws IOException {
    boolean hasOneResource = false;
    for (String className : manager.getClassSource().getClassNames()) {
        final int lastDot = className.lastIndexOf('.');
        if (lastDot == -1) {
            continue;
        }
        String packageName = className.substring(0, lastDot);
        String resourceName = packageName.replace('.', '/') + "/" + "jvm.txt";
        try (InputStream input = manager.getClassLoader().getResourceAsStream(resourceName)) {
            if (input == null || !processed.add(resourceName)) {
                continue;
            }
            ByteArrayOutputStream arr = new ByteArrayOutputStream();
            IOUtils.copy(input, arr);
            String base64 = Base64.getEncoder().encodeToString(arr.toByteArray());
            input.close();
            final SourceWriter w = manager.getWriter();
            w.append("// Resource " + resourceName + " included by " + className).newLine();
            w.append("if (!window.teaVMResources) window.teaVMResources = {};").newLine();
            w.append("window.teaVMResources['" + resourceName + "'] = '");
            w.append(base64).append("';").newLine().newLine();
        }
        hasOneResource = true;
    }
    if (hasOneResource) {
        manager.getWriter().append("// TeaVM generated classes").newLine();
    }
}
Example 56
Project: TracInstant-master  File: AuthenticatedHttpRequester.java View source code
public static InputStream getInputStream(SiteSettings settings, URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (!settings.getUsername().isEmpty()) {
        String userpass = settings.getUsername() + ":" + settings.getPassword();
        String basicAuth = "Basic " + Base64.getEncoder().encodeToString(userpass.getBytes());
        uc.setRequestProperty("Authorization", basicAuth);
    }
    return uc.getInputStream();
}
Example 57
Project: vnluser-master  File: TestStringProcessing.java View source code
public static void main(String[] args) throws Exception {
    String refererUrl = "ab\tc\ndef";
    System.out.println(refererUrl);
    refererUrl = StringUtils.replaceEach(refererUrl, REFERER_SEARCH_LIST, REFERER_REPLACE_LIST);
    System.out.println(refererUrl);
    String u = "aHR0cDovL2dhY3NhY2guY29tL3RodS12aWVuLXNhY2g@cGFnZT00".replace("@", "/");
    System.out.println("urf: " + new String(Base64.getDecoder().decode(u)));
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("name", "value 1");
    model.put("blogs", Arrays.asList("title1", "title2"));
    model.put("users", Arrays.asList(new User("trieu", 28), new User("Khoa", 1)));
    TemplateLoader loader = new FileTemplateLoader("C:\\Users\\trieu.nguyen\\git\\netty-s2-http-server\\resources\\tpl\\handlebars", ".html");
    Handlebars handlebars = new Handlebars(loader);
    Template template = handlebars.compile("test");
    System.out.println(template.apply(model));
}
Example 58
Project: webpie-master  File: Security.java View source code
public String sign(SecretKeyInfo keyInfo, String message) {
    if (keyInfo == null || keyInfo.getAlgorithm() == null || keyInfo.getKeyData() == null)
        throw new IllegalArgumentException("key must be fully specified");
    try {
        Mac mac = Mac.getInstance(keyInfo.getAlgorithm());
        mac.init(keyInfo.getKey());
        byte[] messageBytes = message.getBytes("utf-8");
        byte[] result = mac.doFinal(messageBytes);
        return Base64.getEncoder().encodeToString(result);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
Example 59
Project: wildfly-core-master  File: DisplaySecret.java View source code
public State execute() {
    String pwdBase64 = Base64.getEncoder().encodeToString(stateValues.getPassword().getBytes(StandardCharsets.UTF_8));
    theConsole.printf(DomainManagementLogger.ROOT_LOGGER.secretElement(pwdBase64));
    theConsole.printf(NEW_LINE);
    // This is now the final state so return null.
    return null;
}
Example 60
Project: zipkin-java-master  File: ScribeSpanConsumer.java View source code
@Override
public ResultCode log(List<LogEntry> messages) {
    Stream<Span> spansToStore = messages.stream().filter( m -> m.category().equals("zipkin")).map(LogEntry::message).map( m -> Base64.getDecoder().decode(m)).map( bytes -> {
        TMemoryBuffer transport = new TMemoryBuffer(bytes.length);
        try {
            transport.write(bytes);
            return spanCodec.read(new TBinaryProtocol(transport));
        } catch (Exception e) {
            return null;
        }
    }).filter( s -> s != null).filter( s -> !(s.isClientSide() && s.serviceNames().contains("client")));
    consumer.accept(spansToStore.collect(Collectors.toList()));
    return ResultCode.OK;
}
Example 61
Project: wicket-master  File: ImageUtil.java View source code
/**
	 * Creates a base64 encoded image string based on the given image reference
	 *
	 * @param imageReference
	 *            the image reference to create the base64 encoded image string of
	 * @param removeWhitespaces
	 *            if whitespaces should be removed from the output
	 * @return the base64 encoded image string
	 * @throws ResourceStreamNotFoundException
	 *             if the resource couldn't be found
	 * @throws IOException
	 *             if the stream couldn't be read
	 */
public static CharSequence createBase64EncodedImage(PackageResourceReference imageReference, boolean removeWhitespaces) throws ResourceStreamNotFoundException, IOException {
    IResourceStream resourceStream = imageReference.getResource().getResourceStream();
    InputStream inputStream = resourceStream.getInputStream();
    try {
        byte[] bytes = IOUtils.toByteArray(inputStream);
        String base64EncodedImage = Base64.getEncoder().encodeToString(bytes);
        return "data:" + resourceStream.getContentType() + ";base64," + (removeWhitespaces ? base64EncodedImage.replaceAll("\\s", "") : base64EncodedImage);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}
Example 62
Project: accumulo-master  File: ShellUtil.java View source code
/**
   * Scans the given file line-by-line (ignoring empty lines) and returns a list containing those lines. If decode is set to true, every line is decoded using
   * {@link Base64} from the UTF-8 bytes of that line before inserting in the list.
   *
   * @param filename
   *          Path to the file that needs to be scanned
   * @param decode
   *          Whether to decode lines in the file
   * @return List of {@link Text} objects containing data in the given file
   * @throws FileNotFoundException
   *           if the given file doesn't exist
   */
public static List<Text> scanFile(String filename, boolean decode) throws FileNotFoundException {
    String line;
    Scanner file = new Scanner(new File(filename), UTF_8.name());
    List<Text> result = new ArrayList<>();
    try {
        while (file.hasNextLine()) {
            line = file.nextLine();
            if (!line.isEmpty()) {
                result.add(decode ? new Text(Base64.getDecoder().decode(line)) : new Text(line));
            }
        }
    } finally {
        file.close();
    }
    return result;
}
Example 63
Project: activedirectory-master  File: DelegatingNegotiateSecurityFilterTest.java View source code
/**
     * Test the delegating filter ,in case no custom authentication was passed, the filter would store the auth in the
     * security context.
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     * @throws ServletException
     *             the servlet exception
     */
@Test
public void testNegotiate() throws IOException, ServletException {
    final String securityPackage = "Negotiate";
    final SimpleFilterChain filterChain = new SimpleFilterChain();
    final SimpleHttpRequest request = new SimpleHttpRequest();
    final String clientToken = Base64.getEncoder().encodeToString(WindowsAccountImpl.getCurrentUsername().getBytes(StandardCharsets.UTF_8));
    request.addHeader("Authorization", securityPackage + " " + clientToken);
    final SimpleHttpResponse response = new SimpleHttpResponse();
    this.filter.doFilter(request, response, filterChain);
    final Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Assert.assertNotNull(auth);
    final Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
    Assert.assertNotNull(authorities);
    Assert.assertEquals(3, authorities.size());
    final List<String> list = new ArrayList<>();
    for (GrantedAuthority grantedAuthority : authorities) {
        list.add(grantedAuthority.getAuthority());
    }
    Collections.sort(list);
    Assert.assertEquals("ROLE_EVERYONE", list.get(0));
    Assert.assertEquals("ROLE_USER", list.get(1));
    Assert.assertEquals("ROLE_USERS", list.get(2));
    Assert.assertEquals(0, response.getHeaderNamesSize());
}
Example 64
Project: bamboo-artifactory-plugin-master  File: EncryptionHelper.java View source code
@NotNull
public static String encrypt(@Nullable String stringToEncrypt) {
    if (StringUtils.isEmpty(stringToEncrypt)) {
        return StringUtils.EMPTY;
    }
    try {
        final byte[] encrypted = getEncrypter().doFinal(stringToEncrypt.getBytes(StandardCharsets.UTF_8));
        return Base64.getMimeEncoder().encodeToString(encrypted);
    } catch (Exception e) {
        throw new RuntimeException("Failed to encrypt.", e);
    }
}
Example 65
Project: che-master  File: UserSpecificDockerRegistryCredentialsProvider.java View source code
/**
     * Gets and decode credentials for docker registries from user preferences.
     * If it hasn't saved yet, {@code AuthConfigs} with empty map will be returned.
     *
     * @return docker registry credentials from user preferences
     *         or null when preferences can't be retrieved or parsed
     */
@Nullable
public AuthConfigs getCredentials() {
    try {
        String encodedCredentials = preferenceManager.find(EnvironmentContext.getCurrent().getSubject().getUserId(), DOCKER_REGISTRY_CREDENTIALS_KEY).get(DOCKER_REGISTRY_CREDENTIALS_KEY);
        String credentials = encodedCredentials != null ? new String(Base64.getDecoder().decode(encodedCredentials), "UTF-8") : "{}";
        return DtoFactory.newDto(AuthConfigs.class).withConfigs(DtoFactory.getInstance().createMapDtoFromJson(credentials, AuthConfig.class));
    } catch (Exception e) {
        LOG.warn(e.getLocalizedMessage());
        return null;
    }
}
Example 66
Project: critter-master  File: ProtobufPath.java View source code
@Override
public boolean test(RuleContext ctx) {
    String contentType = ctx.httpContext.getRequest().getHeaderValue("Content-Type");
    if (!"application/octet-stream".equals(contentType)) {
        if (ctx.rule.tracing) {
            LOG.info("rule={} contentType={} expected={}", ctx.rule.id, contentType, "application/octet-stream");
            return false;
        }
    }
    byte[] data = ctx.getRequestEntityContent();
    // see if we need to decode it
    String contentEncoding = ctx.httpContext.getRequest().getHeaderValue("Content-Encoding");
    if (contentEncoding != null && contentEncoding.length() > 0) {
        if (!"base64".equals(contentEncoding)) {
            if (ctx.rule.tracing) {
                LOG.info("rule={} acceptEncoding={} expected={}", ctx.rule.id, contentEncoding, "base64");
            }
            return false;
        }
        data = Base64.getDecoder().decode(data);
    }
    if (ctx.rule.tracing) {
        LOG.info("rule={} data-base64={} data-size={}", ctx.rule.id, new String(Base64.getEncoder().encode(data)), data.length);
    }
    Definitions defs = ctx.protoDefinitions.getDefinitions(ctx.rule.id);
    if (defs.isEmpty()) {
        if (ctx.rule.tracing) {
            LOG.info("rule={} missing definitions", ctx.rule.id);
        }
        return false;
    }
    Inspector inspector = defs.newInspector(this.messageName);
    if (!inspector.read(data)) {
        if (ctx.rule.tracing) {
            LOG.info("rule={} error=unable to read protobuf message data (definitions uploaded?)", ctx.rule.id);
        }
        return false;
    }
    String value = inspector.path(this.expression);
    if (ctx.rule.tracing) {
        LOG.debug("rule={} messageName={} expression={} value={}", ctx.rule.id, this.messageName, this.expression, value);
    }
    return value.matches(this.matches);
}
Example 67
Project: cxf-master  File: CustomBSTTokenValidator.java View source code
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isBinarySecurityToken()) {
        return response;
    }
    BinarySecurityTokenType binarySecurityToken = (BinarySecurityTokenType) validateTarget.getToken();
    //
    if (Base64.getMimeEncoder().encodeToString("12345678".getBytes()).equals(binarySecurityToken.getValue())) {
        validateTarget.setState(STATE.VALID);
    }
    response.setPrincipal(new CustomTokenPrincipal("alice"));
    return response;
}
Example 68
Project: ddf-master  File: PostRequestDecoder.java View source code
@Override
public AuthnRequest decodeRequest(String samlRequest) {
    LOGGER.debug("Creating AuthnRequest object from SAMLRequest string.");
    if (StringUtils.isEmpty(samlRequest)) {
        throw new IllegalArgumentException("Missing SAMLRequest on IdP request.");
    }
    String decodedRequest = new String(Base64.getMimeDecoder().decode(samlRequest), StandardCharsets.UTF_8);
    ByteArrayInputStream tokenStream = new ByteArrayInputStream(decodedRequest.getBytes(StandardCharsets.UTF_8));
    Document authnDoc;
    try {
        authnDoc = StaxUtils.read(new InputStreamReader(tokenStream, "UTF-8"));
    } catch (Exception ex) {
        throw new IllegalArgumentException("Unable to read SAMLRequest as XML.");
    }
    XMLObject authnXmlObj;
    try {
        authnXmlObj = OpenSAMLUtil.fromDom(authnDoc.getDocumentElement());
    } catch (WSSecurityException ex) {
        throw new IllegalArgumentException("Unable to convert AuthnRequest document to XMLObject.");
    }
    if (!(authnXmlObj instanceof AuthnRequest)) {
        throw new IllegalArgumentException("SAMLRequest object is not AuthnRequest.");
    }
    LOGGER.debug("Created AuthnRequest object successfully.");
    return (AuthnRequest) authnXmlObj;
}
Example 69
Project: DevTools-master  File: UserSpecificDockerRegistryCredentialsProvider.java View source code
/**
     * Gets and decode credentials for docker registries from user preferences.
     * If it hasn't saved yet, {@code AuthConfigs} with empty map will be returned.
     *
     * @return docker registry credentials from user preferences
     *         or null when preferences can't be retrieved or parsed
     */
@Nullable
public AuthConfigs getCredentials() {
    try {
        String encodedCredentials = preferenceManager.find(EnvironmentContext.getCurrent().getSubject().getUserId(), DOCKER_REGISTRY_CREDENTIALS_KEY).get(DOCKER_REGISTRY_CREDENTIALS_KEY);
        String credentials = encodedCredentials != null ? new String(Base64.getDecoder().decode(encodedCredentials), "UTF-8") : "{}";
        return DtoFactory.newDto(AuthConfigs.class).withConfigs(DtoFactory.getInstance().createMapDtoFromJson(credentials, AuthConfig.class));
    } catch (Exception e) {
        LOG.warn(e.getLocalizedMessage());
        return null;
    }
}
Example 70
Project: elasticsearch-master  File: PutPipelineRequestTests.java View source code
public void testSerializationBwc() throws IOException {
    final byte[] data = Base64.getDecoder().decode("ADwDATECe30=");
    final Version version = randomFrom(Version.V_5_0_0, Version.V_5_0_1, Version.V_5_0_2, Version.V_5_0_3_UNRELEASED, Version.V_5_1_1_UNRELEASED, Version.V_5_1_2_UNRELEASED, Version.V_5_2_0_UNRELEASED);
    try (StreamInput in = StreamInput.wrap(data)) {
        in.setVersion(version);
        PutPipelineRequest request = new PutPipelineRequest();
        request.readFrom(in);
        assertEquals(XContentType.JSON, request.getXContentType());
        assertEquals("{}", request.getSource().utf8ToString());
        try (BytesStreamOutput out = new BytesStreamOutput()) {
            out.setVersion(version);
            request.writeTo(out);
            assertArrayEquals(data, out.bytes().toBytesRef().bytes);
        }
    }
}
Example 71
Project: fenixedu-cms-master  File: CMSThemeFile.java View source code
public JsonElement toJson() {
    JsonObject json = new JsonObject();
    json.addProperty("fileName", fileName);
    json.addProperty("fullPath", fullPath);
    json.addProperty("contentType", contentType);
    json.addProperty("content", Base64.getEncoder().encodeToString(content));
    json.addProperty("lastModified", lastModified.getMillis());
    return json;
}
Example 72
Project: fess-master  File: ApiAdminLogAction.java View source code
// GET /api/admin/log/file/{id}
@Execute
public StreamResponse get$file(final String id) {
    final String filename = new String(Base64.getDecoder().decode(id), StandardCharsets.UTF_8).replace("..", "").replaceAll("\\s", "");
    final String logFilePath = systemHelper.getLogFilePath();
    if (StringUtil.isNotBlank(logFilePath)) {
        final Path path = Paths.get(logFilePath, filename);
        return asStream(filename).contentTypeOctetStream().stream( out -> {
            try (InputStream in = Files.newInputStream(path)) {
                out.write(in);
            }
        });
    }
    return StreamResponse.asEmptyBody();
}
Example 73
Project: Fiazard-master  File: AtomPoller.java View source code
private <T extends Element> T getElement(String url) throws IOException {
    String username = "admin";
    String password = "changeit";
    URLConnection uc = new URL(url).openConnection();
    String userpass = username + ":" + password;
    String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
    uc.setRequestProperty("Authorization", basicAuth);
    uc.setRequestProperty("Accept", "application/atom+xml");
    Abdera abdera = new Abdera();
    Parser parser = abdera.getParser();
    Document<T> doc = parser.parse(uc.getInputStream(), url);
    return doc.getRoot();
}
Example 74
Project: flashback-master  File: NettyHttpResponseMapper.java View source code
public static FullHttpResponse from(RecordedHttpResponse recordedHttpResponse) throws IOException {
    FullHttpResponse fullHttpResponse;
    HttpResponseStatus status = HttpResponseStatus.valueOf(recordedHttpResponse.getStatus());
    if (recordedHttpResponse.hasHttpBody()) {
        ByteBuf content = wrappedBuffer(createHttpBodyBytes(recordedHttpResponse));
        fullHttpResponse = new DefaultFullHttpResponse(HTTP_1_1, status, content);
    } else {
        fullHttpResponse = new DefaultFullHttpResponse(HTTP_1_1, status);
    }
    for (Map.Entry<String, String> header : recordedHttpResponse.getHeaders().entrySet()) {
        // differently
        if (SET_COOKIE.equals(header.getKey())) {
            fullHttpResponse.headers().set(header.getKey(), StreamSupport.stream(Splitter.onPattern(",\\s*").split(header.getValue()).spliterator(), false).map( p -> new String(Base64.getDecoder().decode(p.getBytes()))).collect(Collectors.toList()));
        } else {
            fullHttpResponse.headers().set(header.getKey(), Splitter.onPattern(",\\s*").split(header.getValue()));
        }
    }
    return fullHttpResponse;
}
Example 75
Project: gradle-aws-plugin-master  File: AmazonEC2RunInstanceTask.java View source code
@TaskAction
public void runInstance() {
    // to enable conventionMappings feature
    String ami = getAmi();
    String keyName = getKeyName();
    List<String> securityGroupIds = getSecurityGroupIds();
    String userData = getUserData();
    String instanceType = getInstanceType();
    String subnetId = getSubnetId();
    if (ami == null) {
        throw new GradleException("AMI ID is required");
    }
    AmazonEC2PluginExtension ext = getProject().getExtensions().getByType(AmazonEC2PluginExtension.class);
    AmazonEC2 ec2 = ext.getClient();
    RunInstancesRequest request = new RunInstancesRequest().withImageId(ami).withKeyName(keyName).withMinCount(1).withMaxCount(1).withSecurityGroupIds(securityGroupIds).withInstanceType(instanceType).withSubnetId(subnetId);
    if (Strings.isNullOrEmpty(this.userData) == false) {
        request.setUserData(new String(Base64.getEncoder().encode(userData.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
    }
    runInstancesResult = ec2.runInstances(request);
    String instanceIds = runInstancesResult.getReservation().getInstances().stream().map( i -> i.getInstanceId()).collect(Collectors.joining(", "));
    getLogger().info("Run EC2 instance requested: {}", instanceIds);
}
Example 76
Project: ha-jdbc-master  File: CipherCodecFactoryTest.java View source code
@Before
public void before() throws Exception {
    File file = File.createTempFile("ha-jdbc", "keystore");
    SecretKeyFactory factory = SecretKeyFactory.getInstance(ALGORITHM);
    this.key = factory.generateSecret(new DESKeySpec(Base64.getDecoder().decode(KEY)));
    KeyStore store = KeyStore.getInstance(CipherCodecFactory.Property.KEYSTORE_TYPE.defaultValue);
    store.load(null, null);
    store.setKeyEntry(CipherCodecFactory.Property.KEY_ALIAS.defaultValue, this.key, KEY_PASSWORD.toCharArray(), null);
    try (FileOutputStream out = new FileOutputStream(file)) {
        store.store(out, STORE_PASSWORD.toCharArray());
    }
    System.setProperty(CipherCodecFactory.Property.KEYSTORE_FILE.name, file.getPath());
    System.setProperty(CipherCodecFactory.Property.KEYSTORE_PASSWORD.name, STORE_PASSWORD);
    System.setProperty(CipherCodecFactory.Property.KEY_PASSWORD.name, KEY_PASSWORD);
}
Example 77
Project: ja-micro-master  File: RpcReadException.java View source code
public String toJson(HttpServletRequest req) {
    JsonObject obj = new JsonObject();
    Enumeration<String> h = req.getHeaderNames();
    while (h.hasMoreElements()) {
        String hKey = h.nextElement();
        String hValue = req.getHeader(hKey);
        obj.addProperty("request_header_" + hKey, hValue);
    }
    obj.addProperty("exception_message", this.getMessage());
    obj.addProperty("request_query_string", req.getQueryString());
    obj.addProperty("request_url", req.getRequestURL().toString());
    obj.addProperty("request_remote_addr", req.getRemoteAddr());
    obj.addProperty("request_remote_port", req.getRemotePort());
    obj.addProperty("request_remote_host", req.getRemoteHost());
    obj.addProperty("request_remote_user", req.getRemoteUser());
    String readBody = "success";
    // read the whole remaining body and put the joined base64 encoded message into the json object
    try {
        byte[] ba = IOUtils.toByteArray(this.in);
        byte[] combined;
        if ((ba != null) && (this.incomplete != null)) {
            combined = new byte[ba.length + this.incomplete.length];
            System.arraycopy(incomplete, 0, combined, 0, this.incomplete.length);
            System.arraycopy(ba, 0, combined, this.incomplete.length, ba.length);
            obj.addProperty("request_body", Base64.getEncoder().encodeToString(combined));
        } else if (ba != null) {
            combined = ba;
        } else if (this.incomplete != null) {
            combined = this.incomplete;
        } else {
            readBody = "body is empty";
        }
    } catch (Exception ex) {
        readBody = String.format("failed because: %s", ex.getCause());
    }
    obj.addProperty("read_body", readBody);
    return obj.toString();
}
Example 78
Project: janusz-master  File: CMDFuCommand.java View source code
private String retriveFromCMDFu(String question) throws UnirestException {
    HttpResponse<JsonNode> cmdfuResponse = Unirest.get(CMDFU_API_PATH + "//matching/{search}/{b64_search}/bys=/sort-by-votes/json").routeParam("search", question).routeParam("b64_search", new String(Base64.getEncoder().encode(question.getBytes()))).asJson();
    System.out.println("cmdfuResponse = " + cmdfuResponse);
    log.info("Command for {}", question);
    log.info("CMDFu response: {}", cmdfuResponse.getBody().toString());
    String response = "";
    for (int i = 0; i < 3; i++) {
        response += cmdfuResponse.getBody().getArray().getJSONObject(i).get("command").toString() + "\n";
    }
    log.info("Got commands {}", response);
    return response;
}
Example 79
Project: JECommons-master  File: ConnectionEncoder.java View source code
public static JEVisOption decode(String value) {
    byte[] decodedValue = Base64.getDecoder().decode(value);
    String asSting = new String(decodedValue, StandardCharsets.UTF_8);
    //        String encoded = Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8));
    String[] segs = asSting.split(Pattern.quote(seperator));
    JEVisOption datasource = new BasicOption();
    datasource.setKey(CommonOptions.DataSource.DataSource.getKey());
    JEVisOption host = new BasicOption();
    host.setKey(CommonOptions.DataSource.HOST.getKey());
    host.setValue(segs[0]);
    JEVisOption port = new BasicOption();
    port.setKey(CommonOptions.DataSource.PORT.getKey());
    port.setValue(segs[1]);
    JEVisOption schema = new BasicOption();
    schema.setKey(CommonOptions.DataSource.SCHEMA.getKey());
    schema.setValue(segs[2]);
    JEVisOption user = new BasicOption();
    user.setKey(CommonOptions.DataSource.USERNAME.getKey());
    user.setValue(segs[3]);
    JEVisOption pass = new BasicOption();
    pass.setKey(CommonOptions.DataSource.PASSWORD.getKey());
    pass.setValue(segs[4]);
    JEVisOption dsclass = new BasicOption();
    dsclass.setKey(CommonOptions.DataSource.CLASS.getKey());
    dsclass.setValue("org.jevis.api.sql.JEVisDataSourceSQL");
    datasource.addOption(host, true);
    datasource.addOption(port, true);
    datasource.addOption(schema, true);
    datasource.addOption(user, true);
    datasource.addOption(pass, true);
    datasource.addOption(dsclass, true);
    //        }
    return datasource;
}
Example 80
Project: josm-plugins-master  File: SdsConnection.java View source code
/**
     * Adds an authentication header for basic authentication
     *
     * @param con the connection
     * @throws SdsTransferException thrown if something went wrong. Check for nested exceptions
     */
protected void addBasicAuthorizationHeader(HttpURLConnection con) throws SdsTransferException {
    CredentialsAgentResponse response;
    String token;
    try {
        response = credAgent.getCredentials(RequestorType.SERVER, con.getURL().getHost(), false);
    } catch (CredentialsAgentException e) {
        throw new SdsTransferException(e);
    }
    if (response == null) {
        token = ":";
    } else if (response.isCanceled()) {
        cancel = true;
        return;
    } else {
        String username = response.getUsername() == null ? "" : response.getUsername();
        String password = response.getPassword() == null ? "" : String.valueOf(response.getPassword());
        token = username + ":" + password;
        con.addRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8)));
    }
}
Example 81
Project: kura-master  File: CryptoServiceImpl.java View source code
private Object base64DecodeJava8(String internalStringValue) {
    Object convertedData = null;
    try {
        Class<?> clazz = Class.forName("java.util.Base64");
        Method decoderMethod = clazz.getMethod("getDecoder", (Class<?>[]) null);
        Object decoder = decoderMethod.invoke(null, new Object[0]);
        Class<?> base64Decoder = Class.forName("java.util.Base64$Decoder");
        Method decodeMethod = base64Decoder.getMethod("decode", String.class);
        convertedData = decodeMethod.invoke(decoder, internalStringValue);
    } catch (Exception e1) {
    }
    return convertedData;
}
Example 82
Project: loklak_server-master  File: IO.java View source code
/**
	 * Create PublicKey from String representation
	 * @param encodedKey
	 * @param algorithm
	 * @return PublicKey public_key
	 */
public static synchronized PublicKey decodePublicKey(@Nonnull String encodedKey, @Nonnull String algorithm) {
    try {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
        PublicKey pub = KeyFactory.getInstance(algorithm).generatePublic(keySpec);
        return pub;
    } catch (NoSuchAlgorithmExceptionInvalidKeySpecException |  e) {
        Log.getLog().warn(e);
    }
    return null;
}
Example 83
Project: MaritimeCloud-master  File: BasicAuthAuthenticationTokenHandler.java View source code
/**
     * Resolves an {@code AuthenticationToken} from the websocket upgrade request authorization header.
     * If none can be resolved, null is returned.
     *
     * @param authHeader the authorization header
     * @return the authentication token, or null if none is resolved
     */
public static AuthenticationToken resolveAuthenticationToken(String authHeader) {
    if (authHeader != null && authHeader.startsWith("Basic ")) {
        // Extract the user part from the header
        authHeader = authHeader.substring("Basic ".length());
        authHeader = new String(Base64.getDecoder().decode(authHeader), Charset.forName("UTF-8"));
        String name = authHeader.substring(0, authHeader.indexOf(":"));
        String password = authHeader.substring(name.length() + 1);
        return new UsernamePasswordToken(name, password.toCharArray());
    }
    // No principal resolved
    return null;
}
Example 84
Project: Orestes-Bloomfilter-master  File: BloomFilterConverter.java View source code
/**
     * Constructs a Bloom filter from its JSON representation
     *
     * @param source the JSON source
     * @param type   The class of the generic type
     * @param <T>    Generic type parameter of the Bloom filter
     * @return the Bloom filter
     */
public static <T> BloomFilter<T> fromJson(JsonElement source, Class<T> type) {
    JsonObject root = source.getAsJsonObject();
    int m = root.get("m").getAsInt();
    int k = root.get("h").getAsInt();
    //String hashMethod = root.get("HashMethod").getAsString();
    byte[] bits = Base64.getDecoder().decode(root.get("b").getAsString());
    FilterBuilder builder = new FilterBuilder(m, k).hashFunction(HashMethod.Murmur3KirschMitzenmacher);
    BloomFilterMemory<T> filter = new BloomFilterMemory<>(builder.complete());
    filter.setBitSet(BitSet.valueOf(bits));
    return filter;
}
Example 85
Project: org.ops4j.pax.web-master  File: AuthHttpContext.java View source code
protected boolean authenticated(HttpServletRequest request) {
    request.setAttribute(AUTHENTICATION_TYPE, HttpServletRequest.BASIC_AUTH);
    String authzHeader = request.getHeader("Authorization");
    String usernameAndPassword = new String(Base64.getDecoder().decode(authzHeader.substring(6).getBytes()));
    int userNameIndex = usernameAndPassword.indexOf(":");
    String username = usernameAndPassword.substring(0, userNameIndex);
    String password = usernameAndPassword.substring(userNameIndex + 1);
    // Here I will do lame hard coded credential check. HIGHLY NOT RECOMMENDED!
    boolean success = ((username.equals("admin") && password.equals("admin")));
    if (success) {
        request.setAttribute(REMOTE_USER, "admin");
    }
    return success;
}
Example 86
Project: presto-master  File: TestingBlockJsonSerde.java View source code
@Override
public void serialize(Block block, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
    SliceOutput output = new DynamicSliceOutput(64);
    BlockEncoding encoding = block.getEncoding();
    blockEncodingSerde.writeBlockEncoding(output, encoding);
    encoding.writeBlock(output, block);
    String encoded = Base64.getEncoder().encodeToString(output.slice().getBytes());
    jsonGenerator.writeString(encoded);
}
Example 87
Project: spring-boot-master  File: HelloWebSecurityApplicationTests.java View source code
@Test
public void userAuthenticates() throws Exception {
    this.request.addHeader("Authorization", "Basic " + new String(Base64.getEncoder().encode("user:password".getBytes("UTF-8"))));
    this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
    assertThat(this.response.getStatus()).isEqualTo(HttpServletResponse.SC_OK);
}
Example 88
Project: spring-framework-issues-master  File: AsyncrestremplatebugApplicationTests.java View source code
// exception is thrown
@Test(expected = SystemException.class)
public void works() throws Exception {
    AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate();
    HttpHeaders headers = new HttpHeaders();
    String authHeader = "Basic " + Base64.getEncoder().encode(("user:secret").getBytes());
    headers.add(AUTHORIZATION, authHeader);
    ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate.exchange("http://localhost:8080/sleepingendpoint", GET, new HttpEntity<String>(headers), String.class);
    // NOTE - only difference is that this sleeps
    Thread.sleep(5000);
    future.addCallback( s -> {
    },  f -> {
        System.err.println("CALLED ERROR HANDLER");
        throw new SystemException(f);
    });
    // the below is never reached
    ResponseEntity<String> resp = future.get();
    assertTrue(resp.getStatusCode().is2xxSuccessful());
}
Example 89
Project: spring-framework-master  File: ExchangeFilterFunctions.java View source code
private static String authorization(String username, String password) {
    String credentials = username + ":" + password;
    byte[] credentialBytes = credentials.getBytes(StandardCharsets.ISO_8859_1);
    byte[] encodedBytes = Base64.getEncoder().encode(credentialBytes);
    String encodedCredentials = new String(encodedBytes, StandardCharsets.ISO_8859_1);
    return "Basic " + encodedCredentials;
}
Example 90
Project: spring-session-master  File: HomePage.java View source code
public void terminateButtonDisabled() {
    Set<Cookie> cookies = getDriver().manage().getCookies();
    String cookieValue = null;
    for (Cookie cookie : cookies) {
        if ("SESSION".equals(cookie.getName())) {
            cookieValue = new String(Base64.getDecoder().decode(cookie.getValue()));
        }
    }
    WebElement element = getDriver().findElement(By.id("terminate-" + cookieValue));
    assertThat(element.isEnabled()).isFalse();
}
Example 91
Project: stash-hook-mirror-master  File: DefaultPasswordEncryptor.java View source code
@Override
public void init(PluginSettings pluginSettings) {
    try {
        String keyBase64;
        Object value = pluginSettings.get(SETTINGS_CRYPTO_KEY);
        if (value == null || value.toString().isEmpty()) {
            KeyGenerator gen = KeyGenerator.getInstance("AES");
            secretKey = gen.generateKey();
            keyBase64 = Base64.getEncoder().encodeToString(secretKey.getEncoded());
            pluginSettings.put(SETTINGS_CRYPTO_KEY, keyBase64);
        } else {
            keyBase64 = value.toString();
            byte[] data = Base64.getDecoder().decode(keyBase64);
            secretKey = new SecretKeySpec(data, 0, data.length, "AES");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
Example 92
Project: uaa-master  File: TokenKeyEndpointMockMvcTests.java View source code
@Test
public void checkTokenKeyValues() throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("app:appclientsecret").getBytes()));
    MvcResult result = getMockMvc().perform(get("/token_key").accept(MediaType.APPLICATION_JSON).header("Authorization", basicDigestHeaderValue)).andExpect(status().isOk()).andReturn();
    Map<String, Object> key = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class);
    validateKey(key);
}
Example 93
Project: user-master  File: CursorSerializerUtil.java View source code
/**
     * Turn the json node in to a base64 encoded SMILE binary
     */
public static String asString(final JsonNode node) {
    final byte[] output;
    try {
        output = MAPPER.writeValueAsBytes(node);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Unable to create output from json node " + node);
    }
    //generate a base64 url save string
    final String value = Base64.getUrlEncoder().encodeToString(output);
    return value;
}
Example 94
Project: usergrid-master  File: CursorSerializerUtil.java View source code
/**
     * Turn the json node in to a base64 encoded SMILE binary
     */
public static String asString(final JsonNode node) {
    final byte[] output;
    try {
        output = MAPPER.writeValueAsBytes(node);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Unable to create output from json node " + node);
    }
    //generate a base64 url save string
    final String value = Base64.getUrlEncoder().encodeToString(output);
    return value;
}
Example 95
Project: waffle-master  File: BasicSecurityFilterTests.java View source code
/**
     * Test basic auth.
     *
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     * @throws ServletException
     *             the servlet exception
     */
@Test
public void testBasicAuth() throws IOException, ServletException {
    final SimpleHttpRequest request = new SimpleHttpRequest();
    request.setMethod("GET");
    final String userHeaderValue = WindowsAccountImpl.getCurrentUsername() + ":password";
    final String basicAuthHeader = "Basic " + Base64.getEncoder().encodeToString(userHeaderValue.getBytes(StandardCharsets.UTF_8));
    request.addHeader("Authorization", basicAuthHeader);
    final SimpleHttpResponse response = new SimpleHttpResponse();
    final FilterChain filterChain = new SimpleFilterChain();
    this.filter.doFilter(request, response, filterChain);
    final Subject subject = (Subject) request.getSession(false).getAttribute("javax.security.auth.subject");
    Assert.assertNotNull(subject);
    Assertions.assertThat(subject.getPrincipals().size()).isGreaterThan(0);
}
Example 96
Project: zipkin-master  File: ScribeSpanConsumer.java View source code
@Override
public ListenableFuture<ResultCode> log(List<LogEntry> messages) {
    metrics.incrementMessages();
    List<byte[]> thrifts;
    try {
        thrifts = messages.stream().filter( m -> m.category.equals(category)).map( m -> m.message.getBytes(StandardCharsets.ISO_8859_1)).map(// finagle-zipkin uses mime encoding
         b -> Base64.getMimeDecoder().decode(b)).collect(Collectors.toList());
    } catch (RuntimeException e) {
        metrics.incrementMessagesDropped();
        return Futures.immediateFailedFuture(e);
    }
    SettableFuture<ResultCode> result = SettableFuture.create();
    collector.acceptSpans(thrifts, Codec.THRIFT, new Callback<Void>() {

        @Override
        public void onSuccess(@Nullable Void value) {
            result.set(ResultCode.OK);
        }

        @Override
        public void onError(Throwable t) {
            result.setException(t);
        }
    });
    return result;
}
Example 97
Project: gradle-master  File: Download.java View source code
/**
     * Base64 encode user info for HTTP Basic Authentication.
     *
     * Try to use {@literal java.util.Base64} encoder which is available starting with Java 8.
     * Fallback to {@literal javax.xml.bind.DatatypeConverter} from JAXB which is available starting with Java 6 but is not anymore in Java 9.
     * Fortunately, both of these two Base64 encoders implement the right Base64 flavor, the one that does not split the output in multiple lines.
     *
     * @param userInfo user info
     * @return Base64 encoded user info
     * @throws RuntimeException if no public Base64 encoder is available on this JVM
     */
private String base64Encode(String userInfo) {
    ClassLoader loader = getClass().getClassLoader();
    try {
        Method getEncoderMethod = loader.loadClass("java.util.Base64").getMethod("getEncoder");
        Method encodeMethod = loader.loadClass("java.util.Base64$Encoder").getMethod("encodeToString", byte[].class);
        Object encoder = getEncoderMethod.invoke(null);
        return (String) encodeMethod.invoke(encoder, new Object[] { userInfo.getBytes("UTF-8") });
    } catch (Exception java7OrEarlier) {
        try {
            Method encodeMethod = loader.loadClass("javax.xml.bind.DatatypeConverter").getMethod("printBase64Binary", byte[].class);
            return (String) encodeMethod.invoke(null, new Object[] { userInfo.getBytes("UTF-8") });
        } catch (Exception java5OrEarlier) {
            throw new RuntimeException("Downloading Gradle distributions with HTTP Basic Authentication is not supported on your JVM.", java5OrEarlier);
        }
    }
}
Example 98
Project: mobile-persistence-master  File: MCSManager.java View source code
public String login(String userName, String password, String mobileBackendId) {
    this.userName = userName;
    this.mobileBackendId = mobileBackendId;
    String userCredentials = userName + ":" + password;
    // for some strange reason the java.util.Base64, nor
    try {
        // oracle.adfmf.misc.Base64 nor java.util.Base64 does not encode correctly for some strange reason
        //      authHeader = "Basic " + Base64.encode(userCredentials.getBytes("UTF-8"));
        //      authHeader = "Basic " + Base64.getEncoder().encode(userCredentials.getBytes("UTF-8"));
        authHeader = "Basic " + new BASE64Encoder().encode(userCredentials.getBytes("UTF-8"));
        RestJSONPersistenceManager rpm = new RestJSONPersistenceManager();
        String result = rpm.invokeRestService(getConnectionName(), "GET", "/platform/users/login", null, getMCSHeaderParams(), 0, false);
        return result;
    } catch (UnsupportedEncodingException e) {
    } catch (Exception e) {
        authHeader = null;
        userName = null;
        throw e;
    }
    return null;
}
Example 99
Project: structr-master  File: Main.java View source code
public static void main(final String[] args) {
    String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");
    String initialPeer = "255.255.255.255";
    String bindAddress = "0.0.0.0";
    String privateKeyFile = null;
    String publicKeyFile = null;
    boolean printKeys = false;
    boolean isInteractive = false;
    boolean verbose = false;
    for (int i = 0; i < args.length; i++) {
        switch(args[i]) {
            case "-i":
                System.out.println("Interactive mode enabled.");
                isInteractive = true;
                break;
            case "-b":
                bindAddress = args[i + 1];
                System.out.println("Bind address set to " + bindAddress);
                break;
            case "-p":
                initialPeer = args[i + 1];
                System.out.println("Initial peer set to " + initialPeer);
                break;
            case "-v":
                verbose = true;
                System.out.println("Verbose mode enabled.");
                break;
            case "-u":
                uuid = args[i + 1];
                System.out.println("Client UUID set to " + uuid);
                break;
            case "--print-keys":
                printKeys = true;
                System.out.println("Printing peer keys.");
                break;
            case "--private-key-file":
                privateKeyFile = args[i + 1];
                System.out.println("Using private key from " + privateKeyFile);
                break;
            case "--public-key-file":
                publicKeyFile = args[i + 1];
                System.out.println("Using public key from " + publicKeyFile);
                break;
            case "-h":
                printHelp();
                System.exit(0);
                break;
        }
    }
    final DefaultRepository repo = new DefaultRepository(uuid);
    KeyPair keyPair = null;
    if (privateKeyFile != null && publicKeyFile != null) {
        try {
            final Decoder decoder = Base64.getDecoder();
            final byte[] privateKey = decoder.decode(readBase64(privateKeyFile));
            final byte[] publicKey = decoder.decode(readBase64(publicKeyFile));
            keyPair = KeyHelper.fromBytes("RSA", privateKey, publicKey);
        } catch (IOException ioex) {
            logger.warn("", ioex);
        }
    } else {
        keyPair = KeyHelper.getOrCreateKeyPair("RSA", 2048);
    }
    final Peer peer = new Peer(keyPair, repo, bindAddress, initialPeer);
    if (printKeys && keyPair != null) {
        final Encoder encoder = Base64.getEncoder();
        System.out.println("Private key (BASE64 encoded): " + encoder.encodeToString(keyPair.getPrivate().getEncoded()));
        System.out.println("Public key (BASE64 encoded):  " + encoder.encodeToString(keyPair.getPublic().getEncoded()));
    }
    repo.setPeer(peer);
    peer.setVerbose(verbose);
    peer.initializeServer();
    peer.start();
    if (isInteractive) {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        do {
            try {
                System.out.print(peer.getLocalPort() + "> ");
                line = reader.readLine();
                final String[] parts = line.split("[ ]+");
                final String cmd = parts[0];
                switch(cmd) {
                    case "exit":
                        peer.stop();
                        break;
                    case "i":
                        peer.printInfo();
                        break;
                    case "kill":
                        peer.broadcast(new BroadcastMessage(peer.getUuid(), "kill"));
                        break;
                    case "info":
                        peer.broadcast(new BroadcastMessage(peer.getUuid(), "info"));
                        break;
                    case "span":
                        peer.broadcast(new BroadcastMessage(peer.getUuid(), "span"));
                        break;
                    case "msg":
                        if (parts.length < 3) {
                            System.out.println("usage: msg <peer> <message>");
                            break;
                        }
                        peer.broadcast(new DirectMessage(peer.getUuid(), parts[1], parts[2]));
                        break;
                    case "broadcast":
                        if (parts.length < 2) {
                            System.out.println("usage: broadcast <message>");
                            break;
                        }
                        peer.broadcast(new BroadcastMessage(peer.getUuid(), parts[1]));
                        break;
                    case "ping":
                        if (parts.length < 2) {
                            System.out.println("usage: ping <peer>");
                            break;
                        }
                        peer.broadcast(new DirectMessage(peer.getUuid(), parts[1], "ping"));
                        break;
                    case "new":
                        if (parts.length < 3) {
                            System.out.println("usage: new <type> <owner> [<key> <value>]...");
                            break;
                        }
                        final Map<String, Object> map = new HashMap<>();
                        String key = null;
                        for (int i = 3; i < parts.length; i++) {
                            if (key == null) {
                                key = parts[i];
                            } else {
                                System.out.println(key + " = " + parts[i]);
                                map.put(key, parts[i]);
                                key = null;
                            }
                        }
                        repo.create(UUID.randomUUID().toString().replaceAll("\\-", ""), parts[1], peer.getUuid(), parts[2], peer.getPseudoTemporalEnvironment().next(), map);
                        break;
                    case "get":
                        if (parts.length < 3) {
                            System.out.println("usage: get <id> <key>");
                            break;
                        }
                        peer.get(parts[1], parts[2]);
                        break;
                    case "set":
                        if (parts.length < 4) {
                            System.out.println("usage: set <id> <key> <value>");
                            break;
                        }
                        peer.set(parts[1], parts[2], parts[3]);
                        break;
                }
            } catch (Throwable t) {
                logger.warn("", t);
            }
        } while (peer.isRunning() && !line.equals("quit"));
        peer.stop();
    }
}
Example 100
Project: acteur-master  File: BasicCredentials.java View source code
public static BasicCredentials parse(String header) {
    Matcher m = HEADER.matcher(header);
    if (m.matches()) {
        String base64 = m.group(1);
        //            byte[] decoded = Base64.getDecoder().decode(base64);
        //            String s = new String(decoded, UTF_8);
        byte[] bytes = base64.getBytes(UTF_8);
        if (Base64.isArrayByteBase64(bytes)) {
            bytes = Base64.decodeBase64(bytes);
        }
        String s = new String(bytes, US_ASCII);
        m = UNPW.matcher(s);
        if (m.matches()) {
            String username = m.group(1);
            String password = m.group(2);
            return new BasicCredentials(username, password);
        }
    }
    return null;
}
Example 101
Project: Cardshifter-master  File: ClientWebSocket.java View source code
@Override
protected void onSendToClient(Message message) {
    if (!conn.isOpen()) {
        this.disconnected();
        return;
    }
    String data;
    try {
        if (knownBase64client == null) {
            logger.error("It is not yet known whether or not client is Base64 or JSON, " + "ignoring sending of " + message + " to " + this);
            return;
        }
        if (knownBase64client) {
            byte[] bytes = transformer.transform(message);
            data = Base64Utils.toBase64(bytes);
            logger.info("Sending to client: " + message + " - " + Arrays.toString(bytes));
            conn.send(data);
        } else {
            try {
                data = jsonMapper.writeValueAsString(message);
                logger.info("Sending to client: " + message + " - " + data);
                conn.send(data);
            } catch (JsonProcessingException e) {
                throw new CardshifterSerializationException(e);
            }
        }
    } catch (CardshifterSerializationException e) {
        throw new RuntimeException("Error serializing message " + message + " to " + this, e);
    } catch (WebsocketNotConnectedException ex) {
        this.disconnected();
        logger.error("Websocket not connected: " + this, ex);
    }
}