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() 

Source Link

Document

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

Usage

From source file:UploadTest.java

@BeforeClass
public static void initConfigs() throws IOException {
    try {/* w  ww  . j a v a2  s .  com*/
        url = new URL("http://localhost:9000/resource/frl:6376984");
        httpCon = (HttpURLConnection) url.openConnection();
        String userpass = user + ":" + password;
        basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        httpCon.setRequestProperty("Authorization", basicAuth);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.wabacus.util.DesEncryptTools.java

private static byte[] base64Decode(String s) {
    if (s == null)
        return null;
    try {//from   ww w.  j  a  v a2  s. co  m
        return new Base64().decode(s);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    //        {
    //        }
}

From source file:co.cask.hydrator.plugin.EncoderTest.java

@Test
public void testBase64Encoder() throws Exception {
    String test = "This is a test for testing base64 encoding";
    Transform<StructuredRecord, StructuredRecord> transform = new Encoder(
            new Encoder.Config("a:BASE64", OUTPUT.toString()));
    transform.initialize(null);//w  w  w . java  2s  .  c o  m

    MockEmitter<StructuredRecord> emitter = new MockEmitter<>();
    transform.transform(StructuredRecord.builder(INPUT).set("a", test).set("b", "2").set("c", "3").set("d", "4")
            .set("e", "5").build(), emitter);

    Base64 base64 = new Base64();
    byte[] expected = base64.encode(test.getBytes("UTF-8"));
    byte[] actual = emitter.getEmitted().get(0).get("a");
    Assert.assertEquals(2, emitter.getEmitted().get(0).getSchema().getFields().size());
    Assert.assertArrayEquals(expected, actual);
}

From source file:bazaar4idea.util.BzrErrorReportConfigurable.java

public void setPlainItnPassword(String password) {
    if (password == null || "".equals(password.trim())) {
        AUTH_PASSWORD = "";
    } else {//from   w  w w  .j  a va  2  s  . co  m
        AUTH_PASSWORD = new String(new Base64().encode(password.getBytes()));
    }
}

From source file:edu.northwestern.cbits.purple_robot_manager.http.BasicAuthTokenExtractor.java

public String extract(final HttpRequest request) throws HttpException {
    String auth = null;/*  w  w w .  j  av  a 2  s .c o  m*/
    final Header h = request.getFirstHeader(AUTH.WWW_AUTH_RESP);

    if (h != null) {
        final String s = h.getValue();

        if (s != null) {
            auth = s.trim();
        }
    }

    if (auth != null) {
        final int i = auth.indexOf(' ');

        if (i == -1) {
            throw new ProtocolException("Invalid Authorization header: " + auth);
        }

        final String authscheme = auth.substring(0, i);

        if (authscheme.equalsIgnoreCase("basic")) {
            final String s = auth.substring(i + 1).trim();

            try {
                final byte[] credsRaw = EncodingUtils.getAsciiBytes(s);
                final BinaryDecoder codec = new Base64();
                auth = EncodingUtils.getAsciiString(codec.decode(credsRaw));
            } catch (final DecoderException ex) {
                throw new ProtocolException("Malformed BASIC credentials");
            }
        }
    }
    return auth;
}

From source file:co.cask.hydrator.plugin.DecoderTest.java

@Test
public void testBase64Decoder() throws Exception {
    String test = "This is a test for testing base64 decoding";
    Transform<StructuredRecord, StructuredRecord> encoder = new Encoder(
            new Encoder.Config("a:BASE64", OUTPUT.toString()));
    encoder.initialize(null);/*  www . j  a  v a2  s.co  m*/

    MockEmitter<StructuredRecord> emitterEncoded = new MockEmitter<>();
    encoder.transform(StructuredRecord.builder(INPUT).set("a", test).set("b", "2").set("c", "3").set("d", "4")
            .set("e", "5").build(), emitterEncoded);

    Base64 base64 = new Base64();
    byte[] expected = base64.encode(test.getBytes("UTF-8"));
    byte[] actual = emitterEncoded.getEmitted().get(0).get("a");
    Assert.assertEquals(2, emitterEncoded.getEmitted().get(0).getSchema().getFields().size());
    Assert.assertArrayEquals(expected, actual);

    Transform<StructuredRecord, StructuredRecord> decoder = new Decoder(
            new Decoder.Config("a:BASE64", OUTPUTSTR.toString()));
    decoder.initialize(null);
    MockEmitter<StructuredRecord> emitterDecoded = new MockEmitter<>();
    decoder.transform(emitterEncoded.getEmitted().get(0), emitterDecoded);
    Assert.assertEquals(2, emitterDecoded.getEmitted().get(0).getSchema().getFields().size());
    Assert.assertEquals(test, emitterDecoded.getEmitted().get(0).get("a"));
}

From source file:net.bioclipse.cdk.ui.sdfeditor.CDKFingerPrintPropertyCalculator.java

public String toString(Object value) {
    // TODO check if this is right
    BitSet val = (BitSet) value;
    byte[] bytes = new byte[val.length() / 8 + 1];
    for (int i = 0; i < val.length(); i++) {
        if (val.get(i)) {
            bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
        }//from  w  ww.  j  a v a  2  s  .c o  m
    }
    return new String(new Base64().encode(bytes));
}

From source file:de.hybris.platform.b2b.punchout.services.impl.SymmetricManager.java

public static String getKey() {
    String key = null;//ww w .ja va  2  s .  c  om
    try {
        final KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
        kgen.init(KEY_SIZE);
        // Generate the secret key specs.
        final SecretKey skey = kgen.generateKey();
        final byte[] raw = skey.getEncoded();
        key = new Base64().encodeAsString(raw);
    } catch (final NoSuchAlgorithmException e) {
        // should never happen
        LOG.error("System was unable to generate the key.", e);
    }
    return key;
}

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Creates a new private and public key and at the same time encodes the public key as XML to be used by the .NET client
 * @param size/* w w w . j  a v  a  2  s .  c  o m*/
 * @param productId
 *
 */
private void firstTimeInitialisation(int size) {
    try {

        // Get Key Pair Generator for RSA.
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(size);

        KeyPair keypair = keyGen.genKeyPair();
        privateKey = keypair.getPrivate();
        publicKey = keypair.getPublic();

        // Get the bytes of the public and private keys
        byte[] privateKeyBytes = privateKey.getEncoded();
        byte[] publicKeyBytes = publicKey.getEncoded();

        // store temporarily witht he public key for the lifetime of this class.
        encodedPrivateKey = new Base64().encode(privateKeyBytes);

        // Generate the Private Key, Public Key and Public Key in XML format.
        KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(publicKeyBytes));

        // Store the public key in XML string to make compatible .Net public key file
        encodedToXMLPublicKey = getRSAPublicKeyAsXMLString(rsaPublicKey);

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:com.jamfsoftware.jss.healthcheck.controller.HTTPController.java

public String doGet(String URL) throws Exception {
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    URL obj = new URL(URL);
    //Relax host checking for Self Signed Certs
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    TrustModifier.relaxHostChecking(con);
    //Setup the Connection.
    con.setRequestMethod("GET");
    con.setRequestProperty("User_Agent", USER_AGENT);
    Base64 b = new Base64();
    String encoding = b.encodeAsString((username + ":" + password).getBytes());
    con.setRequestProperty("Authorization", "Basic " + encoding);

    int responseCode = con.getResponseCode();
    LOGGER.debug("Sending 'GET' request to URL : " + URL);
    LOGGER.debug("Response Code : " + responseCode);

    //Get the response
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;//from w  w  w  .ja v a 2s .  c o  m
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return response.toString();
}