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

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

Introduction

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

Prototype

public static byte[] encodeBase64(final byte[] binaryData) 

Source Link

Document

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

Usage

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.connotea.ConnoteaUtils.java

public ConnoteaUtils(String username, String password) {
    this.username = username;
    this.password = password;
    authHeader = "Basic " + new String(Base64.encodeBase64((this.username + ":" + this.password).getBytes()));
}

From source file:com.apporiented.hermesftp.utils.SecurityUtil.java

/**
 * Calculates based on the passed parameters an hash code and returns its BASE64 representation. The
 * used algorithm is prepended./*from  w  w  w  .  j  a  v  a  2 s.  c o  m*/
 * 
 * @param password The password to encode.
 * @param algorithm The algorithm to use (MD5 e.g.)
 * @return The encoded password as string.
 * @throws NoSuchAlgorithmException Passed algorithm is not supported.
 */
public static String digestPassword(String password, String algorithm) throws NoSuchAlgorithmException {
    if (password == null) {
        throw new IllegalArgumentException("No password passed");
    }
    String result = password.trim();
    if (algorithm == null) {
        return result;
    }
    MessageDigest digest = MessageDigest.getInstance(algorithm);
    digest.update(password.getBytes());
    byte[] digestedPassword = digest.digest();
    String base64password = new String(Base64.encodeBase64(digestedPassword));
    return ALG_START + algorithm + ALG_END + base64password;
}

From source file:com.klarna.checkout.Digest.java

/**
 * Create a digest from a supplied string.
 *
 * @param message string to hash// w  w w  .j av  a 2  s  .c  o m
 *
 * @return Base64 and SHA256 hashed string
 *
 * @throws UnsupportedEncodingException if UTF-8 is unsupported
 */
public String create(final String message) throws UnsupportedEncodingException {
    md.reset();

    if (message != null) {
        md.update(message.getBytes("UTF-8"));
    }

    md.update(secret.getBytes("UTF-8"));

    return new String(Base64.encodeBase64(md.digest()));
}

From source file:com.dasol.util.AES256Util.java

public String aesEncode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
    c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));

    byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));
    String enStr = new String(Base64.encodeBase64(encrypted));

    return enStr;
}

From source file:com.enonic.cms.core.portal.rendering.PortletErrorMessageMarkupCreator.java

private String getDetailsBase64(final Exception e) {
    return new String(Base64.encodeBase64(getDetails(e).getBytes()));
}

From source file:ezbake.data.postgres.hibernate.HibernateUtil.java

private static SessionFactory buildSessionFactory(Properties ezConfig, EzSecurityToken token,
        SessionType sessionType) {//from w ww  . jav  a  2  s.  com
    try {
        String appName = ezConfig.getProperty(EzBakePropertyConstants.EZBAKE_APPLICATION_NAME);
        switch (sessionType) {
        case EZBAKE: {

            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
            for (Map.Entry<Object, Object> entry : ezConfig.entrySet()) {
                String key = (String) entry.getKey();
                String value = (String) entry.getValue();

                configuration.setProperty("hibernate.connection." + key, value);
            }

            return configuration
                    .setProperty("hibernate.connection.driver_class", "ezbake.data.postgres.EzPostgresDriver")
                    .setProperty("hibernate.connection.username",
                            ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_USERNAME))
                    .setProperty("hibernate.connection.password",
                            ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PASSWORD))
                    .setProperty("hibernate.connection.url",
                            String.format("jdbc:ezbake:postgresql://%s:%s/%s",
                                    ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_HOST),
                                    ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PORT), appName))
                    .setProperty("hibernate.default_schema", "public")
                    .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect")
                    .setProperty("EzSecurityToken",
                            new String(Base64.encodeBase64(new TSerializer().serialize(token)),
                                    Charsets.US_ASCII))
                    .setProperty("hibernate.hbm2ddl.auto", "update").configure().buildSessionFactory();
        }
        case POSTGRES: {
            return new Configuration().setProperty("hibernate.connection.driver_class", "org.postgresql.Driver")
                    .setProperty("hibernate.connection.username",
                            ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_USERNAME))
                    .setProperty("hibernate.connection.password",
                            ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PASSWORD))
                    .setProperty("hibernate.connection.url",
                            String.format("jdbc:postgresql://%s:%s/%s",
                                    ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_HOST),
                                    ezConfig.getProperty(EzBakePropertyConstants.POSTGRES_PORT), appName))
                    .setProperty("hibernate.default_schema", "public")
                    .setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect")
                    .setProperty("hibernate.show_sql", "true").setProperty("hibernate.hbm2ddl.auto", "update")
                    .configure().buildSessionFactory();
        }
        default: {
            throw new Exception("Invalid session type [" + sessionType + "].");
        }
        }
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

From source file:com.ibm.sbt.security.encryption.HMACEncryptionUtility.java

