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:mail.MailService.java

/**
 * Konvertiert die bergebene Bytes in das Base64 Format.
 * @param input Die Originalbytes/*from w  w w. j  a  v  a 2  s. c  om*/
 * @return In base64 konvertierte Bytes.
 */
public byte[] encodeBase64(byte[] input) {
    Base64 b64 = new Base64();
    return b64.encode(input);
}

From source file:edu.harvard.iq.dvn.api.resources.FileAccessSingletonBean.java

public VDCUser authenticateAccess(String authCredentials) {
    VDCUser vdcUser = null;/*w w w  .j  a v a2 s. c  om*/
    Base64 base64codec = new Base64();

    String decodedCredentials = "";
    byte[] authCredBytes = authCredentials.getBytes();

    try {
        byte[] decodedBytes = base64codec.decode(authCredBytes);
        decodedCredentials = new String(decodedBytes, "ASCII");
    } catch (UnsupportedEncodingException e) {
        return null;
    }

    if (decodedCredentials != null) {
        int i = decodedCredentials.indexOf(':');
        if (i != -1) {
            String userPassword = decodedCredentials.substring(i + 1);
            String userName = decodedCredentials.substring(0, i);

            if (!"".equals(userName)) {
                vdcUser = userService.findByUserName(userName, true);
                if (vdcUser == null || !userService.validatePassword(vdcUser.getId(), userPassword)) {
                    return null;
                }
            }
        }
    }

    return vdcUser;
}

From source file:cn.util.RSAUtils.java

/**
 * ?/?//w w w  . ja  v a  2 s  .  co  m
 * @return void
 * @author 
 * @time 2015-6-6?12:54:36
 */
