Example usage for org.apache.commons.net.util Base64 decodeBase64

List of usage examples for org.apache.commons.net.util Base64 decodeBase64

Introduction

In this page you can find the example usage for org.apache.commons.net.util Base64 decodeBase64.

Prototype

public static byte[] decodeBase64(byte[] base64Data) 

Source Link

Document

Decodes Base64 data into octets

Usage

From source file:de.burlov.ultracipher.core.mail.AuthenticatingSMTPClient.java

/**
 * Authenticate to the SMTP server by sending the AUTH command with the
 * selected mechanism, using the given username and the given password.
 * <p/>//from   w ww  . jav a2 s .c  om
 *
 * @return True if successfully completed, false if not.
 * @throws SMTPConnectionClosedException              If the SMTP server prematurely closes the connection as a
 *                                                    result of the client being idle or some other reason
 *                                                    causing the server to send SMTP reply code 421. This
 *                                                    exception may be caught either as an IOException or
 *                                                    independently as itself.
 * @throws java.io.IOException                        If an I/O error occurs while either sending a command to
 *                                                    the server or receiving a reply from the server.
 * @throws java.security.NoSuchAlgorithmException     If the CRAM hash algorithm cannot be instantiated by the
 *                                                    Java runtime system.
 * @throws java.security.InvalidKeyException          If the CRAM hash algorithm failed to use the given
 *                                                    password.
 * @throws java.security.spec.InvalidKeySpecException If the CRAM hash algorithm failed to use the given
 *                                                    password.
 *                                                    *
 */
public boolean auth(AUTH_METHOD method, String username, String password)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    if (!SMTPReply.isPositiveIntermediate(sendCommand(SMTPCommand.AUTH, AUTH_METHOD.getAuthName(method)))) {
        return false;
    }

    if (method.equals(AUTH_METHOD.PLAIN)) {
        // the server sends an empty response ("334 "), so we don't have to
        // read it.
        return SMTPReply.isPositiveCompletion(sendCommand(
                new String(Base64.encodeBase64(("\000" + username + "\000" + password).getBytes()))));
    } else if (method.equals(AUTH_METHOD.CRAM_MD5)) {
        // get the CRAM challenge
        byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(4).trim());
        // get the Mac instance
        Mac hmac_md5 = Mac.getInstance("HmacMD5");
        hmac_md5.init(new SecretKeySpec(password.getBytes(), "HmacMD5"));
        // compute the result:
        byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes();
        // join the byte arrays to form the reply
        byte[] usernameBytes = username.getBytes();
        byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
        System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
        toEncode[usernameBytes.length] = ' ';
        System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
        // send the reply and read the server code:
        return SMTPReply.isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(toEncode))));
    } else if (method.equals(AUTH_METHOD.LOGIN)) {
        // the server sends fixed responses (base64("Username") and
        // base64("Password")), so we don't have to read them.
        if (!SMTPReply
                .isPositiveIntermediate(sendCommand(new String(Base64.encodeBase64(username.getBytes()))))) {
            return false;
        }
        return SMTPReply
                .isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(password.getBytes()))));
    } else {
        return false; // safety check
    }
}

From source file:com.ibm.iotf.sample.devicemgmt.device.DeviceInitiatedHandlerSample.java

/**
 * If the output of checkAndSetFirmware() is true, then Firmware Download is initiated
 * by passing the Cloudant Document ID of the latest firmware to downloadFromCloudant().
 * The method reads the contents of the Cloudant Document and writes it to a file on the
 * local file system. If it encounters issues while writing to a file, then, it raises
 * exception.//w w w .java 2 s  .  c  om
*/

public void downloadFromCloudant() {

    try {
        Foo foo = firmwareDB.find(Foo.class, docId, new Params().attachments());
        String attachmentData = foo.getAttachments().get(getLatestFirmware()).getData();
        String bytes = attachmentData;
        byte[] buffer = Base64.decodeBase64(bytes);
        FileOutputStream outputStream = new FileOutputStream(getLatestFirmware());
        outputStream.write(buffer);
        outputStream.close();
        System.out.println("Completed Restoration of Cloudant Document ID " + docId
                + " into the Debian package " + getLatestFirmware());

    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        System.out.println("Error writing to the Debian package" + getLatestFirmware());
    }
}

From source file:dpfmanager.shell.modules.server.post.HttpPostHandler.java

