Java Code Examples for sun.misc.BASE64Encoder#encode()

The following examples show how to use sun.misc.BASE64Encoder#encode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Base64ImgUtils.java    From spring-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 图片转化成base64字符串,将图片文件转化为字节数组字符串,并对其进行Base64编码处理
 *
 * @param imgFile 待处理的图片
 * @return String 返回Base64编码过的字节数组字符串
 */
public static final String toBase64String(String imgFile) {

    InputStream in = null;
    if(StringUtils.isEmpty(imgFile)) return null;
    byte[] data = null;

    //读取图片字节数组
    try {
        in = new FileInputStream(imgFile);
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        System.err.println("图片转化成base64字符串错误:" + e.getMessage());
    }
    //对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data);
}
 
Example 2
Source File: ImageUtils.java    From wechat-pay-sdk with MIT License 6 votes vote down vote up
/**
 * <pre>
 * 图片文件转化为Base64编码字符串
 *
 * </pre>
 *
 * @param image
 * @param type
 * @return
 */
public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();

        BASE64Encoder encoder = new BASE64Encoder();
        imageString = encoder.encode(imageBytes);

        bos.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return imageString.replaceAll("\\n", "");
}
 
Example 3
Source File: FileUtils.java    From paas with Apache License 2.0 6 votes vote down vote up
/**
 * 对文件名发送到客户端时进行编码
 *
 * @param agent
 * @param fileName
 * @author jitwxs
 * @version 创建时间:2018年4月17日 下午4:06:31
 */