@SuppressWarnings("static-access")
private static void loadProperties(String publicFileName, String privateFileName) {
    InputStream publicIn = null;
    InputStream privateIn = null;
    InputStreamReader inReader = null;
    BufferedReader brKeyword = null;
    try {
        publicIn = RSAUtils.class.getResourceAsStream("/key/" + publicFileName);
        privateIn = RSAUtils.class.getResourceAsStream("/key/" + privateFileName);

        inReader = new InputStreamReader(publicIn);
        brKeyword = new BufferedReader(inReader);
        StringBuffer sb = new StringBuffer();
        String keyword = null;

        while ((keyword = brKeyword.readLine()) != null) {
            sb.append(keyword);
        }
        keyword = sb.toString().replaceAll("-----\\w+ PUBLIC KEY-----", "").replace("\n", "");
        publickKeyData = (new Base64()).decodeBase64(keyword.getBytes());

        inReader = new InputStreamReader(privateIn);
        brKeyword = new BufferedReader(inReader);
        sb = new StringBuffer();
        while ((keyword = brKeyword.readLine()) != null) {
            sb.append(keyword);
        }
        keyword = sb.toString().replaceAll("-----\\w+ PRIVATE KEY-----", "").replace("\n", "");
        privateKeyData = (new Base64()).decodeBase64(keyword.getBytes());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != brKeyword)
                brKeyword.close();
            if (null != inReader)
                inReader.close();
            if (null != inReader)
                publicIn.close();
            privateIn.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.github.benyzhous.springboot.web.core.gateway.sign.backend.Sign.java

/**
 * MD5??Base64???//from  w w w.ja  v  a2  s.  co  m
 *
 * @param bytes 
 * @return
 */
public static String base64AndMD5(byte[] bytes) {
    if (bytes == null) {
        throw new IllegalArgumentException("bytes can not be null");
    }

    try {
        final MessageDigest md = MessageDigest.getInstance("MD5");
        md.reset();
        md.update(bytes);
        final Base64 base64 = new Base64();

        return new String(base64.encode(md.digest()));
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("unknown algorithm MD5");
    }
}

From source file:com.aimluck.eip.util.ALCellularUtils.java

/**
 * Triple DES ?????//ww  w .  j av a 2s  .  c o  m
 * 
 * @param plain
 *          ?
 * @return ?
 * @throws Exception
 *           ??
 */
@SuppressWarnings("unused")
private static String decrypt3Des(String key, String plain) throws Exception {
    String KEY_CRPTY_ALGORITHM = "DESede";

    // 24????
    byte[] tripleDesKeyData = new byte[24];
    byte[] kyebyte = key.getBytes();
    int len = kyebyte.length;
    for (int i = 0; i < len; i++) {
        tripleDesKeyData[i] = kyebyte[i];
    }
    SecretKey secretKey = new SecretKeySpec(tripleDesKeyData, KEY_CRPTY_ALGORITHM);

    Cipher cipher = Cipher.getInstance(KEY_CRPTY_ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, secretKey);

    Base64 decoder = new Base64();
    byte[] decParam = decoder.decode(plain.trim().getBytes());

    return String.valueOf(cipher.doFinal(decParam));
}

From source file:at.gv.egiz.pdfas.moa.MOAConnector.java

public byte[] sign(byte[] input, int[] byteRange, SignParameter parameter,
        RequestedSignature requestedSignature) throws PdfAsException {

    logger.info("signing with MOA @ " + this.moaEndpoint);
    /*/*from w  w  w.  ja v a2 s.  c  om*/
     * URL moaUrl; try { moaUrl = new URL(this.moaEndpoint+"?wsdl"); } catch
     * (MalformedURLException e1) { throw new
     * PdfAsException("Invalid MOA endpoint!", e1); }
     */
    SignatureCreationService service = new SignatureCreationService();

    SignatureCreationPortType creationPort = service.getSignatureCreationPort();
    BindingProvider provider = (BindingProvider) creationPort;
    provider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, this.moaEndpoint);

    CreateCMSSignatureRequest request = new CreateCMSSignatureRequest();
    request.setKeyIdentifier(this.keyIdentifier.trim());
    SingleSignatureInfo sigInfo = new SingleSignatureInfo();
    sigInfo.setSecurityLayerConformity(Boolean.TRUE);
    DataObjectInfo dataObjectInfo = new DataObjectInfo();
    dataObjectInfo.setStructure("detached");
    DataObject dataObject = new DataObject();
    MetaInfoType metaInfoType = new MetaInfoType();

    if (parameter.getConfiguration().hasValue(IConfigurationConstants.SIG_PADES_FORCE_FLAG)) {
        if (IConfigurationConstants.TRUE.equalsIgnoreCase(
                parameter.getConfiguration().getValue(IConfigurationConstants.SIG_PADES_FORCE_FLAG))) {
            metaInfoType.setMimeType("application/pdf");
            sigInfo.setPAdESConformity(true);
        } else {
            metaInfoType.setMimeType("application/pdf");
        }
    } else {
        metaInfoType.setMimeType("application/pdf");
    }
    dataObject.setMetaInfo(metaInfoType);

    CMSContentBaseType content = new CMSContentBaseType();
    content.setBase64Content(input);

    dataObject.setContent(content);

    dataObjectInfo.setDataObject(dataObject);
    sigInfo.setDataObjectInfo(dataObjectInfo);
    request.getSingleSignatureInfo().add(sigInfo);

    requestedSignature.getStatus().getMetaInformations().put(ErrorConstants.STATUS_INFO_SIGDEVICE,
            SIGNATURE_DEVICE);
    // TODO: Find a way to get MOA-SPSS Version
    requestedSignature.getStatus().getMetaInformations().put(ErrorConstants.STATUS_INFO_SIGDEVICEVERSION,
            "UNKNOWN");

    CreateCMSSignatureResponseType response;
    try {
        response = creationPort.createCMSSignature(request);
    } catch (MOAFault e) {
        logger.warn("MOA signing failed!", e);
        if (e.getFaultInfo() != null) {
            throw new PdfAsMOAException(e.getFaultInfo().getErrorCode().toString(), e.getFaultInfo().getInfo(),
                    "", "");
        } else {
            throw new PdfAsMOAException("", e.getMessage(), "", "");
        }
    }

    if (response.getCMSSignatureOrErrorResponse().size() != 1) {
        throw new PdfAsException(
                "Invalid Response Count [" + response.getCMSSignatureOrErrorResponse().size() + "] from MOA!");
    }

    Object resp = response.getCMSSignatureOrErrorResponse().get(0);
    if (resp instanceof byte[]) {
        // done the signature!
        byte[] cmsSignatureData = (byte[]) resp;

        VerifyResult verifyResult;
        try {
            verifyResult = SignatureUtils.verifySignature(cmsSignatureData, input);
            if (SettingsUtils.getBooleanValue(requestedSignature.getStatus().getSettings(),
                    IConfigurationConstants.KEEP_INVALID_SIGNATURE, false)) {
                Base64 b64 = new Base64();
                requestedSignature.getStatus().getMetaInformations().put(ErrorConstants.STATUS_INFO_INVALIDSIG,
                        b64.encodeToString(cmsSignatureData));
            }
        } catch (PDFASError e) {
            throw new PdfAsErrorCarrier(e);
        }

        if (!StreamUtils.dataCompare(requestedSignature.getCertificate().getFingerprintSHA(),
                ((X509Certificate) verifyResult.getSignerCertificate()).getFingerprintSHA())) {
            throw new PdfAsSignatureException("Certificates missmatch!");
        }

        return cmsSignatureData;
    } else if (resp instanceof ErrorResponseType) {
        ErrorResponseType err = (ErrorResponseType) resp;

        throw new PdfAsMOAException("", "", err.getInfo(), err.getErrorCode().toString());

    } else {
        throw new PdfAsException("MOA response is not byte[] nor error but: " + resp.getClass().getName());
    }
}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

