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

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

Introduction

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

Prototype

public Base64(final int lineLength) 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:com.buddycloud.mediaserver.update.UpdateAvatarTest.java

@Test
public void anonymousSuccessfulUpdateParamAuth() throws Exception {
    // file fields
    String title = "New Avatar";
    String description = "New Avatar Description";

    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    ClientResource client = new ClientResource(URL + "?auth=" + new String(encoder.encode(authStr.getBytes())));

    Form form = createWebForm(null, title, description, null, null);

    Representation result = client.post(form);
    Media media = gson.fromJson(result.getText(), Media.class);

    // verify if resultant media has the passed attributes
    assertEquals(title, media.getTitle());
    assertEquals(description, media.getDescription());
}

From source file:com.netcrest.pado.internal.security.AESCipher.java

public static String decryptUserTextToText(String encryptedText) throws Exception {
    if (encryptedText == null) {
        return null;
    }// w  w  w.  ja v  a 2  s.c  o  m
    Base64 base64 = new Base64(0); // no line breaks
    byte[] e = base64.decode(encryptedText);
    return decryptUserBinaryToText(e);
}

From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java

private String createPemCertificate(X509Certificate certificate) throws CertificateException {
    final StringBuilder sb = new StringBuilder();
    final Base64 b64 = new Base64(64);

    sb.append("-----BEGIN CERTIFICATE-----\r\n");
    sb.append(b64.encodeToString(certificate.getEncoded()));
    sb.append("-----END CERTIFICATE-----\r\n");
    return sb.toString();
}

From source file:com.buddycloud.mediaserver.upload.UploadMediaTest.java

@Test
public void uploadMultipartFormDataImageParamAuth() throws Exception {
    // file fields
    String title = "Test Image";
    String description = "My Test Image";

    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    ClientResource client = new ClientResource(
            BASE_URL + "/" + BASE_CHANNEL + "?auth=" + new String(encoder.encode(authStr.getBytes())));

    FormDataSet form = createFormData(TEST_IMAGE_NAME, title, description, TEST_FILE_PATH + TEST_IMAGE_NAME,
            TEST_IMAGE_CONTENT_TYPE);/*from   w  ww .ja  v  a  2  s. co  m*/

    Representation result = client.post(form);
    Media media = gson.fromJson(result.getText(), Media.class);

    // verify if resultant media has the passed attributes
    assertEquals(TEST_IMAGE_NAME, media.getFileName());
    assertEquals(title, media.getTitle());
    assertEquals(description, media.getDescription());
    assertEquals(BASE_USER, media.getAuthor());

    // delete metadata
    dataSource.deleteMedia(media.getId());
}

From source file:com.buddycloud.mediaserver.upload.UploadAvatarTest.java

@Test
public void uploadAvatarMultipartFormDataParamAuth() throws Exception {
    // file fields
    String title = "Test Avatar";
    String description = "My Test Avatar";

    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    ClientResource client = new ClientResource(BASE_URL + "/" + BASE_CHANNEL + "/avatar" + "?auth="
            + new String(encoder.encode(authStr.getBytes())));

    FormDataSet form = createFormData(TEST_AVATAR_NAME, title, description, TEST_FILE_PATH + TEST_AVATAR_NAME,
            TEST_AVATAR_CONTENT_TYPE);//  w ww .ja v a  2s . c  o  m

    Representation result = client.put(form);
    Media media = gson.fromJson(result.getText(), Media.class);

    // verify if resultant media has the passed attributes
    assertEquals(TEST_AVATAR_NAME, media.getFileName());
    assertEquals(title, media.getTitle());
    assertEquals(description, media.getDescription());
    assertEquals(BASE_USER, media.getAuthor());

    // delete metadata
    dataSource.deleteEntityAvatar(media.getEntityId());
    dataSource.deleteMedia(media.getId());
}

From source file:com.buddycloud.mediaserver.download.DownloadImageTest.java

@Test
public void downloadImagePreviewParamAuth() throws Exception {
    int height = 50;
    int width = 50;
    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    String completeUrl = URL + "?maxheight=" + height + "&maxwidth=" + width + "?auth="
            + new String(encoder.encode(authStr.getBytes()));

    ClientResource client = new ClientResource(completeUrl);

    File file = new File(TEST_OUTPUT_DIR + File.separator + "preview.jpg");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);//from w  w  w  .  j  a v  a2s.c  om

    Assert.assertTrue(file.exists());

    // Delete downloaded file
    FileUtils.deleteDirectory(new File(TEST_OUTPUT_DIR));
    outputStream.close();

    // Delete previews table row
    final String previewId = dataSource.getPreviewId(MEDIA_ID, height, width);
    dataSource.deletePreview(previewId);
}

From source file:com.buddycloud.mediaserver.download.DownloadVideoTest.java

