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:course.UserDAO.java

private String makePasswordHash(String password, String salt) {
    try {/*from  w w w. ja  va 2  s . co m*/
        String saltedAndHashed = password + "," + salt;
        MessageDigest digest = MessageDigest.getInstance("MD5");
        digest.update(saltedAndHashed.getBytes());

        // BASE64Encoder encoder = new BASE64Encoder();
        byte hashedBytes[] = new String(digest.digest(), "UTF-8").getBytes();
        // return encoder.encode(hashedBytes) + "," + salt;
        return new Base64().encodeToString(hashedBytes) + "," + salt;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("MD5 is not available", e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("UTF-8 unavailable?  Not a chance", e);
    }
}

From source file:com.twosigma.beaker.r.rest.RShellRest.java

public RShellRest() {
    this.encoder = new Base64();
}

From source file:com.cloudant.sync.datastore.ForceInsertTest.java

@Test
public void notification_forceinsertWithAttachments() {

    // this test only makes sense if the data is inline base64 (there's no remote server to pull the attachment from)
    boolean pullAttachmentsInline = true;

    // create a document and insert the first revision
    BasicDocumentRevision doc1_rev1 = datastore.createDocument(bodyOne);
    Map<String, Object> atts = new HashMap<String, Object>();
    Map<String, Object> att1 = new HashMap<String, Object>();

    atts.put("att1", att1);
    att1.put("data", new String(new Base64().encode("this is some data".getBytes())));
    att1.put("content_type", "text/plain");

    ArrayList<String> revisionHistory = new ArrayList<String>();
    revisionHistory.add(doc1_rev1.getRevision());

    // now do a force insert and then see if we get the attachment back
    datastore.forceInsert(doc1_rev1, revisionHistory, atts, pullAttachmentsInline);

    Attachment storedAtt = datastore.getAttachment(doc1_rev1, "att1");
    Assert.assertNotNull(storedAtt);/*ww  w.  j ava  2s . c  o m*/

    Attachment noSuchAtt = datastore.getAttachment(doc1_rev1, "att2");
    Assert.assertNull(noSuchAtt);
}

From source file:de.scoopgmbh.copper.persistent.StandardJavaSerializer.java

private String serialize(final Object o) throws IOException {
    if (o == null)
        return null;
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
    final ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(o);/*from w w w .ja va  2 s .c  o m*/
    oos.close();
    baos.close();
    byte[] data = baos.toByteArray();
    boolean isCompressed = false;
    if (compress && compressThresholdSize <= data.length && data.length <= compressorMaxSize) {
        data = compressorTL.get().compress(data);
        isCompressed = true;
    }
    final String encoded = new Base64().encodeToString(data);
    final StringBuilder sb = new StringBuilder(encoded.length() + 4);
    sb.append(isCompressed ? 'C' : 'U').append(encoded);
    return sb.toString();
}

From source file:com.intera.roostrap.util.EncryptionUtil.java

public static String decrypt(String encryptionKey, String encryptedText) throws InvalidKeyException {
    Base64 base64 = new Base64();
    InputStream inStream = new ByteArrayInputStream(base64.decode(toBytes(encryptedText)));
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    try {//from  www  . j  a v  a2 s.com
        decrypt(encryptionKey, inStream, outStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return toString(outStream.toByteArray());
}

From source file:edu.harvard.iq.dvn.core.web.servlet.ICPSRproxyServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) {

    String icpsrId = req.getParameter("icpsrId");

    if (icpsrId != null) {
        Base64 b64 = new Base64();

        byte[] bytesDecoded = b64.decode(icpsrId.getBytes());

        String icpsrURLdecoded = new String(bytesDecoded);

        if (icpsrURLdecoded.startsWith("http")) {

            GetMethod method = null;/*from w w w . ja va  2  s . c om*/
            int status = 200;

            try {
                method = new GetMethod(icpsrURLdecoded);
                status = getClient().executeMethod(method);
            } catch (IOException ex) {
                // return 404 
                // and generate a FILE NOT FOUND message

                createErrorResponse404(res);
                if (method != null) {
                    method.releaseConnection();
                }
                return;
            }

            if (status == 403) {
                // generate an HTML-ized response with a correct 
                // 403/FORBIDDEN code   

                createErrorResponse403(res);
                if (method != null) {
                    method.releaseConnection();
                }
                return;
            }

            if (status == 404) {
                // generate an HTML-ized response with a correct 
                // 404/FILE NOT FOUND code   

                createErrorResponse404(res);
                if (method != null) {
                    method.releaseConnection();
                }
                return;
            }

            // a generic response for all other failure cases:

            if (status != 200) {
                createErrorResponseGeneric(res, status,
                        (method.getStatusLine() != null) ? method.getStatusLine().toString()
                                : "Unknown HTTP Error");
                if (method != null) {
                    method.releaseConnection();
                }
                return;
            }

            try {
                // recycle all the incoming headers 
                for (int i = 0; i < method.getResponseHeaders().length; i++) {
                    res.setHeader(method.getResponseHeaders()[i].getName(),
                            method.getResponseHeaders()[i].getValue());
                }

                // send the incoming HTTP stream as the response body

                InputStream in = method.getResponseBodyAsStream();
                OutputStream out = res.getOutputStream();

                int i = in.read();
                while (i != -1) {
                    out.write(i);
                    i = in.read();
                }
                in.close();
                out.close();

            } catch (IOException ex) {
                ex.printStackTrace();
            }

            method.releaseConnection();
        } else {
            createErrorResponse404(res);
            return;
        }

    } else {
        createErrorResponse404(res);
        return;
    }
}

From source file:net.mobid.codetraq.utils.PasswordProcessor.java

/**
 * Decrypts a text using the <code>passPhrase</code> above and an algorithm supported
 * by your virtual machine implementation. You can change the default algorithm with
 * another algorithm, but please make sure your virtual machine supports it.
 * @param valueToDecrypt - text to decrypt
 * @return a plain text/*from w w w .java 2s .c om*/
 */
public static String decryptString(String valueToDecrypt) {
    String output = null;
    try {
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterations);
        SecretKey secretKey = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterations);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
        // begin decrypting...
        byte[] encrypted = new Base64().decode(valueToDecrypt);
        byte[] utf8 = cipher.doFinal(encrypted);
        output = new String(utf8, "UTF8");
    } catch (Exception ex) {
        Logger.getLogger(PasswordProcessor.class.getName()).log(Level.SEVERE, null, ex);
    }
    return output;
}

