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:com.ddling.server.smtp.State.Auth.java

public boolean process(SMTPThread smtpThread, String str) {

    // ??/* ww  w .j a  v a 2  s .c om*/
    String cmd = this.getCommandStr(str);
    String arg = this.getArgumentStr(str);

    // ??
    if (!isValidCommand(cmd)) {
        smtpThread.printToClient("502 Error: command not implemented");
        return false;
    }

    // Auth??login
    if (arg == "") {
        smtpThread.printToClient("");
        return false;
    }

    if (cmd.equalsIgnoreCase("auth") && !arg.equalsIgnoreCase("login")) {
        smtpThread.printToClient("504 Unrecognized authentication type");
        return false;
    } else if (cmd.equals("auth") && arg.equals("login")) {
        smtpThread.printToClient("334 " + Base64.encodeBase64String("username:".getBytes()));
        return true;
    } else {
        smtpThread.printToClient("502 Error: command not implemented");
        return false;
    }
}

From source file:com.k42b3.neodym.oauth.HMACSHA1.java

public String build(String baseString, String consumerSecret, String tokenSecret) throws Exception {
    String key = Oauth.urlEncode(consumerSecret) + "&" + Oauth.urlEncode(tokenSecret);

    Charset charset = Charset.defaultCharset();

    SecretKey sk = new SecretKeySpec(key.getBytes(charset), "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");

    mac.init(sk);//from  w  w w .  ja  va2s  . c  o m

    byte[] result = mac.doFinal(baseString.getBytes(charset));

    return Base64.encodeBase64String(result);
}

From source file:com.earldouglas.xjdl.io.LicenseCreator.java

public String encryptLicense(License license, String key)
        throws Exception, NoSuchAlgorithmException, NoSuchPaddingException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
    objectOutputStream.writeObject(license);
    objectOutputStream.close();//w w  w.j av  a  2 s  .c om
    byte[] serializedLicense = byteArrayOutputStream.toByteArray();

    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] encryptedLicense = cipher.doFinal(serializedLicense);
    String encodedLicense = Base64.encodeBase64String(encryptedLicense);
    encodedLicense = encodedLicense.replaceAll("\n", "");
    encodedLicense = encodedLicense.replaceAll("\r", "");
    return encodedLicense;
}

From source file:com.igormaznitsa.sciareto.preferences.PreferencesManager.java

private PreferencesManager() {
    this.prefs = Preferences.userNodeForPackage(PreferencesManager.class);
    String packedUuid = this.prefs.get(PROPERTY_UUID, null);
    if (packedUuid == null) {
        try {/*from w w w .  j  av  a2s .c  om*/
            final UUID newUUID = UUID.randomUUID();
            packedUuid = Base64.encodeBase64String(IOUtils.packData(newUUID.toString().getBytes("UTF-8")));
            this.prefs.put(PROPERTY_UUID, packedUuid);
            this.prefs.flush();
            LOGGER.info("Generated new installation UUID : " + newUUID.toString());

            final Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    LOGGER.info("Send first start metrics");
                    com.igormaznitsa.sciareto.metrics.MetricsService.getInstance().onFirstStart();
                }
            }, "SCIARETO_FIRST_START_METRICS");
            thread.setDaemon(true);
            thread.start();

        } catch (Exception ex) {
            LOGGER.error("Can't generate UUID", ex);
        }
    }
    try {
        this.installationUUID = UUID
                .fromString(new String(IOUtils.unpackData(Base64.decodeBase64(packedUuid)), "UTF-8"));
        LOGGER.info("Installation UUID : " + this.installationUUID.toString());
    } catch (UnsupportedEncodingException ex) {
        LOGGER.error("Can't decode UUID", ex);
        throw new Error("Unexpected error", ex);
    }
}

From source file:com.thoughtworks.go.agent.testhelper.AgentBinariesServlet.java

protected void doHead(HttpServletRequest request, HttpServletResponse response) {
    try {/*from  www  .ja va 2  s  .  c om*/
        response.setHeader("Content-MD5", resource.getMd5());

        final String extraPropertiesHeaderValue = fakeGoServer.getExtraPropertiesHeaderValue();
        if (extraPropertiesHeaderValue != null) {
            response.setHeader(AGENT_EXTRA_PROPERTIES_HEADER,
                    Base64.encodeBase64String(extraPropertiesHeaderValue.getBytes(StandardCharsets.UTF_8)));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.wpi.cs.wpisuitetng.authentication.TestBasicAuth.java

/**
 * Generates a valid BasicAuth token with invalidly formatted
 * credentials. Decoding should work properly. An exception should
 * raise because the credential string is not in the "String:String" format.
 *///from   w  w  w.ja v  a 2 s .  c o m
@Test(expected = AuthenticationException.class)
public void testInvalidCredentialFormat() throws AuthenticationException {
    String authToken = "Basic ";
    String credentials = "abcdefg123456";
    authToken += Base64.encodeBase64String(credentials.getBytes());

    this.basic.parsePost(authToken);
}

From source file:gui.configurar.GerarAssinatura.java

String assinar() {
    String senha = tSenha.getText();
    String c = tContribuinte.getText() + tDev.getText();
    if (certificado == null) {
        Msg.show("Escolha o certificado");
        return "";
    }/*from   w w  w. j av a  2 s  . c o  m*/
    try {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(new FileInputStream(certificado), senha.toCharArray());
        ArrayList<String> apelidos = new ArrayList<String>();
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            apelidos.add(aliases.nextElement());
        }
        PrivateKey key = (PrivateKey) keystore.getKey(apelidos.get(0), senha.toCharArray());
        Signature assinatura = Signature.getInstance("SHA256withRSA");
        assinatura.initSign(key);
        byte[] bytes = c.getBytes();
        assinatura.update(bytes);
        byte[] assinado = assinatura.sign();
        String strAssinado = Base64.encodeBase64String(assinado);
        return strAssinado;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:de.thischwa.pmcms.tool.DESCryptor.java

public String encrypt(String plainTxt) throws CryptorException {
    if (plainTxt == null || plainTxt.trim().length() == 0)
        return null;
    if (key == null)
        key = buildKey();/*from   w ww.  ja v  a 2 s .  co m*/
    try {
        byte[] cleartext = plainTxt.getBytes(encoding);
        Cipher cipher = Cipher.getInstance(algorithm); // cipher is not thread safe
        cipher.init(Cipher.ENCRYPT_MODE, key);
        String encrypedPwd = Base64.encodeBase64String(cipher.doFinal(cleartext));
        return encrypedPwd;
    } catch (Exception e) {
        throw new CryptorException(e);
    }
}

From source file:net.incrementalism.tooter.User.java

private static String hash(String password) {
    // NOTE: Insecure! Don't use this in a real application
    try {/*from ww  w .j a  va2 s  .co m*/
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(password.getBytes("UTF-8"));
        return Base64.encodeBase64String(md.digest());
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError("No SHA");
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError("No UTF-8");
    }
}

From source file:com.reydentx.core.common.JSONUtils.java

private static String encodeToString(BufferedImage image, String type) {
    String imageString = null;//from w ww  .ja  v a  2  s  .  c  o m
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = Base64.encodeBase64String(imageBytes);
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}