public void sendInput(byte[] buf) throws IOException {
    logger.debug("Sending WinRM Send Input request for command {} in shell {}", commandId, shellId);

    final Element bodyContent = DocumentHelper.createElement(QName.get("Send", Namespaces.NS_WIN_SHELL));
    final Base64 base64 = new Base64();
    bodyContent.addElement(QName.get("Stream", Namespaces.NS_WIN_SHELL)).addAttribute("Name", "stdin")
            .addAttribute("CommandId", commandId).addText(base64.encodeAsString(buf));
    final Document requestDocument = getRequestDocument(Action.WS_SEND, ResourceURI.RESOURCE_URI_CMD, null,
            bodyContent);//from ww w.j a va  2 s. c  o m
    sendRequest(requestDocument, SoapAction.SEND);

    logger.debug("Sent WinRM Send Input request for command {} in shell {}", commandId, shellId);
}

From source file:license.ExtraTestWakeLicense.java

/**
 * ?mac?/*from www  .j  a  v  a  2s  .com*/
 * @param sb
 * @throws Exception
 */
private static void mac(StringBuilder sb) throws Exception {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    int i = 12;
    Base64 base64 = new Base64();
    for (NetworkInterface ni : Collections.list(interfaces)) {
        if (ni.getName().substring(0, 1).equalsIgnoreCase("e")) {
            sb.append(String.valueOf(i)).append('=').append(ni.getName()).append('\n');
            i++;
            byte[] mac = ni.getHardwareAddress();
            sb.append(String.valueOf(i)).append('=').append(base64.encodeAsString(mac)).append('\n');
            i++;
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.canvas.CanvasRenderingContext2D.java

private static String encodeToString(final BufferedImage image, final String type) throws IOException {
    try (final ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
        ImageIO.write(image, type, bos);

        final byte[] imageBytes = bos.toByteArray();

        return new String(new Base64().encode(imageBytes));
    }/*from w w  w  .j a v a 2  s  . c o  m*/
}

From source file:edu.tsinghua.lumaqq.ui.config.user.SecurityPage.java

/**
 * ?//from w w  w .  jav  a 2 s.  c  om
 * 
 * @return
 *       truefalse
 */
@SuppressWarnings("unchecked")
protected boolean checkOldPassword() {
    // ?
    if (chkChangePassword.getSelection()) {
        Logins logins = LoginUtil.load(new File(LumaQQ.LOGIN_HISTORY));
        if (logins == null) {
            log.error("???");
            return false;
        }
        List<Login> list = logins.getLogin();
        for (Login login : list) {
            if (login.getQq().equals(String.valueOf(model.qq))) {
                // ??
                String s = "";
                Base64 codec = new Base64();
                if (login.isRememberPassword())
                    s = new String(codec.encode(md5(md5(textOldPassword.getText().getBytes()))));
                else
                    s = new String(codec
                            .encode(md5(new String(codec.encode(md5(md5(textOldPassword.getText().getBytes()))))
                                    .getBytes())));
                if (login.getPassword().equals(s))
                    return true;
                else
                    return false;
            }
        }
        return false;
    } else
        return true;
}