private void parseAttributeData(Attribute attribute) throws IOException {
    String name = attribute.getName();
    if (name.equals("id")) {
        id = Long.parseLong(attribute.getValue());
    } else if (name.equals("config")) {
        destFolder = createNewDirectory(uuid);
        String encoded = attribute.getValue();
        String decoded = new String(Base64.decodeBase64(encoded), "UTF-8");
        File dest = new File(destFolder.getAbsolutePath() + "/config.dpf");
        configpath = dest.getAbsolutePath();
        FileUtils.writeStringToFile(dest, decoded);
    }//from  w  ww. j a  va  2  s  .  c  om
}

From source file:io.hops.hopsworks.common.util.HopsUtils.java

/**
 *
 * @param key// www.java2 s . c o m
 * @param ciphertext
 * @return
 * @throws Exception
 */
public static String decrypt(String key, String ciphertext, String masterEncryptionPassword) throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    Key aesKey = generateKey(key, masterEncryptionPassword);
    cipher.init(Cipher.DECRYPT_MODE, aesKey);
    String decrypted = new String(cipher.doFinal(Base64.decodeBase64(ciphertext)));
    return decrypted;
}

From source file:org.apache.kudu.mapreduce.KuduTableInputFormat.java

@Override
public void setConf(Configuration entries) {
    this.conf = new Configuration(entries);

    String tableName = conf.get(INPUT_TABLE_KEY);
    String masterAddresses = conf.get(MASTER_ADDRESSES_KEY);
    this.operationTimeoutMs = conf.getLong(OPERATION_TIMEOUT_MS_KEY,
            AsyncKuduClient.DEFAULT_OPERATION_TIMEOUT_MS);
    this.client = new KuduClient.KuduClientBuilder(masterAddresses)
            .defaultOperationTimeoutMs(operationTimeoutMs).build();
    KuduTableMapReduceUtil.importCredentialsFromCurrentSubject(client);
    this.nameServer = conf.get(NAME_SERVER_KEY);
    this.cacheBlocks = conf.getBoolean(SCAN_CACHE_BLOCKS, false);

    try {/*w  ww . ja  va2s  . c  om*/
        this.table = client.openTable(tableName);
    } catch (Exception ex) {
        throw new RuntimeException("Could not obtain the table from the master, "
                + "is the master running and is this table created? tablename=" + tableName + " and "
                + "master address= " + masterAddresses, ex);
    }

    String projectionConfig = conf.get(COLUMN_PROJECTION_KEY);
    if (projectionConfig == null || projectionConfig.equals("*")) {
        this.projectedCols = null; // project the whole table
    } else if ("".equals(projectionConfig)) {
        this.projectedCols = new ArrayList<>();
    } else {
        this.projectedCols = Lists.newArrayList(Splitter.on(',').split(projectionConfig));

        // Verify that the column names are valid -- better to fail with an exception
        // before we submit the job.
        Schema tableSchema = table.getSchema();
        for (String columnName : projectedCols) {
            if (tableSchema.getColumn(columnName) == null) {
                throw new IllegalArgumentException("Unknown column " + columnName);
            }
        }
    }

    this.predicates = new ArrayList<>();
    try {
        InputStream is = new ByteArrayInputStream(Base64.decodeBase64(conf.get(ENCODED_PREDICATES_KEY, "")));
        while (is.available() > 0) {
            this.predicates.add(
                    KuduPredicate.fromPB(table.getSchema(), Common.ColumnPredicatePB.parseDelimitedFrom(is)));
        }
    } catch (IOException e) {
        throw new RuntimeException("unable to deserialize predicates from the configuration", e);
    }
}

From source file:org.apache.tajo.storage.json.JsonLineDeserializer.java

/**
 *
 *
 * @param object/*from  ww w.  j  a  v a 2 s  .  c om*/
 * @param pathElements
 * @param depth
 * @param fieldIndex
 * @param output
 * @throws IOException
 */