private String solveFileNameEncode(String agent, String fileName) {
    String res = "";
    try {
        if (agent.contains("MSIE")) {
            // IE浏览器
            res = URLEncoder.encode(fileName, "utf-8");
            res = res.replace("+", " ");
        } else if (agent.contains("Firefox")) {
            // 火狐浏览器
            BASE64Encoder base64Encoder = new BASE64Encoder();
            res = "=?utf-8?B?"
                    + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";
        } else {
            // 其它浏览器
            res = URLEncoder.encode(fileName, "utf-8");
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return res;
}
 
Example 4
Source File: FileUtils.java    From common-project with Apache License 2.0 6 votes vote down vote up
/**
 * 文件内容转换成base64字符串
 *
 * @param imgFile
 * @return
 */
public static String fileContentToBase64(File imgFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
    byte[] data = null;
    // 读取图片字节数组
    try (
            InputStream in = new FileInputStream(imgFile);
    ) {
        data = new byte[in.available()];
        in.read(data);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    // 返回Base64编码过的字节数组字符串
    return encoder.encode(data);
}
 
Example 5
Source File: Des.java    From hy.common.base with Apache License 2.0 6 votes vote down vote up
/**
 * 获取加密的信息
 * @param str
 * @return
 */
public String encrypt(String str)
{
    //基于BASE64编码,接收byte[]并转换成String
    BASE64Encoder base64Encoder=new BASE64Encoder();
    try {
        // 按UTF8编码
        byte[] bytes = str.getBytes($CHARSETNAME);
        // 获取加密对象
        Cipher cipher = Cipher.getInstance($ALGORITHM);
        // 初始化密码信息
        cipher.init(Cipher.ENCRYPT_MODE, this.key);
        // 加密
        byte[] doFinal = cipher.doFinal(bytes);
        // byte[]to encode好的String并返回
        return base64Encoder.encode(doFinal);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 6
Source File: ImageUtils.java    From jeewx-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 通过网络url获取图片的base64字符串
 *
 * @param imgURL 图片url
 * @return 返回图片base64的字符串
 */
public static String ImageToBase64ByOnline(String imgURL) {
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    try {
        // 创建URL
        URL url = new URL(imgURL);
        byte[] by = new byte[1024];
        // 创建链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(10000);
        InputStream is = conn.getInputStream();
        // 将内容读取内存中
        int len = -1;
        while ((len = is.read(by)) != -1) {
            data.write(by, 0, len);
        }
        // 关闭流
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data.toByteArray());
}
 
Example 7
Source File: AliyunUtil.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
public static String MD5Base64(String s) {
    if (s == null) {
        return null;
    }
    String encodeStr = "";
    byte[] utfBytes = s.getBytes();
    MessageDigest mdTemp;
    try {
        mdTemp = MessageDigest.getInstance("MD5");
        mdTemp.update(utfBytes);
        byte[] md5Bytes = mdTemp.digest();
        BASE64Encoder b64Encoder = new BASE64Encoder();
        encodeStr = b64Encoder.encode(md5Bytes);
    } catch (Exception e) {
        throw new Error("Failed to generate MD5 : " + e.getMessage());
    }
    return encodeStr;
}
 
Example 8
Source File: AliyunUtil.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
public static String MD5Base64(String s) {
    if (s == null) {
        return null;
    }
    String encodeStr = "";
    byte[] utfBytes = s.getBytes();
    MessageDigest mdTemp;
    try {
        mdTemp = MessageDigest.getInstance("MD5");
        mdTemp.update(utfBytes);
        byte[] md5Bytes = mdTemp.digest();
        BASE64Encoder b64Encoder = new BASE64Encoder();
        encodeStr = b64Encoder.encode(md5Bytes);
    } catch (Exception e) {
        throw new Error("Failed to generate MD5 : " + e.getMessage());
    }
    return encodeStr;
}
 
Example 9
Source File: ImageUtils.java    From classchecks with Apache License 2.0 6 votes vote down vote up
/**
 *  将图片文件转化为字节数组字符串,并对其进行Base64编码处理
 * @param path	图片路径
 * @return
 */
public static String covertImageToBase64(String path) {
	byte [] buf = null;
	// 读取图片字节数组
	try {
		InputStream in = new FileInputStream(path);
		buf = new byte[in.available()];
		in.read(buf);
		in.close();
	}catch(IOException e) {
		e.printStackTrace();
	}
	// 对字节数组进行Base64编码
	BASE64Encoder encoder = new BASE64Encoder();
	return encoder.encode(buf); // 返回Base64编码字符串
}
 
Example 10
Source File: ApiController.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 获取token
 */
public Map getAccessToken(String code) throws UnsupportedEncodingException {
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    byte[] authorization = (clientId + ":" + clientSecret).getBytes("UTF-8");
    BASE64Encoder encoder = new BASE64Encoder();
    String base64Auth = encoder.encode(authorization);
    headers.add("Authorization", "Basic " + base64Auth);

    MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
    param.add("code", code);
    param.add("grant_type", "authorization_code");
    param.add("redirect_uri", redirectUri);
    param.add("scope", "app");
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
    ResponseEntity<Map> response = restTemplate.postForEntity(accessTokenUri, request , Map.class);
    Map result = response.getBody();
    return result;
}
 
Example 11
Source File: GZipUtil.java    From pmq with Apache License 2.0 6 votes vote down vote up
public static String compress(String str) {
	if ((str == null) || (str.isEmpty())) {
		return "";
	}
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	try {
		GZIPOutputStream gzip = new GZIPOutputStream(out);
		gzip.write(str.getBytes("UTF-8"));
		gzip.flush();
		gzip.close();
		byte[] tArray = out.toByteArray();
		out.close();
		BASE64Encoder tBase64Encoder = new BASE64Encoder();
		return tBase64Encoder.encode(tArray);
	} catch (Exception ex) {
		logger.error("压缩异常,异常信息:" + ex.getMessage());
	}
	return str;
}
 
Example 12
Source File: Base64Utils.java    From ns4_gear_watchdog with Apache License 2.0 6 votes vote down vote up
/**
 * 在线图片转换成base64字符串
 *
 * @param imgURL	图片线上路径
 * @return
 *
 * @author ZHANGJL
 * @dateTime 2018-02-23 14:43:18
 */
public static String ImageToBase64ByOnline(String imgURL) {
	ByteArrayOutputStream data = new ByteArrayOutputStream();
	try {
		// 创建URL
		URL url = new URL(imgURL);
		byte[] by = new byte[1024];
		// 创建链接
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		InputStream is = conn.getInputStream();
		// 将内容读取内存中
		int len = -1;
		while ((len = is.read(by)) != -1) {
			data.write(by, 0, len);
		}
		// 关闭流
		is.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
	// 对字节数组Base64编码
	BASE64Encoder encoder = new BASE64Encoder();
	return encoder.encode(data.toByteArray());
}
 
Example 13
Source File: RsaUtils.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
/**
 * 公钥加密
 * @param content 要加密的内容
 * @param publicKey 公钥
 */
public static String encrypt(String content, PublicKey publicKey) {
    try{
        Cipher cipher = Cipher.getInstance(CIPHER_INSTANCE);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] output = cipher.doFinal(content.getBytes());
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(output);
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}
 
Example 14
Source File: CkanDataProxy.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getMD5Checksum() {
	logger.debug("IN");
	byte[] checksum = this.createChecksum();
	BASE64Encoder encoder = new BASE64Encoder();
	String encoded = encoder.encode(checksum);
	logger.debug("OUT: returning [" + encoded + "]");
	return encoded;
}
 
Example 15
Source File: Base64.java    From LockDemo with Apache License 2.0 5 votes vote down vote up
public static String getAuthor(String secretKey,String author) {
    byte[] data = null;
    String s = secretKey + author;
    try {
        data = s.getBytes();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // 加密
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data != null ? data : new byte[0]);
}
 
Example 16
Source File: MapCatalogueImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private String mapCatalogue(String user, String operation,String path,String featureName,String mapName) {


String strRet = null;
logger.debug("IN");	 				
	try{
		
		if(operation.equalsIgnoreCase(GET_STANDARD_HIERARCHY)) {
			strRet = getStandardHierarchy();
			if (strRet == null){
				strRet = ERROR_HIERARCHY_NOT_FOUND;
			}
		} else if(operation.equalsIgnoreCase(GET_MAPS_BY_FEATURE)) {
			strRet = getMapsByFeature(featureName);
			if (strRet == null){
				strRet = ERROR_MAP_NOT_FOUND;
			}
		} else if(operation.equalsIgnoreCase(GET_FEATURES_IN_MAP)) {
			strRet = getFeaturesInMap(mapName);
			if (strRet == null){
				strRet = ERROR_FEATURE_NOT_FOUND;
			}	 		
		} else if(operation.equalsIgnoreCase(GET_MAP_URL)) {
			//strRet = getMapUrl(request, mapName);
			strRet = getMapUrl(mapName);
		    // TODO   come fare ???
			if (strRet == null){
				strRet = ERROR_MAP_NOT_FOUND;
			}
	} else if(operation.equalsIgnoreCase(GET_ALL_MAP_NAMES)) {	 			
			strRet = getAllMapNames();
			if (strRet == null){
				strRet = ERROR_MAP_NOT_FOUND;
			}			
		} else if(operation.equalsIgnoreCase(GET_ALL_FEATURE_NAMES)) {	 			
			strRet = getAllFeatureNames();
			if (strRet == null){
				strRet = ERROR_FEATURE_NOT_FOUND;
			}
	}
		else if(operation.equalsIgnoreCase(DOWNLOAD)) {
		   byte[] file=readFile(path);
		   BASE64Encoder bASE64Encoder = new BASE64Encoder();
		   strRet=bASE64Encoder.encode(file);
	}
		return strRet;
	} catch(Exception e) {
		logger.error("Exception", e);
	}finally{
	   logger.debug("OUT");
	}
	
return null;
   }
 
Example 17
Source File: JasperReportRunner.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private byte[] getImagesBase64Bytes(JasperReport report, JasperPrint jasperPrint) {
	logger.debug("IN");
	byte[] bytes = new byte[0];
	try {
		String message = "<IMAGES>";
		List bufferedImages = generateReportImages(report, jasperPrint);
		Iterator iterImgs = bufferedImages.iterator();
		int count = 1;
		while (iterImgs.hasNext()) {
			message += "<IMAGE page=\"" + count + "\">";
			BufferedImage image = (BufferedImage) iterImgs.next();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpeg").next();
			ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
			imageWriter.setOutput(ios);
			IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image), null);
			ImageWriteParam par = imageWriter.getDefaultWriteParam();
			par.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
			par.setCompressionQuality(1.0f);
			imageWriter.write(imageMetaData, new IIOImage(image, null, null), par);

			// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
			// JPEGEncodeParam encodeParam = encoder.getDefaultJPEGEncodeParam(image);
			// encodeParam.setQuality(1.0f, true);
			// encoder.setJPEGEncodeParam(encodeParam);
			// encoder.encode(image);

			byte[] byteImg = baos.toByteArray();
			baos.close();
			BASE64Encoder encoder64 = new BASE64Encoder();
			String encodedImage = encoder64.encode(byteImg);
			message += encodedImage;
			message += "</IMAGE>";
			count++;
		}
		message += "</IMAGES>";
		bytes = message.getBytes();
	} catch (Exception e) {
		logger.error("Error while producing byte64 encoding of the report images", e);
	}
	logger.debug("OUT");
	return bytes;
}
 
Example 18
Source File: JobUploadService.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private void publishOnSpagoBI(EngineStartServletIOManager servletIOManager, String language, String projectName, String jobName) throws IOException, SpagoBIEngineException {
	RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();
	
	String template = getTemplate(language, projectName, jobName);
	
	BASE64Encoder encoder = new BASE64Encoder();
	String templateBase64Coded = encoder.encode(template.getBytes());		
	
	TalendEngineConfig config = TalendEngineConfig.getInstance();
	
	String user = USER;
	String password = PASSWORD;
	Date now = new Date();
	String date = new Long (now.getTime()).toString();
	String label = jobName.toUpperCase();
	if (label.length() > 20) label = label.substring(0,19);
	String name = jobName ;
	String description = language + " job defined in " + projectName  + " project";
	String encrypt = "false";
	String visible = "true";
	String functionalitiyCode = config.getSpagobiTargetFunctionalityLabel();		
	String type = "ETL";
	String state = "DEV";
	
	 HashMap<String, Object> attributes = new HashMap<String, Object>();
	attributes.put("TEMPLATE", templateBase64Coded);
	attributes.put("LABEL", label);
	attributes.put("NAME", name);
	attributes.put("DESCRIPTION", description);
	attributes.put("ENCRYPTED", encrypt);
	attributes.put("VISIBLE", visible);
	attributes.put("TYPE", type);
	attributes.put("FUNCTIONALITYCODE", functionalitiyCode);	
	attributes.put("STATE", state);
	attributes.put("USER", user);
	
	try {
		ContentServiceProxy contentProxy=new ContentServiceProxy(user, servletIOManager.getHttpSession());
	    contentProxy.publishTemplate(attributes);
		//servletIOManager.getContentServiceProxy().publishTemplate(attributes);
		/*
		String spagobiurl = config.getSpagobiUrl();
	    session.setAttribute("BACK_END_SPAGOBI_CONTEXT", spagobiurl);
	    ContentServiceProxy contentProxy=new ContentServiceProxy(user,session);
	    contentProxy.publishTemplate(attributes);
	    */
		
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 19
Source File: JobUploadService.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private void publishOnSpagoBI(FileItem item, JobDeploymentDescriptor jobDeploymentDescriptor) throws ZipException, IOException, SpagoBIEngineException {
	String fieldName = item.getFieldName();
    String fileName = item.getName();
    String contentType = item.getContentType();
    boolean isInMemory = item.isInMemory();
    long sizeInBytes = item.getSize();
    
    if(fieldName.equalsIgnoreCase("deploymentDescriptor")) return;
    
    
    
    RuntimeRepository runtimeRepository = TalendEngine.getRuntimeRepository();
    
    String projectName = jobDeploymentDescriptor.getProject();
    String projectLanguage = jobDeploymentDescriptor.getLanguage().toLowerCase();
    String jobName = "JOB_NAME";
    String contextName = "Default";
    String template = "";
    template += "<etl>\n";
    template += "\t<job project=\"" + projectName + "\" ";
    template += "jobName=\"" + projectName + "\" ";
    template += "context=\"" + projectName + "\" ";
    template += "language=\"" + contextName + "\" />\n";
    template += "</etl>";
    
    BASE64Encoder encoder = new BASE64Encoder();
    String templateBase64Coded = encoder.encode(template.getBytes());		
    
    TalendEngineConfig config = TalendEngineConfig.getInstance();
    
    String user = "biadmin";
	String password = "biadmin";
	String label = "ETL_JOB";
	String name = "EtlJob";
	String description = "Etl Job";
	boolean encrypt = false;
	boolean visible = true;
	String functionalitiyCode = config.getSpagobiTargetFunctionalityLabel();	
	String type = "ETL";
	String state = "DEV";
    
    try {

    	//PublishAccessUtils.publish(spagobiurl, user, password, label, name, description, encrypt, visible, type, state, functionalitiyCode, templateBase64Coded);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    
}
 
Example 20
Source File: SecurityUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Encode a byte array using Base64 alghoritm.
 * 
 * @param bytes bytes to encode
 * 
 * @return String Base64 string of the bytes
 */
public String encodeBase64(byte[] bytes) {
	BASE64Encoder encoder = new BASE64Encoder();
	String encoded = encoder.encode(bytes);
	return encoded;
}