Example usage for org.apache.commons.codec.binary Base64 encodeBase64String

List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64String

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 encodeBase64String.

Prototype

public static String encodeBase64String(final byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm but does not chunk the output.

Usage

From source file:bobs.mcapisignature.UtilsTest.java

/**
 * Test of certToBytes method, of class Utils.
 *///from w w  w  .j  av a 2  s.com
@Test
public void testCertToBytes() {
    System.out.println("certToBytes");
    String Sha1Hash = testCertHash;
    Structures.CERT_CONTEXT cert = CertUtils.findCertByHash(Sha1Hash);
    String expResult = "MIICdDCCAd2gAwIBAgIBCDANBgkqhkiG9w0BAQQFADBdMQswCQYDVQQGEwJCRzEOMAwGA1UECBMFU29maWExDjAMBgNVBAcTBVNvZmlhMQ0wCwYDVQQKEwRCT0JTMQ0wCwYDVQQLEwRCT0JTMRAwDgYDVQQDFAdOQ1NQX0NBMB4XDTE1MTEwNTEzNTYwMFoXDTI1MTEwMjEzNTYwMFowZjELMAkGA1UEBhMCQkcxDjAMBgNVBAgTBVNvZmlhMQ4wDAYDVQQHEwVTb2ZpYTENMAsGA1UEChMEQk9CUzENMAsGA1UECxMEQk9CUzEZMBcGA1UEAxMQRGV0ZWxpbiBFdmxvZ2lldjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA4QsnBBknuVTsBIKQA0zlMNA8/0sC+Yh/SLUDWFnMDZyNlxT3sqbk6QgYNtVBM7YIunjiZYKPWtnANrGCx/RSa8ojAJVQLnessxt9nTscqZTTZ2yqqBsM2fFwjtuCW4+qaME7BhQNeEl1Mjj93S02BwSQO1ympTmhsq3/iAMVkbkCAwEAAaM7MDkwHwYDVR0jBBgwFoAUQnIlUNt5M++LuyqsFVyoufSHIwUwCQYDVR0TBAIwADALBgNVHQ8EBAMCBPAwDQYJKoZIhvcNAQEEBQADgYEASOWzwIakf3y0lwRyxI+kk5QEFrRvQF9Ae+0zBfdANEy4y4ApwuQgGk8JcrP+r77HlMHZ9XAFzzL2U19OBPLCiGOqlBDtF4+uoGVk8LCl3eAsA3gQh1k/euMFDxaYkSuHzev2CufOULiMxyg2vcyqKm4SfX1fuMgecmyRbBJL4jc=";
    byte[] result = CertUtils.certToBytes(cert);
    String res = Base64.encodeBase64String(result);
    System.out.println(res);
    assertEquals(expResult, res);

}

From source file:flow.visibility.tapping.OpenDayLightUtils.java

/** The function for inserting the flow */

public static void FlowEntry(String ODPURL, String ODPAccount, String ODPPassword) throws Exception {

    //String user = "admin";
    //String password = "admin";
    String baseURL = "http://" + ODPURL + "/controller/nb/v2/flowprogrammer";
    String containerName = "default";

    /** Check the connection for ODP REST API */

    try {/*  w  w  w .j  a  v  a 2 s  . co m*/

        // Create URL = base URL + container
        URL url = new URL(baseURL + "/" + containerName);

        // Create authentication string and encode it to Base64
        String authStr = ODPAccount + ":" + ODPPassword;
        String encodedAuthStr = Base64.encodeBase64String(authStr.getBytes());

        // Create Http connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // Set connection properties
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
        connection.setRequestProperty("Accept", "application/json");

        // Get the response from connection's inputStream
        InputStream content = (InputStream) connection.getInputStream();

        /** The create the frame and blank pane */
        OpenDayLightUtils object = new OpenDayLightUtils();
        object.setVisible(true);

        /** Read the Flow entry in JSON Format */
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line = "";

        /** Print line by line in Pane with Pretty JSON */
        while ((line = in.readLine()) != null) {

            JSONParser jsonParser = new JSONParser();
            JSONObject jsonObject = (JSONObject) jsonParser.parse(line);

            Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
            String json = gson.toJson(jsonObject);
            System.out.println(json);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.teamgrit.grit.util.mailer.EncryptorDecryptor.java

/**
 * Encrypts a given string.//from w ww.  j a  va2  s.c o  m
 * 
 * @param stringToEncrypt
 *            : this is the string that shall be encrypted.
 * @return : the encrypted String or null in case of fail. : when
 *         encrypting fails.
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public String encrypt(String stringToEncrypt) throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    // get cryptographic cipher with the requested transformation, AES
    // (advanced encryption standard) algorithm with ECB (electronic
    // code book) mode and PKCS5Padding (schema to pad cleartext to be
    // multiples of 8-byte blocks) padding.
    Cipher cipher;

    cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");

    // use the provided secret key for encryption using AES
    final SecretKeySpec secretKey = new SecretKeySpec(m_key, "AES");

    // initialize cryptographic cipher with encryption mode
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    // encode the encrypted string in base 64
    final String encryptedString = Base64.encodeBase64String(cipher.doFinal(stringToEncrypt.getBytes()));
    return encryptedString;
}

From source file:io.apiman.gateway.platforms.vertx3.verticles.ApiVerticle.java

public void authenticateBasic(JsonObject authInfo, Handler<AsyncResult<User>> resultHandler) {
    String username = authInfo.getString("username");
    String password = StringUtils
            .chomp(Base64.encodeBase64String(DigestUtils.sha256(authInfo.getString("password")))); // Chomp, Digest, Base64Encode
    String storedPassword = apimanConfig.getBasicAuthCredentials().get(username);

    if (storedPassword != null && password.equals(storedPassword)) {
        resultHandler.handle(Future.<User>succeededFuture(null));
    } else {/*from  ww w .  ja va 2 s.c o m*/
        resultHandler.handle(Future.<User>failedFuture("Not such user, or password is incorrect."));
    }
}

From source file:com.constellio.app.modules.es.connectors.smb.security.WindowsPermissions.java

private void computePermissionsHash() {
    MessageDigest md;//  ww w . j a va  2 s .  com
    try {
        md = MessageDigest.getInstance("MD5");

        update(md, allowTokenDocument);
        update(md, denyTokenDocument);
        update(md, allowTokenShare);
        update(md, denyTokenShare);

        permissionsHash = Base64.encodeBase64String(md.digest());

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

From source file:com.google.nigori.server.appengine.AEUser.java

@Override
public String getName() {
    return Base64.encodeBase64String(getPublicHash());
}

From source file:de.alpharogroup.crypto.key.PrivateKeyExtensions.java

/**
 * Transform the given {@link PrivateKey} to a base64 encoded {@link String} value.
 *
 * @param privateKey/*from ww w .  j a v a  2  s.c o m*/
 *            the private key
 * @return the new base64 encoded {@link String} value.
 */
public static String toBase64(final PrivateKey privateKey) {
    final byte[] encoded = privateKey.getEncoded();
    final String privateKeyAsBase64String = Base64.encodeBase64String(encoded);
    return privateKeyAsBase64String;
}

From source file:net.officefloor.plugin.web.http.security.store.JndiLdapCredentialStoreTest.java

/**
 * Ensure correct credentials./*  w w  w.j a v a 2s  .  co  m*/
 */
@SuppressWarnings("unchecked")
public void testCredentials() throws Exception {

    // Create the expected credentials
    final String expectedRaw = "daniel:officefloor:password";
    MessageDigest digest = MessageDigest.getInstance("MD5");
    digest.update(expectedRaw.getBytes(US_ASCII));
    final byte[] expectedCredentials = digest.digest();

    // Obtain the encoded credentials
    final String encodedCredentials = Base64.encodeBase64String(expectedCredentials).trim();
    assertEquals("Incorrect encoded credentials", "msu723GSLovbwuaPnaLcnQ==", encodedCredentials);

    // Mocks
    final NamingEnumeration<SearchResult> searchResults = this.createMock(NamingEnumeration.class);
    final Attributes attributes = this.createMock(Attributes.class);
    final Attribute attribute = this.createMock(Attribute.class);
    final NamingEnumeration<?> userPasswords = this.createMock(NamingEnumeration.class);

    // Objects
    final SearchResult searchResult = new SearchResult("uid=daniel", null, attributes);
    searchResult.setNameInNamespace("uid=daniel,ou=People,dc=officefloor,dc=net");

    // Record
    this.recordReturn(this.context, this.context.search("ou=People,dc=officefloor,dc=net",
            "(&(objectClass=inetOrgPerson)(uid=daniel))", null), searchResults);
    this.recordReturn(searchResults, searchResults.hasMore(), true);
    this.recordReturn(searchResults, searchResults.next(), searchResult);
    this.recordReturn(this.context, this.context.getAttributes("uid=daniel,ou=People,dc=officefloor,dc=net"),
            attributes);
    this.recordReturn(attributes, attributes.get("userPassword"), attribute);
    this.recordReturn(attribute, attribute.getAll(), userPasswords);
    this.recordReturn(userPasswords, userPasswords.hasMore(), true);
    this.recordReturn(userPasswords, userPasswords.next(), "Plain Text Password".getBytes(US_ASCII));
    this.recordReturn(userPasswords, userPasswords.hasMore(), true);
    this.recordReturn(userPasswords, userPasswords.next(), ("{MD5}" + encodedCredentials).getBytes(US_ASCII));

    // Test
    this.replayMockObjects();
    CredentialEntry entry = this.store.retrieveCredentialEntry("daniel", "REALM");
    byte[] actualCredentials = entry.retrieveCredentials();
    this.verifyMockObjects();

    // Validate correct value
    assertEquals("Incorrect credential byte length", expectedCredentials.length, actualCredentials.length);
    for (int i = 0; i < expectedCredentials.length; i++) {
        assertEquals("Incorrect credential byte " + i, expectedCredentials[i], actualCredentials[i]);
    }
}

From source file:de.bps.webservices.clients.onyxreporter.HashMapWrapper.java

/**
 * Serializes the given object o and encodes the result as non-chunked base64.
 * /*  ww w  .  j  a va 2s  .c om*/
 * @param objectToSerializeAndEncode
 * @return
 * @throws OnyxReporterException
 */
private static final String serialize(final Object objectToSerializeAndEncode) throws OnyxReporterException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(baos);
        oos.writeObject(objectToSerializeAndEncode);
        oos.close();
        oos = null;
        return Base64.encodeBase64String(baos.toByteArray());
    } catch (final IOException e) {
        throw new OnyxReporterException("Could not serialize object!", e);
    } finally {
        try {
            if (oos != null) {
                oos.close();
            }
        } catch (final IOException e) {
        }
    }
}

From source file:db.dao.Dao.java

public JSONArray listAllHttpClient(String url) {
    url = checkIfLocal(url);//from ww  w  . ja  v  a 2 s . co  m
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet getRequest = new HttpGet(url);
    String usernamepassword = "Pepijn:Mores";
    String encoded = Base64.encodeBase64String(usernamepassword.getBytes());
    getRequest.addHeader("accept", "application/json");
    getRequest.setHeader("Authorization", encoded);
    ;
    HttpResponse response = null;

    try {
        response = client.execute(getRequest);
    } catch (IOException ex) {
        Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }
    JSONArray json = null;
    try (BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
        String inputLine;
        StringBuilder responseString = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            responseString.append(inputLine);
        }
        json = new JSONArray(responseString.toString());
    } catch (IOException ex) {
        Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex);
    } catch (JSONException ex) {
        Logger.getLogger(Dao.class.getName()).log(Level.SEVERE, null, ex);
    }
    return json;
}