@Test
public void downloadVideoPreviewParamAuth() throws Exception {
    int height = 50;
    int width = 50;
    Base64 encoder = new Base64(true);
    String authStr = BASE_USER + ":" + BASE_TOKEN;

    String completeUrl = URL + "?maxheight=" + height + "&maxwidth=" + width + "?auth="
            + new String(encoder.encode(authStr.getBytes()));

    ClientResource client = new ClientResource(completeUrl);

    File file = new File(TEST_OUTPUT_DIR + File.separator + "preview.jpg");
    FileOutputStream outputStream = FileUtils.openOutputStream(file);
    client.get().write(outputStream);/*from  ww w  .j  a  v  a  2 s .  c om*/

    Assert.assertTrue(file.exists());

    // Delete downloaded file
    FileUtils.deleteDirectory(new File(TEST_OUTPUT_DIR));
    outputStream.close();

    // Delete previews table row
    final String previewId = dataSource.getPreviewId(MEDIA_ID, height, width);
    dataSource.deletePreview(previewId);
}

From source file:com.tremolosecurity.scalejs.KubectlTokenLoader.java

private String cert2pem(String certificateName) {
    X509Certificate cert = GlobalEntries.getGlobalEntries().getConfigManager().getCertificate(certificateName);
    if (cert == null) {
        return null;
    } else {// www  . j av  a 2 s .c  o m
        Base64 encoder = new Base64(64);
        StringBuffer b = new StringBuffer();
        b.append("-----BEGIN CERTIFICATE-----\n");
        try {
            b.append(encoder.encodeAsString(cert.getEncoded()));
        } catch (CertificateEncodingException e) {
            logger.warn("Could not decode certificate", e);
            return null;
        }
        b.append("-----END CERTIFICATE-----");
        return b.toString();
    }

}

From source file:ECToken3.java

public static final String decryptv3(String key, String input) throws java.io.UnsupportedEncodingException,
        java.security.NoSuchAlgorithmException, javax.crypto.NoSuchPaddingException,
        java.security.InvalidKeyException, javax.crypto.IllegalBlockSizeException,
        javax.crypto.BadPaddingException, java.security.InvalidAlgorithmParameterException {

    //----------------------------------------------------
    // Base64 decode
    //----------------------------------------------------
    String result = null;/*from ww  w.j  a va  2  s  .  c o m*/
    Base64 encoder = new Base64(true);
    byte[] inputBytes = encoder.decode(input.getBytes("ASCII"));

    //----------------------------------------------------
    // Get SHA-256 of key
    //----------------------------------------------------
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    md.update(key.getBytes("ASCII"));
    byte[] keyDigest = md.digest();

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| Decrypt\n");
    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| key:                   %s\n", key);
    //System.out.format("| token:                 %s\n", input);

    //----------------------------------------------------
    // Rip up the ciphertext
    //----------------------------------------------------
    byte[] ivBytes = new byte[12];
    ivBytes = Arrays.copyOfRange(inputBytes, 0, ivBytes.length);

    byte[] cipherBytes = new byte[inputBytes.length - ivBytes.length];
    cipherBytes = Arrays.copyOfRange(inputBytes, ivBytes.length, inputBytes.length);

    //----------------------------------------------------
    // Decrypt
    //----------------------------------------------------
    AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
    cipher.init(false, new AEADParameters(new KeyParameter(keyDigest), MAC_SIZE_BITS, ivBytes));

    //System.out.format("+-------------------------------------------------------------\n");
    //System.out.format("| iv:                    %s\n", bytesToHex(ivBytes));
    //System.out.format("| ciphertext:            %s\n", bytesToHex(Arrays.copyOfRange(cipherBytes, 0, cipherBytes.length - 16)));
    //System.out.format("| tag:                   %s\n", bytesToHex(Arrays.copyOfRange(cipherBytes, cipherBytes.length - 16, cipherBytes.length)));
    //System.out.format("+-------------------------------------------------------------\n");

    byte[] dec = new byte[cipher.getOutputSize(cipherBytes.length)];

    try {
        int res = cipher.processBytes(cipherBytes, 0, cipherBytes.length, dec, 0);
        cipher.doFinal(dec, res);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    //System.out.format("token: %s\n", new String(dec, "ASCII"));
    return new String(dec, "ASCII");
}

From source file:com.cloudera.alfredo.server.TestKerberosAuthenticationHandler.java

public void testRequestWithAuthorization() throws Exception {
    String token = KerberosTestUtils.doAsClient(new Callable<String>() {
        @Override//from w w w .j  a v  a2s.  c o  m
        public String call() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSContext gssContext = null;
            try {
                String servicePrincipal = KerberosTestUtils.getServerPrincipal();
                GSSName serviceName = gssManager.createName(servicePrincipal, GSSUtil.NT_GSS_KRB5_PRINCIPAL);
                gssContext = gssManager.createContext(serviceName, GSSUtil.GSS_KRB5_MECH_OID, null,
                        GSSContext.DEFAULT_LIFETIME);
                gssContext.requestCredDeleg(true);
                gssContext.requestMutualAuth(true);

                byte[] inToken = new byte[0];
                byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                Base64 base64 = new Base64(0);
                return base64.encodeToString(outToken);

            } finally {
                if (gssContext != null) {
                    gssContext.dispose();
                }
            }
        }
    });

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
            .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token);

    AuthenticationToken authToken = handler.authenticate(request, response);

    if (authToken != null) {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);

        assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName());
        assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName()));
        assertEquals(KerberosAuthenticationHandler.TYPE, authToken.getType());
    } else {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}