From source file:com.norbl.util.StringUtil.java

public static String encrypt(SecretKey key, String s) throws Exception {
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE, key);
    byte[] enb = c.doFinal(s.getBytes());
    Base64 b64enc = new Base64();
    return (new String(b64enc.encode(enb)));
}

From source file:jatran.stub.StringUtil.java

/**
 * Encodes a string using Base64 encoding. Used when storing passwords
 * as cookies.//from ww w  .  j a  v  a  2 s  . com
 * <p>    * This is weak encoding in that anyone can use the decodeString
 * routine to reverse the encoding.
 *
 * @param str The string to encode
 * @return Encoded string
 */
public static String encodeString(String str) {
    Base64 encoder = new Base64();
    return new String(encoder.encode(str.getBytes())).trim();
}

From source file:ch.cern.security.saml2.utils.xml.XMLUtils.java

/**
 * Compress the xml string and encodes it in Base64
 * //from   w  w w  . j  a  v  a  2s  .  c  o m
 * @param xmlString
 * @param isDebugEnabled 
 * @return xml string encoded
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
public static String xmlDeflateAndEncode(String xmlString, boolean isDebugEnabled)
        throws IOException, UnsupportedEncodingException {

    if (isDebugEnabled)
        nc.notice(xmlString);

    // Deflate the SAMLResponse value
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
    deflaterStream.write(xmlString.getBytes());
    deflaterStream.finish();

    // Encoded the deflatedResponse in base64
    Base64 base64encoder = new Base64();
    String base64response = new String(base64encoder.encode(bytesOut.toByteArray()), "UTF-8");

    if (isDebugEnabled)
        nc.notice(base64response);

    return base64response;
}