private void getValue(JSONObject object, String fullPath, String[] pathElements, int depth, int fieldIndex,
        Tuple output) throws IOException {
    String fieldName = pathElements[depth];

    if (!object.containsKey(fieldName)) {
        output.put(fieldIndex, NullDatum.get());
    }

    switch (types.get(fullPath)) {
    case BOOLEAN:
        String boolStr = object.getAsString(fieldName);
        if (boolStr != null) {
            output.put(fieldIndex, DatumFactory.createBool(boolStr.equals("true")));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case CHAR:
        String charStr = object.getAsString(fieldName);
        if (charStr != null) {
            output.put(fieldIndex, DatumFactory.createChar(charStr));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case INT1:
    case INT2:
        Number int2Num = object.getAsNumber(fieldName);
        if (int2Num != null) {
            output.put(fieldIndex, DatumFactory.createInt2(int2Num.shortValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case INT4:
        Number int4Num = object.getAsNumber(fieldName);
        if (int4Num != null) {
            output.put(fieldIndex, DatumFactory.createInt4(int4Num.intValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case INT8:
        Number int8Num = object.getAsNumber(fieldName);
        if (int8Num != null) {
            output.put(fieldIndex, DatumFactory.createInt8(int8Num.longValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case FLOAT4:
        Number float4Num = object.getAsNumber(fieldName);
        if (float4Num != null) {
            output.put(fieldIndex, DatumFactory.createFloat4(float4Num.floatValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case FLOAT8:
        Number float8Num = object.getAsNumber(fieldName);
        if (float8Num != null) {
            output.put(fieldIndex, DatumFactory.createFloat8(float8Num.doubleValue()));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case TEXT:
        String textStr = object.getAsString(fieldName);
        if (textStr != null) {
            output.put(fieldIndex, DatumFactory.createText(textStr));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case TIMESTAMP:
        String timestampStr = object.getAsString(fieldName);
        if (timestampStr != null) {
            output.put(fieldIndex, DatumFactory.createTimestamp(timestampStr, timezone));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case TIME:
        String timeStr = object.getAsString(fieldName);
        if (timeStr != null) {
            output.put(fieldIndex, DatumFactory.createTime(timeStr));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case DATE:
        String dateStr = object.getAsString(fieldName);
        if (dateStr != null) {
            output.put(fieldIndex, DatumFactory.createDate(dateStr));
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;
    case BIT:
    case BINARY:
    case VARBINARY:
    case BLOB: {
        Object jsonObject = object.getAsString(fieldName);

        if (jsonObject == null) {
            output.put(fieldIndex, NullDatum.get());
            break;
        }

        output.put(fieldIndex, DatumFactory.createBlob(Base64.decodeBase64((String) jsonObject)));
        break;
    }

    case RECORD:
        JSONObject nestedObject = (JSONObject) object.get(fieldName);
        if (nestedObject != null) {
            getValue(nestedObject, fullPath + "/" + pathElements[depth + 1], pathElements, depth + 1,
                    fieldIndex, output);
        } else {
            output.put(fieldIndex, NullDatum.get());
        }
        break;

    case NULL_TYPE:
        output.put(fieldIndex, NullDatum.get());
        break;

    default:
        throw new TajoRuntimeException(
                new NotImplementedException("" + types.get(fullPath).name() + " for json"));
    }
}

From source file:org.jevis.rest.Config.java

public static JEVisDataSource getJEVisDS(HttpHeaders httpHeaders) throws AuthenticationException {
    if (httpHeaders.getRequestHeader("authorization") == null
            || httpHeaders.getRequestHeader("authorization").isEmpty()) {
        throw new AuthenticationException("Authorization header is missing");
    }//from   w  ww  . j a v  a2  s .c  o m
    String auth = httpHeaders.getRequestHeader("authorization").get(0);
    if (auth != null && !auth.isEmpty()) {
        auth = auth.replaceFirst("[Bb]asic ", "");

        System.out.println("Auth: '" + auth + "'");
        byte[] decoded2 = DatatypeConverter.parseBase64Binary(auth);
        //            if (Base64.isBase64(auth.getBytes())) {
        byte[] decoded = Base64.decodeBase64(auth);
        String debugFuck = ("1: " + Arrays.toString(decoded2) + "\n" + "2: " + Arrays.toString(decoded) + "\n"
                + "Equal: " + Arrays.equals(decoded, decoded2));

        try {
            //InitialContext()
            String decodeS = (new String(decoded, "UTF-8"));
            String decodeS2 = (new String(decoded));

            //                String decodeS = (new String(decoded, "UTF-8") + "\n");
            String[] dauth = decodeS.split(":");
            if (dauth.length == 2) {

                String username = dauth[0];
                String password = dauth[1];
                //                    String username = "Sys Admin";
                //                    String password = "OpenJEVis2016";

                System.out.println("Username: '" + username + "'   PW: '" + password + "'");
                try {
                    JEVisDataSource ds = Config.getDS(username, password);

                    try {
                        if (ds.connect(username, password)) {
                            return ds;
                        } else {
                            //                                throw new AuthenticationException("Username/Password is not correct.1");
                            throw ErrorBuilder.ErrorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), 2001,
                                    "Username/Password is not correct.");
                        }
                    } catch (JEVisException jex) {
                        throw ErrorBuilder.ErrorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), 2002,
                                "Username/Password is not correct.");
                    }

                } catch (JEVisException ex) {
                    //                        throw new AuthenticationException("Could not connect to Database:\n" + ex);
                    throw ErrorBuilder.ErrorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), 2001,
                            "Username/Password is not correct.");
                }
            } else {
                //                    throw new AuthenticationException("The HTML authorization header is not correct formate");
                throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2002,
                        "The HTML authorization header is not correct formate");
            }
        } catch (UnsupportedEncodingException uee) {
            //                throw new AuthenticationException("The HTML authorization header is not in Base64");
            throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2003,
                    "The HTML authorization header is not in Base64");
        }
        //            } else {
        //                throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2003, "The HTML authorization header is not in Base64");
        //            }
    } else {
        //            throw new AuthenticationException("The HTML authorization header is missing or emty");
        throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2004,
                "The HTML authorization header is missing or emty");
    }

}

From source file:org.kududb.mapreduce.KuduTableInputFormat.java

@Override
public void setConf(Configuration entries) {
    this.conf = new Configuration(entries);

    String tableName = conf.get(INPUT_TABLE_KEY);
    String masterAddresses = conf.get(MASTER_ADDRESSES_KEY);
    this.operationTimeoutMs = conf.getLong(OPERATION_TIMEOUT_MS_KEY,
            AsyncKuduClient.DEFAULT_OPERATION_TIMEOUT_MS);
    this.nameServer = conf.get(NAME_SERVER_KEY);
    this.cacheBlocks = conf.getBoolean(SCAN_CACHE_BLOCKS, false);

    this.client = new KuduClient.KuduClientBuilder(masterAddresses)
            .defaultOperationTimeoutMs(operationTimeoutMs).build();
    try {/* w ww  . ja v a2 s.  co  m*/
        this.table = client.openTable(tableName);
    } catch (Exception ex) {
        throw new RuntimeException("Could not obtain the table from the master, "
                + "is the master running and is this table created? tablename=" + tableName + " and "
                + "master address= " + masterAddresses, ex);
    }

    String projectionConfig = conf.get(COLUMN_PROJECTION_KEY);
    if (projectionConfig == null || projectionConfig.equals("*")) {
        this.projectedCols = null; // project the whole table
    } else if ("".equals(projectionConfig)) {
        this.projectedCols = new ArrayList<>();
    } else {
        this.projectedCols = Lists.newArrayList(Splitter.on(',').split(projectionConfig));

        // Verify that the column names are valid -- better to fail with an exception
        // before we submit the job.
        Schema tableSchema = table.getSchema();
        for (String columnName : projectedCols) {
            if (tableSchema.getColumn(columnName) == null) {
                throw new IllegalArgumentException("Unknown column " + columnName);
            }
        }
    }

    String encodedPredicates = conf.get(ENCODED_COLUMN_RANGE_PREDICATES_KEY, "");
    rawPredicates = Base64.decodeBase64(encodedPredicates);
}

From source file:org.openbmp.db_rest.helpers.AuthenticationService.java

public boolean authenticate(String authCredentials) {

    if (null == authCredentials)
        return false;
    // header value format will be "Basic encodedstring" for Basic
    // authentication. Example "Basic YWRtaW46YWRtaW4="
    final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
    String usernameAndPassword = null;
    try {//from w  ww.  ja  v  a2  s  . c  o  m
        byte[] decodedBytes = Base64.decodeBase64(encodedUserPassword);
        usernameAndPassword = new String(decodedBytes, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
    final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
    final String username = tokenizer.nextToken();
    final String password = tokenizer.nextToken();

    // we have fixed the userid and password as admin
    // call some UserService/LDAP here

    StringBuilder query = new StringBuilder();

    query.append("SELECT * FROM users\n");
    query.append("WHERE username=\"" + username + "\" AND password=PASSWORD(\"" + password + "\")\n");

    Map map = DbUtils.select_DbToMap(mysql_ds, query.toString());
    boolean authenticationStatus = map.size() > 0;

    return authenticationStatus;
}

From source file:org.openhab.binding.max.internal.command.SCommandTest.java

@Test
public void BaseCommandTest() {
    SCommand scmd = new SCommand("0b0da3", 1, ThermostatModeType.MANUAL, 20.0);

    String commandStr = scmd.getCommandString();

    String base64Data = commandStr.substring(3);
    byte[] bytes = Base64.decodeBase64(base64Data.getBytes());

    int[] data = new int[bytes.length];

    for (int i = 0; i < bytes.length; i++) {
        data[i] = bytes[i] & 0xFF;/* w  ww.j  a  v a  2 s.  c o  m*/
    }

    String decodedString = Utils.toHex(data);
    assertEquals("s:AARAAAAACw2jAWg=\r\n", commandStr);
    assertEquals("011000000002C368C05A", decodedString);
}