public static String generateHMACSignature(String apiUrl, String method, String consumerSecret,
        String tokenSecret, Map<String, String> paramsSortedMap) throws OAuthException {
    try {/*w  w  w . j  a v a 2 s  . c  o m*/
        String parameterString = generateParameterString(paramsSortedMap);
        String signature_base_string = generateSignatureBaseString(method, apiUrl, parameterString);
        String signingKey = null;
        if (StringUtil.isEmpty(tokenSecret)) {
            // No token secret is available when call is made from getRequestToken, tokensecret is fetched
            // later in OADance
            signingKey = consumerSecret + "&";
        } else {
            signingKey = consumerSecret + "&" + tokenSecret;
        }

        byte[] keyBytes = null;
        try {
            keyBytes = signingKey.getBytes(Configuration.ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new OAuthException(e,
                    "HMACEncryptionUtility : generateHMACSignature caused UnsupportedEncodingException exception");
        }
        SecretKey secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] text = null;
        try {
            text = signature_base_string.getBytes(Configuration.ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new OAuthException(e,
                    "HMACEncryptionUtility : generateHMACSignature caused UnsupportedEncodingException exception");
        }
        String signature = new String(Base64.encodeBase64(mac.doFinal(text))).trim();
        return signature;
    } catch (NoSuchAlgorithmException e) {
        throw new OAuthException(e,
                "HMACEncryptionUtility : generateHMACSignature caused NoSuchAlgorithmException exception");
    } catch (InvalidKeyException e) {
        throw new OAuthException(e,
                "HMACEncryptionUtility : generateHMACSignature caused InvalidKeyException exception");
    }
}

From source file:com.rr.familyPlanning.ui.security.encryptObject.java

/**
 * Encrypts and encodes the Object and IV for url inclusion
 *
 * @param input//from ww w  .j  a v a 2 s . co  m
 * @return
 * @throws Exception
 */
public String[] encryptObject(Object obj) throws Exception {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(stream);
    try {
        // Serialize the object
        out.writeObject(obj);
        byte[] serialized = stream.toByteArray();
        // Setup the cipher and Init Vector
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iv = new byte[cipher.getBlockSize()];
        new SecureRandom().nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        // Hash the key with SHA-256 and trim the output to 128-bit for the key
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        digest.update(keyString.getBytes());
        byte[] key = new byte[16];
        System.arraycopy(digest.digest(), 0, key, 0, key.length);
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
        // encrypt
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        // Encrypt & Encode the input
        byte[] encrypted = cipher.doFinal(serialized);
        byte[] base64Encoded = Base64.encodeBase64(encrypted);
        String base64String = new String(base64Encoded);
        String urlEncodedData = URLEncoder.encode(base64String, "UTF-8");
        // Encode the Init Vector
        byte[] base64IV = Base64.encodeBase64(iv);
        String base64IVString = new String(base64IV);
        String urlEncodedIV = URLEncoder.encode(base64IVString, "UTF-8");

        return new String[] { urlEncodedData, urlEncodedIV };
    } finally {
        stream.close();
        out.close();
    }
}

From source file:com.mothsoft.alexis.web.security.OutboundRestAuthenticationInterceptor.java

@Override
public void handleMessage(Message message) {

    if (!CurrentUserUtil.isAuthenticated()) {
        throw new AuthenticationCredentialsNotFoundException("Unauthenticated user!");
    }// ww w . j  a  v a  2 s .com

    @SuppressWarnings("unchecked")
    Map<String, List<String>> headers = (Map<String, List<String>>) message.get(Message.PROTOCOL_HEADERS);
    if (headers == null) {
        headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
        message.put(Message.PROTOCOL_HEADERS, headers);
    }

    final List<String> header = new ArrayList<String>();

    final String username = CurrentUserUtil.getCurrentUser().getUsername();
    final String apiToken = CurrentUserUtil.getCurrentUser().getApiToken();
    final String usernameToken = String.format("%s:%s", username, apiToken);
    try {
        header.add(String.format("Basic %s", new String(Base64.encodeBase64(usernameToken.getBytes("UTF-8")))));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

    headers.put("Authorization", header);
}

From source file:edu.kit.scc.http.client.HttpClientTest.java

@Test
public void testMakeHttpGetRequestWithAuthorization() {
    String url = "http://www.kit.edu";
    String restUser = "test";
    String restPassword = "test";
    String auth = restUser + ":" + restPassword;
    byte[] authZheader = auth.getBytes();
    String authorizationHeader = "Basic "
            + new String(Base64.encodeBase64(authZheader), StandardCharsets.UTF_8);

    HttpResponse response = client.makeHttpGetRequest(restUser, restPassword, url);

    assertNotNull(response);//from w  w  w .j  av a2 s  .  com
    assertTrue(response.getStatusCode() == 200);
}